保持服务运行(Keep Service running)

2019-06-17 18:45发布

谁能告诉我要保持服务始终运行或重新启动本身,当用户关闭它的方法是什么? 我看过Facebook的服务重新启动时,我清晰的记忆。 我不想做ForegroundServices。

Answer 1:

您应该创建一个棘手的服务。 了解更多关于它在这里 。

您可以通过在onStartCommand返回START_STICKY做到这一点。

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("LocalService", "Received start id " + startId + ": " + intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
}

还阅读应用:持续性 ,这是“应用程序是否应该保留在任何时候运行”。 这是比较麻烦 - 系统会尽量不杀你的应用程序,它会在系统中影响别人,你应该使用它要小心。



Answer 2:

我复制这从我的应用我之前使用的服务。

其重要不更新任何UI。 因为你的服务没有用户界面。 这也适用于祝酒词为好。

祝好运

public class nasserservice extends Service {
    private static long UPDATE_INTERVAL = 1*5*1000;  //default

    private static Timer timer = new Timer(); 
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate(){
        super.onCreate();
        _startService();

    }   

    private void _startService()
    {      
        timer.scheduleAtFixedRate(    

                new TimerTask() {

                    public void run() {

                        doServiceWork();

                    }
                }, 1000,UPDATE_INTERVAL);
        Log.i(getClass().getSimpleName(), "FileScannerService Timer started....");
    }

    private void doServiceWork()
    { 
        //do something wotever you want 
        //like reading file or getting data from network 
        try {
        }
        catch (Exception e) {
        }

    }

    private void _shutdownService()
    {
        if (timer != null) timer.cancel();
        Log.i(getClass().getSimpleName(), "Timer stopped...");
    }

    @Override 
    public void onDestroy() 
    {
        super.onDestroy();

        _shutdownService();

        // if (MAIN_ACTIVITY != null)  Log.d(getClass().getSimpleName(), "FileScannerService stopped");
    }

}


文章来源: Keep Service running