Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting service from another service

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

like image 551
Vishal Afre Avatar asked Mar 22 '15 09:03

Vishal Afre


People also ask

Can we start a service from another 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.

How do I start a service from another application?

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!

Can we start the same service twice?

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.

Can a service be started twice Android?

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.


1 Answers

Instead of using getApplicationContext() you should use Service1.this or getBaseContext() . Have you declared your Service2 in the AndroidManifest?

like image 134
Frederik Schweiger Avatar answered Oct 02 '22 13:10

Frederik Schweiger