我剛剛在Android上開始了一個簡單的線程處理程序。代碼起作用。唯一的部分是如何關閉處理程序。我試圖關閉處理程序onPause(),但它只是繼續運行。有什麼建議麼?如何在Android中停止線程處理程序?
下面是代碼: 我的主要活動主題:
package com.test.prog;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
public class AndroidThreadProgv1Activity extends Activity {
private Handler DataHandler;
private DataUpdater du;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* Initialize handler to allow UI updating in other threads */
DataHandler = new Handler();
startDataUpdater();
}
public void onPause(){
super.onPause();
du.stopConnection();
}
private void startDataUpdater(){
System.out.println("In startDataUpdater");
du = new DataUpdater(DataHandler,(TextView) findViewById(R.id.textView1));
du.start();
}
}
DataUpdater.java:
package com.test.prog;
import java.io.IOException;
import android.os.Handler;
import android.os.Looper;
import android.widget.TextView;
/*
* Data updater thread. Updates the display with the response.
*/
public class DataUpdater extends Thread{
/*Handler for the UI update*/
private Handler dataRefreshHandler;
/*The UI text displaying the data*/
private TextView dataLabel;
/*data value*/
private int data = 0;
/*data update rate in ms*/
private static final int dataUpdateRate = 2000;
private boolean stoppedFlag= false;
public DataUpdater(Handler handler, TextView tv){
this.dataRefreshHandler = handler;
this.dataLabel = tv;
}
public void stopConnection()
{
if(this.dataRefreshHandler != null) {
this.dataRefreshHandler.removeMessages(data); // Remove a delayed message
System.out.println("In stopConnection");
/*
if(!stoppedFlag){
this.dataRefreshHandler.getLooper().quit(); // Warning
stoppedFlag = true;
}
*/
}
}
@Override
public void run(){
try {
while(true){
System.out.println("In run");
data = data + 1;
updateData();
Thread.sleep(dataUpdateRate);
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
/*
* Calls the UI Handler and updates the display
*/
private void updateData(){
dataRefreshHandler.post(new Runnable() {
public void run() {
if(data==0)
{
dataLabel.setText("Value not known");
}
else
{
System.out.println("In update");
dataLabel.setText("Value="+data);
}
}
});
}
}
如何使用'runOnUiThread()'而不是創建一個Handler? – Dalmas