即使用户强制关闭服务,如何自动重启服务? [英] How to automatically restart a service even if user force close it?
问题描述
我想要一个服务在我的应用程序中一直运行.所以我想重新启动它,即使它被用户强制关闭.肯定有办法做到这一点,因为像 facebook 这样的应用程序正在这样做.这不是使用推送通知完成的,即使互联网关闭,Facebook 也会重新启动其服务.
I want a service to run all the time in my application. So I want to restart it even if it is force closed by user. There is definitely a way to do it as apps like facebook are doing it. It's not done using push notification, facebook restarts its service even if internet is off.
推荐答案
首先,强行违背用户意愿运行服务是非常糟糕的模式.
First of all, it is really very bad pattern to run service forcefully against the user's willingness.
无论如何,您可以通过使用 BroadcastReceiver
来重新启动它,该BroadcastReceiver
处理从您的服务的 onDestroy()
发送的广播.
Anyways, you can restart it by using a BroadcastReceiver
which handles the broadcast sent from onDestroy()
of your service.
StickyService.java
public class StickyService extends Service
{
private static final String TAG = "StickyService";
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
sendBroadcast(new Intent("YouWillNeverKillMe"));
}
}
重启ServiceReceiver.java
public class RestartServiceReceiver extends BroadcastReceiver
{
private static final String TAG = "RestartServiceReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.e(TAG, "onReceive");
context.startService(new Intent(context.getApplicationContext(), StickyService.class));
}
}
在清单文件中声明组件:
<service android:name=".StickyService" >
</service>
<receiver android:name=".RestartServiceReceiver" >
<intent-filter>
<action android:name="YouWillNeverKillMe" >
</action>
</intent-filter>
</receiver>
在组件(即Application
、Activity
、Fragment
)中启动StickyService
:
Start the StickyService
in a Component (i.e. Application
, Activity
, Fragment
):
startService(new Intent(this, StickyService.class));
或
sendBroadcast(new Intent("YouWillNeverKillMe"));
这篇关于即使用户强制关闭服务,如何自动重启服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!