Context.startForegroundService() did not then call Service.startForeground

前端 未结 3 902
温柔的废话
温柔的废话 2021-01-13 21:38

My app will call startForegroundService(intent) in the onCreate of the MainActivity. And I put startForeground(ON_SERVICE_CONNEC

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-13 22:30

    i had the same problem.
    What helped me in the end, was to initialize the NotificationChannel as early as possible ( i did it in the application class itself) and then create and use the notification in the service.

    I put this in the Application class:

    private void createNotificationChannel() {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            CharSequence name = "MyStreamingApplication";
            String description = "radio";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
            mChannel.setSound(null, null);
            mChannel.enableVibration(false);
            mChannel.setDescription(description);
            notificationManager.createNotificationChannel(mChannel);
        }
    }
    

    and in the onStartCommand method of the service i call:

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) {
            startForeground(NOTIFICATION_ID, createNotification());
        } 
    

提交回复
热议问题