Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start an Activity from a Service?

Tags:

android

Is it possible to start an Activity from a Service? If yes, how can we achieve this?

like image 218
SpunkerBaba Avatar asked Aug 11 '10 07:08

SpunkerBaba


People also ask

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 start a service from another service?

Starting a service You can start a service from an activity or other application component by passing an Intent to startService() or startForegroundService() . The Android system calls the service's onStartCommand() method and passes it the Intent , which specifies which service to start.


1 Answers

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.

like image 50
Marcin Gil Avatar answered Oct 15 '22 01:10

Marcin Gil