I'm trying to start a service from another service. But wonder what's going wrong. The code is like
class Service1 extends GCMBaseIntentService {
@Override
protected void onMessage(Context arg0, Intent intent) {
Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_LONG).show();
Intent service = new Intent(getApplicationContext(), Service2.class);
startService(service);
}
}
And Service2 is
class Service2 extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Started", Toast.LENGTH_LONG).show();
}
}
I'm getting the Toast "Hello" in Service1 but not getting Toast "Service Started" from Service2
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.
And this is how we'd now start the Service from the second app: Intent intent = new Intent(); intent. setAction("StartSomeService"); startService(intent); That's it!
If you call startService() multiple times, the service will be called with onStartCommand() multiple times, one per call to startService() . Whether it will "restart" will depend upon whether the service was still considered to be running from the previous startService() call.
No, this method is called by the Android system in the main user interface thread, therefore it cannot be called simultaneously from two different threads. A service is only started once, no matter how often you call the startService() method.
Instead of using getApplicationContext()
you should use Service1.this
or getBaseContext()
. Have you declared your Service2 in the AndroidManifest?
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