停止服务“处理程序循环代码”不起作用

时间:2017-03-21 08:19:34

标签: android service

我引用了所有类似的问题并尝试了它们,但我无法解决我的问题。我创建了一个服务,这个服务每5秒显示一次toast消息。但我不能阻止这项服务。你可以帮我修理或者不同的方式吗?谢谢。

public class myservice extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    go2sec();
    return super.onStartCommand(intent, flags, startId);
}

private void go2sec() {
    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(myservice.this, "hello", Toast.LENGTH_LONG).show();
            go2sec();
        }
    }, 5000);
}

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

---主动性---

我可以开始服务了;

startService(new Intent(this, myservice.class));

但是,我无法停止服务;

stopService(new Intent(this, myservice.class));

3 个答案:

答案 0 :(得分:1)

您需要删除服务中的处理程序回调。并在服务中致电stopSelf()以阻止它。

以下是代码:

  public class Myservice extends Service {

    final Handler handler = new Handler();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        go2sec();
        return super.onStartCommand(intent, flags, startId);
    }

    private Runnable task = new Runnable () {
        public void run() {
            Toast.makeText(Myservice.this, "hello", Toast.LENGTH_LONG).show();
            go2sec();
        }
    };

    private void go2sec() {
        handler.postDelayed(task, 5000);
    }

    @Override
    public void onDestroy() {
        handler.removeCallbacks(task);   //remove handler
        stopSelf();    //stop the service
        super.onDestroy();
    }

}

答案 1 :(得分:0)

你需要停止你的处理程序。

您必须使用import numpy as np import matplotlib.pyplot as plt # given some mean values and their confidence intervals, means = np.array([30, 100, 60, 80]) conf = np.array([[24, 35],[90, 110], [52, 67], [71, 88]]) # calculate the error yerr = np.c_[means-conf[:,0],conf[:,1]-means ].T print (yerr) # prints [[ 6 10 8 9] # [ 5 10 7 8]] # and plot it on a bar chart plt.bar(range(len(means)), means, yerr=yerr) plt.xticks(range(len(means))) plt.show() 方法在removeCallbacks上致电handler

这应该会使您的服务正常停止。

答案 2 :(得分:0)

找到解决方案:

    public class VolumeService extends Service  {
        boolean running;
        Thread t;

        }

        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

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

        @Override
        public void onDestroy() {
            Log.d("service destroyed", "destroyed");
            running = false;
            super.onDestroy();
        }
       @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        running = true;
        t = new Thread(new Runnable() {
            @Override
            public void run() {
                while (running) {

                        if ("check your condition when you want to start the job") {
                            Log.d("Service", "Service:Started");
                            try {
                                startJob();
                                waitForSometime();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            t.interrupt();
                            Log.d("ServiceStop", "Service:Stopped");
                            running = false;
                        }

                }
            }
        });
        t.start();
        return START_STICKY;
    }

    private void startJob() {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {

               // your logic / business implementation
            }
        });
    }


    }