Start Activity from Service in Android

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);

fail to start activity from service

You cannot do that. This behaviour is discouraged. You are not allowed to interrupt the user when you get a message from the server. The correct behaviour is to show a Notification. The user can then tap on the Notification to view the Activity. This allows the user to decide when and if he wants to see it.

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