我嘗試建立一個使用線程內的服務,服務和線程運行良好的android應用程序,但是當我停止並銷燬服務時,線程仍然生活,所以當我再次運行應用程序時,應用程序中有2個線程,所以我想知道我可以如何銷燬線程。 有人可以幫我解決這個問題嗎?Android:線程仍然永久運行,雖然服務已經銷燬
這裏我服務類:
public class MyService extends Service{
Handler handler;
static String toast_msg;
Thread t;
private static final String TAG = "MyService";
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
@Override
public void onStart(Intent intent, int startId) {
/* Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
//Note: You can start a new thread and use it for long background processing from here.*/
toast_msg = "Horas";
super.onStart(intent, startId);
Toast.makeText(getApplicationContext(), toast_msg, Toast.LENGTH_LONG)
.show();
handler = new Handler() {
public void handleMessage(android.os.Message msg) {
super.handleMessage(msg);
Toast.makeText(getApplicationContext(), toast_msg,
Toast.LENGTH_LONG).show();
}
};
t = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
t.sleep(5000);
// Toast.makeText(getApplicationContext(), "Horas",
// Toast.LENGTH_LONG).show();
handler.sendEmptyMessage(0);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
t.start();
}
@Override
public void onDestroy() {
Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
//t.interrupt();
handler.removeCallbacks(t);
super.onDestroy();
t.currentThread().interrupt();
}
}
這確實解決了他眼前的問題,但我已經提出了我認爲會是更好的方法,下面:) – wislon
它的工作和運行良好,我認爲這對其他像我一樣的幫助,謝謝 – user2548784
標誌變量在兩個不同的線程上使用,所以對它的所有訪問都應該同步以保證正確的行爲。 – Kai