问题描述
错误信息是:android.app.RemoteServiceException: Bad notification for startForeground
也不知道是否值得一提,但该服务在mac os上正常启动。
我的代码:
public class App extends Application {
public static final String CHANNEL_ID = "serviceChannel";
@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,"Service Channel",notificationmanager.IMPORTANCE_DEFAULT
);
notificationmanager manager = getSystemService(notificationmanager.class);
manager.createNotificationChannel(serviceChannel);
}
}
public class NotificationActivity extends AppCompatActivity {
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_service);
editText = findViewById(R.id.editText);
}
public void startService(View v) {
String input = editText.getText().toString();
Intent serviceIntent = new Intent(this,NotificationService.class);
serviceIntent.putExtra("inputExtra",input);
ContextCompat.startForegroundService(this,serviceIntent);
}
public void stopService(View v) {
Intent serviceIntent = new Intent(this,NotificationService.class);
stopService(serviceIntent);
}
}
通知服务
public class NotificationService extends Service {
@Override
public int onStartCommand(Intent intent,int flags,int startId) {
String input = intent.getStringExtra("inputExtra");
Intent notificationIntent = new Intent(this,NotificationActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,notificationIntent,0);
Notification notification = new NotificationCompat.Builder(this,CHANNEL_ID)
.setContentTitle("Reminder")
.setContentText(input)
.setSmallIcon(R.drawable.ic_android)
.setContentIntent(pendingIntent)
.build();
startForeground(1,notification);
//do heavy work on a background thread
//stopSelf();
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
解决方法
所以我的问题是,我忘了在清单中添加 android 名称: android:name=".notificationService.App" 。我多么愚蠢。谢谢你