Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start context.startService(intent) on Android Pie

Tags:

android

I start a service on my activity's onResume, it worked fine on oreo but lately I have been seeing crashes for Android P, which says "Unable to resume Activity.... Not allowed to start service intent ... app is in background..". Has anyone seen this before and where able to apply fix, any input would be much appreciated.

@Override
public void onResume() {
    super.onResume();
    Timber.v("onResume");
    Intent intent = new Intent(context, Token.class);
    intent.setAction(ACTION_FETCH_TOKEN);
    context.startService(intent);
}

just to add more context, I have not been able to reproduce the crash myself.

like image 690
Mohammed Abdul Bari Avatar asked Sep 18 '18 09:09

Mohammed Abdul Bari


People also ask

What is the difference between startService and startForegroundService?

NO MORE STARTSERVICE - The new context. startForegroundService() method starts a foreground service but with a implicit contract that service will call start foreground within 5 second of its creation. You can also call startService and startForegroundService for different OS version.

How we can start activity and service in Android?

Start a service. An Android component (service, receiver, activity) can trigger the execution of a service via the startService(intent) method. // use this to start and trigger a service Intent i= new Intent(context, MyService. class); // potentially add data to the intent i.

How do I stop programmatically running in the background Android?

By calling stopService() method, The service can stop itself by using stopSelf() method.


1 Answers

On Oreo8+ you cannot start a background service if your application is not "shown", to do that you need to edit your code like below:

    protected void onResume() {
        super.onResume(); context.startForegroundService(intent);
 } 

In onCreate() method of your service class you also need to add:

*EDITED* 2018-09-18 18:15

PendingIntent pIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, MainActivity.class), 0);
Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("My App")
                .setContentText("Doing some work...")
                .setContentIntent(pIntent).build();
startForeground(1000, notification);
like image 80
Legion Avatar answered Oct 04 '22 02:10

Legion