gpt4 book ai didi

android - 停止服务 "handler loop code"不起作用

转载 作者:行者123 更新时间:2023-11-29 01:11:07 25 4
gpt4 key购买 nike

我阅读了所有类似的问题并进行了尝试,但我无法解决我的问题。我创建了一个服务,这个服务每 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();
}
}

--- 主要 Activity ---

我可以开始服务了;

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

但是,我无法停止服务;

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

最佳答案

您需要删除服务中的处理程序回调。并在服务中调用 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();
}

}

关于android - 停止服务 "handler loop code"不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42921602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com