在 android studio 中启动服务时 startForeground 错误的错误通知

问题描述

错误信息是: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" 。我多么愚蠢。谢谢你

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...