我的服务类中有以下线程。
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,表示服务已停止,但我的线程仍在继续运行。它不会终止。我不知道我做错了什么?
慕运维8079593
皈依舞
相关分类