我的服务类中有以下线程。public class MyLocalThread extends Thread { @Override public void run() { while (!Thread.interrupted()) { try { //do some work Thread.sleep(4000); } catch (Exception e){ System.out.println("Exception occur" + e.getMessage()); e.printStackTrace(); } } }}当我收到来自MainActivity.java. 我已经建立了BroadcastReceiver服务和活动之间的通信。我像下面这样启动线程。线程开始正常,我收到祝酒词。public class MyReceiver extends BroadcastReceiver { MyLocalThread thread = new MyLocalThread(); @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals("com.example.START")) { //starts the thread thread.start(); Toast.makeText(context, "Service is started.", Toast.LENGTH_LONG).show(); } else if (action.equals("com.example.STOP")) { //stops the thread thread.interrupt(); Toast.makeText(context, "Service has stopped.", Toast.LENGTH_LONG).show(); } }}但是当试图停止我的线程时,iesecond action不起作用。我收到一个 TOAST,表示服务已停止,但我的线程仍在继续运行。它不会终止。我不知道我做错了什么?
2 回答
慕运维8079593
TA贡献1876条经验 获得超5个赞
编辑:
您可以调用thread.interrupt()中断线程并进行Thread.interrupted()检查而不是创建布尔值。
class MyLocalThread extends Thread {
public void run() {
if(!Thread.interrupted()) {
try {
//do some work
}
catch (InterruptedException e) {
System.out.println("InterruptedException occur");
}
}
}
}
像这样中断线程:
MyLocalThread thread = new MyLocalThread();
thread.start();
// when need to stop the thread
thread.interrupt();
添加回答
举报
0/150
提交
取消