gpt4 book ai didi

android - 停止服务内的线程

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:55:34 25 4
gpt4 key购买 nike

我在服务中有一个线程,我希望能够在我按下主 Activity 类上的 buttonStop 时停止该线程。

在我的主要 Activity 课上我有:

public class MainActivity extends Activity implements OnClickListener { 
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);

buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
}

public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonStart:
startService(new Intent(this, MyService.class));
break;
case R.id.buttonStop:
stopService(new Intent(this, MyService.class));
break;
}
}
}

在我的服务类(class)中,我有:

public class MyService extends Service {
...
@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onCreate() {
int icon = R.drawable.myicon;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, "notification title", "notification message", pendingIntent);
startForeground(ONGOING_NOTIFICATION, notification);
...
}

@Override
public void onStart(Intent intent, int startid) {
Thread mythread= new Thread() {
@Override
public void run() {
while(true) {
MY CODE TO RUN;
}
}
}
};
mythread.start();
}

停止 mythread 的最佳方法是什么?

另外,我通过 stopService(new Intent(this, MyService.class)); 停止服务的方式是否正确?

最佳答案

您无法停止具有像这样正在运行的不可停止循环的线程

while(true)
{

}

要停止该线程,声明一个 boolean 变量并在 while 循环条件下使用它。

public class MyService extends Service {
...
private Thread mythread;
private boolean running;



@Override
public void onDestroy()
{
running = false;
super.onDestroy();
}

@Override
public void onStart(Intent intent, int startid) {

running = true;
mythread = new Thread() {
@Override
public void run() {
while(running) {
MY CODE TO RUN;
}
}
};
};
mythread.start();

}

关于android - 停止服务内的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14700936/

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