App停止时服务停止

时间:2017-03-14 17:58:04

标签: android service

当我关闭App服务停止运行时, 我试过START_STICKY但仍然无法正常工作。 我需要在服务器响应时显示通知

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Timer timer = new Timer();
    timer.schedule(new Receive(), 0, 5000);

    return START_STICKY;
}

这是我的enitre课程 http://justpaste.it/14gqd

2 个答案:

答案 0 :(得分:0)

您需要将其与通知绑定。然后系统允许运行服务。

@Override
public int onStartCommand(Intent intent, int flags, int startId){
startForeground(999, bindService()/*function to return notification*/);
return START_REDELIVER_INTENT;
}

和此函数返回通知。

protected Notification bindService(){
    Notification.Builder mBuilder = new Notification.Builder(this);

    /*customize notification builder here*/

    return mBuilder.build();
}

答案 1 :(得分:0)

服务因活动被破坏而被杀死,你可能想看看JobScheduler 使用TimerTask(易于实施)

计时器任务示例

    @Override
        public void onStart(Intent intent, int startId) {
            // Perform your long running operations here.

            //Creating new thread for  service
            //Always write your long running tasks in a separate thread, to avoid ANR
        final Handler handler = new Handler();
         timer = new Timer();
        TimerTask task = new TimerTask() {

            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {


                        Log.i(TAG, "Service running");

                    }
                });
            }
        };
        timer.scheduleAtFixedRate(task, 0, 10000); // Executes thetask every 5 seconds.