Question

I've got a Service in my Android application. During onStartCommand, I pass the Service object to another class. Then, from there, there's a thread that after 30 seconds starts another Service. It is something like this:

public class FooService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        MyClass mc = new MyClass(this);
        mc.testMethod();
        stopSelf();
        return START_NOT_STICKY;
    }
}

And this is MyClass:

public class MyClass {

    private Service service;

    public MyClass(Service service) {
        this.service = service;
    }

    public void testMethod() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(20*1000);
                    Intent intent = new Intent(service, BarService.class);
                    service.startService(intent);
                }
                catch (Exception e) {
                    // CATCH!
                }
            }
        }).start();
    }
}

Now, as you can see, in FooService I call stopSelf() wich destroys that Service object. By the way MyClass has got a copy of that Service that was passed by value. After 20 seconds, we can start BarService from MyClass. I've tested it and it works but I can't understand why! The way I wrote the code is dirty (for me). Is it correct to start another service from one that was destroyed? Thank you for your help.

Was it helpful?

Solution

I've tested it and it works but I can't understand why

It works today on the environments you tested in. It may not work in all environments (e.g., ROM mods) and may not work tomorrow (e.g., Android OS updates). A destroyed Context, such as your stopped service, should not be used for anything. It happens that presently you can still use it to call startService() later, but that behavior is not guaranteed.

Is it correct to start another service from one that was destroyed?

No. In this case, I fail to see why you need two services in the first place.

I've got a copy of that service

No, you do not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top