Reputation: 1040
My app is supposed to receive time in seconds that determines how audio is played.
Example: Play audio file x(length about 2 seconds) every 2 minutes all in all 16 times.
It would work great if android didn't enjoy closing foreign apps and services so frequently, once you move to another app.
My structure is like this:
MainActivity
starts a new MainActivityService
via intent
.
gintent = new Intent(MainActivity.this,MainActivityService.class);
gintent.putExtra(...);
gintent.putExtra(...);
...
startService(gintent);
Then this service runs the mentioned time being given to it by putExtra.
The point is, android has all kinds of mechanisms to kill services and apps. So I have been trying to keep it up by using onSaveInstanceState in MainActivity
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean(...);
savedInstanceState.putInt(...);
...
}
onRestoreInstanceState
, isMyServiceRunning(MainActivityService.class)
and so forth, but I lost track with all the onResume and whatnot. And in the end, the service was still killed.
I don't want to debug this back and forth. I want to know the gold standard how to do this.
Upvotes: 1
Views: 73
Reputation: 766
Android treats nonforegrounded services as ripe for killing. You'll need to make your Service flag itself as a foreground service. This will lower the chance the OS will kill that process.
A foreground service is a service that the user is actively aware of and is not a candidate for the system to kill when low on memory.... To request that your service run in the foreground, call startForeground().
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification =
new Notification.Builder(this, CHANNEL_DEFAULT_IMPORTANCE)
.setContentTitle(getText(R.string.notification_title))
.setContentText(getText(R.string.notification_message))
.setSmallIcon(R.drawable.icon)
.setContentIntent(pendingIntent)
.setTicker(getText(R.string.ticker_text))
.build();
startForeground(ONGOING_NOTIFICATION_ID, notification);
See: Running a service in the foreground
Upvotes: 1