[英]Retain a background service after android app update
我的后台服务执行我的应用程序的核心功能,并在UI打开时首先启动。
因此,当在Play商店更新应用程序时,该服务将被终止,但UI可能无法再次打开(所以我猜服务也不会再次启动)。这对我不利,因为该服务执行的核心功能应用程序。 我该如何克服这个问题?
非常感谢任何帮助
是每一个应用程序被打死时更新是指我的答案在这里
您可以将服务作为STICKY服务,这项服务在被杀时重新启动。来自文档 :
public static final int START_STICKY在API级别5中添加
从onStartCommand(Intent,int,int)返回的常量:如果此服务的进程在启动时被终止(从onStartCommand(Intent,int,int)返回后),则将其保留在启动状态但不保留此状态交付意图。 稍后系统将尝试重新创建服务。 因为它处于启动状态,所以它将保证在创建新服务实例后调用onStartCommand(Intent,int,int); 如果没有任何挂起的启动命令要传递给服务,则将使用null intent对象调用它,因此您必须注意检查这一点。
您可以尝试的另一件事是检测应用更新并再次启动服务 。要检测应用更新,您可以收听PACKAGE_INSTALL广播或使用以下解决方法:
您的服务将在升级期间被终止。 您需要捕获升级事件并再次启动它。
在Manifest.xml中
<receiver android:name=".yourpackage.UpgradeReceiver" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
</intent-filter>
</receiver>
在UpgradeReceiver.java中
public class UpgradeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
if (!Intent.ACTION_MY_PACKAGE_REPLACED.equals(intent.getAction()))
return;
// Start your service here.
} catch (Exception e) {
Utils.handleException(e);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.