[英]android - How to stop the running thread safely
My application has two activities.我的应用程序有两个活动。 Activity one(A1) starts the thread.活动一(A1)启动线程。 Let's suppose this activity(A1) goes to pause-state.假设此活动 (A1) 进入暂停状态。 I want to stop the running thread safely;我想安全地停止正在运行的线程; how to do this?这该怎么做?
thanks谢谢
you can use return statement in your Threads run method like this...您可以像这样在线程运行方法中使用return语句...
public void run(){
if(isDone)
{
return;
}
}
or you can use this...或者你可以用这个...
if(thread != null)
{
Thread t1 = thread;
thread = null;
t1.interrupt();
}
I would suggest you having a look at the AsyncTask and IntentService .我建议您看看AsyncTask和IntentService 。
//use boolean flag in side run method of Thread
as following // 在Thread
的侧运行方法中使用 boolean 标志,如下所示
boolean isActivityPaused = false;
public void run(){
// use isActivityPaused boolean flag here to stop your Thread
while(!isActivityPaused){
}
}
now this is onPause()
methed of your Activity
现在这是你的Activity
的onPause()
方法
public void onPause(){
isActivityPaused = true; // set isActivityPaused= true to stop your `Thread`
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.