开发者

Android: stop services and alarms when the application ends

开发者 https://www.devze.com 2023-01-10 15:14 出处:网络
I have an application that consist of several Activities.When the application starts, some alarms are scheduled using AlarmManager and some services are started:开发者_如何学Go

I have an application that consist of several Activities. When the application starts, some alarms are scheduled using AlarmManager and some services are started:开发者_如何学Go

AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
a.setInexactRepeating(...)
....

I would like to know any way to guarantee every service is stopped and every alarm is unscheduled when the user exits the application.

The problem is that the user can leave the application from different Activities, and I don't like the idea of overriding the onDestroy method in every Activity. Is there any known Intent I can receive when the application ends?

I've also found that an Android application can have a class that extends from Application, with a onTerminate method:

public class MyApplication extends Application { 
    @Override
    public void onTerminate() {
        ...
    }
}

But the documentation is very clear: "never depend on this method being called; in many cases an unneeded application process will simply be killed by the kernel without executing any application code"

Any suggestion is highly appreciated.


I would like to know any way to guarantee every service is stopped and every alarm is unscheduled when the user exits the application.

There is no such thing as "user exits the application" in Android.

Is there any known Intent I can receive when the application ends?

No.

I've also found that an Android application can have a class that extends from Application, with a onTerminate method

This will be called, in many cases, sometime after there are no more running components. In your case, there are running components (services).

But the documentation is very clear: "never depend on this method being called; in many cases an unneeded application process will simply be killed by the kernel without executing any application code"

The only case I know of when it will not be called is if the process is being terminated, in which case your service will be eliminated as well, though scheduled alarms will not.

0

精彩评论

暂无评论...
验证码 换一张
取 消