简体   繁体   中英

How to start the automatically stopped android service?

I have written a service, it runs at start up, but suddenly due to some run time errors the service is stopping. How can I re run the automatically stopped service (because of run time exception).

there is a

stopSelf()
stopSelf(startId)

method in service which you can use to stop a service from inside.

EDIT

i guess i need some rest.

well if you want to find if a service is stopping due to some runtimeexecption

can you try

    private Thread.UncaughtExceptionHandler onRuntimeError= new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread thread, Throwable ex) {
            //Try starting the service again
                    //May be a pending intent might work
    };

in your on create

    @Override
    protected void onCreate() { 
        super.onCreate();
        Thread.setDefaultUncaughtExceptionHandler(onRuntimeError);  
    }

Maybe you could get a second service that monitors the first service, and restarts it if its stops responding. I think that is basically what the watchdog in Android does for the system-services.

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