gpt4 book ai didi

java - 在 MainActivity 中调用 stopService() 时线程不会停止

转载 作者:太空宇宙 更新时间:2023-11-03 11:09:05 25 4
gpt4 key购买 nike

主要 Activity

public class MainActivity extends ActionBarActivity {

Context c=this;
Intent i;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b=(Button)findViewById(R.id.button1);
Button b1=(Button)findViewById(R.id.button2);

b.setOnClickListener(new OnClickListener() {

public void onClick(View v)
{
i=new Intent(c,serv.class);
startService(i);
}
});

b1.setOnClickListener(new OnClickListener()
{

public void onClick(View v) {

stopService(i);

}
});
}
}

服务

class bob implements Runnable{
Thread ac;

public void run()
{
while(true)
{
Log.d("tag","RUNNING");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

} }
public class serv extends Service {
Thread ac;


public void onCreate() {
Log.d("tag","CREATED");
super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("tag","SERVICE STARTED");

ac=new Thread(new bob());
ac.start();


return Service.START_NOT_STICKY;

}

@Override
public void onDestroy() {
Log.d("tag","DESTROYED");
try{
ac.stop();
}catch(Exception e)
{e.printStackTrace();}


}

public IBinder onBind(Intent arg0) {
return null;
}

}

当我单击 StopService 按钮时,将调用 ondestroy() 消息,但我的线程继续运行。日志如下:

03-26 16:48:45.065: D/tag(15674): CREATED

03-26 16:48:45.065: D/tag(15674): SERVICE STARTED

03-26 16:48:45.065: D/tag(15674): RUNNING

03-26 16:48:45.495: D/tag(15674): RUNNING

03-26 16:48:46.065: D/tag(15674): RUNNING

03-26 16:48:46.495: D/tag(15674): RUNNING

03-26 16:48:47.065: D/tag(15674): RUNNING

03-26 16:48:47.495: D/tag(15674): RUNNING

03-26 16:48:48.065: D/tag(15674): RUNNING

03-26 16:48:48.505: D/tag(15674): RUNNING

03-26 16:48:48.615: D/tag(15674): DESTROYED

03-26 16:48:49.065: D/tag(15674): RUNNING

03-26 16:48:49.495: D/tag(15674): RUNNING

最佳答案

试试这个..

class bob implements Runnable{
Thread ac;
boolean isRunning = true;
public void run()
{
while(isRunning)
{
Log.d("tag","RUNNING");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
public void stopRunning()
{
isRunning = false;
}

并且在您的服务中引用可运行对象并调用 stopRunning() 方法...

关于java - 在 MainActivity 中调用 stopService() 时线程不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29277148/

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