How to Start an Activity from a Service

Start Activity from Service in Android

From inside the Service class:

Intent dialogIntent = new Intent(this, MyActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);

But, this does not work from Android 10+ due to battery optimisation restrictions

How to start an Activity from a Service?

android.app.Service is descendant of android.app.Context so you can use startActivity directly. However since you start this outside any activity you need to set FLAG_ACTIVITY_NEW_TASK flag on the intent.

For example:

Intent i = new Intent();
i.setClass(this, MyActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);

where this is your service.

Start Activity from service android

Use this code It will help you.

Intent i = new Intent(context,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);

//More Clarification
Firstly check your app is running or not.
If your Application is not running then call this code.

 Intent i = new Intent(context,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);

If running then use this code

Intent i = new Intent(context,MainActivity.class);    
context.startActivity(i);

Android start an activity from a service

If your app targets API level 29 or higher, you cannot launch an Activity from a Service if the Service is in the background and the app has not got any existing activities (which is the case when the app is not running, as you've seen). This restriction was added in API level 29 to reduce UI interference from background apps. See https://developer.android.com/guide/components/activities/background-starts for an explanation of the exact conditions that are necessary to allow a background Service to launch an Activity.

To verify that this is your problem, change your targetSDK to 28 or lower and see if the problem goes away.

how to start activity from android service

If you want to distribute your code through a jar, you need to add the activity on the manifest in the app which will include the jar.

The only way to start an activity is to include it in a manifest.



Related Topics



Leave a reply



Submit