简体   繁体   English

Android服务正在停止,如何通知应用程序?

[英]Android service being stopped, how to notify applications?

I have an application which works like a framework - other apps can register a PendingIntent with my app which triggers them at some point in the future. 我有一个像框架一样工作的应用程序-其他应用程序可以向我的应用程序注册PendingIntent,这会在将来某个时候触发它们。 I am keeping the PendingIntents in an array list in a service and then iterating over them to trigger. 我将PendingIntents保留在服务的数组列表中,然后遍历它们以进行触发。 To register an intent the application calls "startService()" with a PendingIntent set within the intent bundle. 要注册意图,应用程序将在意图包中设置PendingIntent的情况下调用“ startService()”。

At some point, my service is being closed - or more specifically my array list is being emptied (which can only happen by Android killing the service) and as such I loose my PendingIntents for the registered apps. 在某个时候,我的服务已关闭-更具体地说,我的阵列列表已清空(这只能通过Android终止该服务来实现),因此,我为已注册的应用程序释放了PendingIntents。

How can I keep my service alive, or more specifically keep my PendingItents from being lost? 如何保持服务的生命力,或更具体地说,使我的PendingItents不会丢失? I don't want to go against the Android system mechanisms and create a hacky effort, I would like to know the way in which Google think this should be done. 我不想违背Android系统机制并做出骇人的努力,我想知道Google认为应该这样做的方式。

Have you tried with START_STICKY ? 您尝试过START_STICKY吗?

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    // Put your code here
    return START_STICKY;
}

You can try START_REDELIVER_INTENT 您可以尝试START_REDELIVER_INTENT

When a service is killed, it's onDestroy() method is called. 服务被杀死时,将调用onDestroy()方法。 You could probably over-ride the onDestroy() method and do something like: 您可能会改写onDestroy()方法并执行以下操作:

public void onDestroy(){
Intent intent = new Intent();
intent.setAction("SERVICESTOPPED");
sendBroadcast(intent);
super.onDestroy();  
}   

Have a BroadcastReceiver that listens to this intent and handle the situation as and when it happens. 有一个BroadcastReceiver可以侦听此意图并在情况发生时进行处理。 Alternatively, in the onstartCommand(), if you specify the return value as START_STICKY, the OS will restart your service if it gets killed by OS. 或者,在onstartCommand()中,如果您将返回值指定为START_STICKY,则如果操作系统将其终止,则操作系统将重新启动您的服务。 Generally this happens with long running serices 通常,这种情况发生在长期运行的服务中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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