如何自动重新启动服务,即使用户强制关闭了吗? [英] How to automatically restart a service even if user force close it?

查看:173
本文介绍了如何自动重新启动服务,即使用户强制关闭了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有一个服务运行所有的时间在我的应用程序。所以,我要重新启动它,即使它是由用户关闭力。肯定是有办法做到这一点像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.(Its not done using push notification, facebook restarts its service even if internet is off).

任何帮助将是AP preciated。谢谢!

Any help would be appreciated. Thanks!

推荐答案

首先,它的真的是很糟糕的模式运行服务有力地对用户的意愿

First of all, it is really very bad pattern to run service forcefully against the user's willingness.

不管怎么说,您可以通过使用重启一个 BroadcasteReceiver 它处理从的onDestroy()发送广播您服务。

Anyways, you can restart it by using a BroadcasteReceiver 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"));
    }

}

RestartServiceReceiver.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>

这篇关于如何自动重新启动服务,即使用户强制关闭了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆