保持服务正常运行

时间:2012-08-18 07:04:08

标签: android service

当用户关闭服务时,有人能告诉我保持服务始终运行或重启的方法吗?当我清除内存时,我看到facebook服务重启了。 我不想制作ForegroundServices。

2 个答案:

答案 0 :(得分:28)

您应该创建一个粘性服务。阅读更多相关信息here

您可以通过在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;
}

另请阅读application:persistent,即“应用程序是否应始终保持运行”。这更麻烦 - 系统会尽量不杀死你的应用程序,这将影响系统中的其他人,你应该小心使用它。

答案 1 :(得分:8)

我是通过我之前使用的应用程序中使用的服务复制的。

重要的是不要更新任何UI。因为您在服务中没有用户界面。这也适用于Toasts。

祝你好运

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");
    }

}
相关问题