Is it possible to start an Activity from a Service? If yes, how can we achieve this?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With