gpt4 book ai didi

java - 停止Android Service创建的线程

转载 作者:行者123 更新时间:2023-12-01 23:46:53 24 4
gpt4 key购买 nike

我目前有一个应用程序,当按下按钮时会启动一个服务,并在该服务内创建一个线程。然后,我有第二个按钮(按下第一个按钮后就会出现),该按钮应该关闭服务并依次杀死线程,下面是我当前的代码,但是服务似乎停止了,但线程仍在继续。

public class MainActivity extends Activity {
private static Button lock = null;
private static Button unlock = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

lock = (Button) this.findViewById(R.id.lock);
unlock = (Button) this.findViewById(R.id.unlock);


lock.setOnClickListener(btn_lock);
unlock.setOnClickListener(btn_unlock);

unlock.setVisibility(View.VISIBLE);
lock.setVisibility(View.GONE);
text.setVisibility(View.GONE);


startService(new Intent(this, MainService.class));
}


private OnClickListener btn_lock = new OnClickListener() {
public void onClick(View v) {
unlock.setVisibility(View.VISIBLE);
lock.setVisibility(View.GONE);

startService(new Intent(MainActivity.this, MainService.class));

}
};

private OnClickListener btn_unlock = new OnClickListener() {
public void onClick(View v) {
unlock.setVisibility(View.GONE);
lock.setVisibility(View.VISIBLE);
stopService(new Intent(MainActivity.this, MainService.class));
}
};


}

然后我的服务类看起来像:

public class MainService extends Service {

Thread 1Thread;

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

@Override
public void onCreate() {
1Thread = new Thread() {
public void run() {
while(true){
try {
Thread.sleep(180000); // 3 minutes
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("TEST", "Thread is still here!");
}
}
};


}

@Override
public void onDestroy() {
1Thread.interrupt();
}

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

1Thread.start();
}

}

希望有人可以提供帮助,如果您需要更多信息,请告诉我!

最佳答案

  boolean mStatus = true;

@Override
public void onCreate() {
1Thread = new Thread() {
public void run() {
while (mStatus) {
try {
Thread.sleep(180000); // 3 minutes
} catch (InterruptedException e) {
e.printStackTrace();
continue;

}
Log.i("TEST", "Thread is still here!");

}
};


}



@Override
public void onDestroy() {
mStatus = false;
1Thread.interrupt();
}

关于java - 停止Android Service创建的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16896644/

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