Skip to content Skip to sidebar Skip to footer

Should I Use StartService Or StartForegroundService For API >= 26?

I'm a bit confused because i read some posts where i'm supposed too use ContextCompat.StartForegroundService(); if the API is >= 26. Now I still just use StartService and it wor

Solution 1:

startService will not work for api >=26

You can change your service to foreground service with help of following code. It will show the notification.

private void runAsForeground(){
Intent notificationIntent = new Intent(this, MediaPlayerService.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
        notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

Notification notification=new NotificationCompat.Builder(this)
                            .setSmallIcon(R.drawable.ic_launcher)
                            .setContentText(getString(R.string.isRecording))
                            .setContentIntent(pendingIntent).build();

startForeground(NOTIFICATION_ID, notification);
}

for more reference - https://android-developers.googleblog.com/2018/12/effective-foreground-services-on-android_11.html

https://developer.android.com/guide/components/services

another way (not recommended.. target sdk must be 26 or less)

public static void startService(Context context, Class className) {
    try {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            Intent restartServiceIntent = new Intent(context, className);
            restartServiceIntent.setPackage(context.getPackageName());
            PendingIntent restartServicePendingIntent = PendingIntent.getService(context, 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
            AlarmManager alarmService = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            if (alarmService != null) {
                alarmService.set(
                        AlarmManager.ELAPSED_REALTIME,
                        SystemClock.elapsedRealtime() + 500,
                        restartServicePendingIntent);
            }
        } else {
            Intent i = new Intent(context, className);
            context.startService(i);
        }
    } catch (Exception e) {
        MyLog.e(TAG, "startService: ", e);
    }
}

Call by

 startService(context,MediaPlayerService.class);

Post a Comment for "Should I Use StartService Or StartForegroundService For API >= 26?"