简体   繁体   中英

Service onDestroy called without onStartCommand

I'm getting reports of a NullPointerException when the onDestroy() service method gets called. The part that i don't understand is that i always start the service with a Context.startService() so the onStartCommand() should always be called and the reference should never be null.

It is worth mentioning, that the NullPointerException doesn't happen when i shutdown the service with Context.stopService() call.

So my conclusion is that the framework is calling onDestroy() without having called onStartCommand() . I'm guessing that the Service might be being destroyed, and restarted by the framework so onStartCommand() doesn't actually gets executed. But again, this is me just guessing.

Any ideas on what might be going on here? Thanks!

Here's the relevant code:

public class ServiceLocationListener extends Service 

    private NotificationManager mNotificationManager;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        mNotificationManager = getService(this, Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(SOME_NOTIFICATION_ID, someNotification);
        ...
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        mNotificationManager.cancel(SOME_NOTIFICATION_ID);  <<<<<<<<< NPE
        ...
    }
}

Put mNotificationManager = getService(this, Context.NOTIFICATION_SERVICE); in onCreat() of service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM