Reputation: 1511
I have a media player service that gets killed everytime the user clears recent apps. I want the service to continue playing on the background. I have tried
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
return START_STICKY;
}
and
mediaPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK);
but it's not working. How do I solve this?
Upvotes: 0
Views: 2009
Reputation: 915
Google did some updates:
Some of those updates included security and it reached the services. This means that we can no longer perform lengthy operations in the background without notifying the user.
Foreground A foreground service performs some operation that is noticeable to the user. For example, an audio app would use a foreground service to play an audio track. Foreground services must display a Notification. Foreground services continue running even when the user isn't interacting with the app.
Background A background service performs an operation that isn't directly noticed by the user. For example, if an app used a service to compact its storage, that would usually be a background service. Note: If your app targets API level 26 or higher, the system imposes restrictions on running background services when the app itself isn't in the foreground. In most cases like this, your app should use a scheduled job instead.
Make sure to call startForeground as soon as possible
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
//do heavy work on a background thread
//stopSelf();
return START_STICKY;
}
This is how you start the foreground service:
public void startService() {
Intent serviceIntent = new Intent(this, ForegroundService.class);
serviceIntent.putExtra("inputExtra", "Foreground Service Example in Android");
ContextCompat.startForegroundService(this, serviceIntent);
}
Upvotes: 3
Reputation: 1131
As specified in Mr.Patel answer,
Many of the manufactures wont allow running of background service when frontend Activity is not running or removed from the recent list.
There is a way of achiving your requirement.
You can run your service in the background by setting a non cancellable notification from your application. Till you close your notification forcefully programatically using a close button, your service will be running in the background.
Hope this will solve your problem.
Upvotes: 1