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.
privatevoidrunAsForeground(){
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)
publicstaticvoidstartService(Context context, Class className) {
try {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
IntentrestartServiceIntent=newIntent(context, className);
restartServiceIntent.setPackage(context.getPackageName());
PendingIntentrestartServicePendingIntent= PendingIntent.getService(context, 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManageralarmService= (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (alarmService != null) {
alarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 500,
restartServicePendingIntent);
}
} else {
Intenti=newIntent(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?"