Oreo - Starting a service in the foreground

后端 未结 2 522
难免孤独
难免孤独 2020-12-17 23:40

I have created a service that tracks the device\'s location as it moves. The service is started in by an Activity that binds to it, and in this activity there is a \"Start T

相关标签:
2条回答
  • 2020-12-18 00:04

    Try to change your startInForeground() method with this code:

    private void startInForeground() {
            Intent notificationIntent = new Intent(this, WorkoutActivity.class);
            PendingIntent pendingIntent=PendingIntent.getActivity(this,0,notificationIntent,0);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this,NOTIFICATION_CHANNEL_ID)
                    .setSmallIcon(R.drawable.shsl_notification)
                    .setContentTitle("TEST")
                    .setContentText("HELLO")
                    .setTicker("TICKER") 
                    .setContentIntent(pendingIntent);
            Notification notification=builder.build();
            if(Build.VERSION.SDK_INT>=26) {
                NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
                channel.setDescription(NOTIFICATION_CHANNEL_DESC);
                NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.createNotificationChannel(channel);
            }
            startForeground(NOTIFICATION_ID, notification);
    }
    

    So, when your Android version is Oreo (or higher) notification channel will be created, otherwise not.

    0 讨论(0)
  • 2020-12-18 00:28

    Before show notification you have to create notification channel:

    private void createNotificationChannel() {
        if (Build.VERSION_CODES.O <= Build.VERSION.SDK_INT) {
            NotificationChannel notificationChannel =
                    new NotificationChannel(PRIMARY_CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(notificationChannel);
        }
    }
    

    and then change create notification builder

    new Notification.Builder(context, PRIMARY_CHANNEL_ID)
    
    0 讨论(0)
提交回复
热议问题