我有一個Android應用程序,它有一個運行線程的類。基本上與here一樣。Android應用程序 - 簡歷線程
當前的線程每500毫秒更新一次計算值的文本視圖並另外記錄該值,所以我可以在adb-logcat中看到它。
當我用設備的後退按鈕退出我的應用程序時,線程仍然在後臺運行。 (這是我想要的)。 adb-logcat仍然給出了線程正在計算的值。
但是當我重新打開應用程序,textview不再更新!
當我再次打開應用程序時,我必須做什麼,它恢復更新textview?
這裏是我的簡化代碼:
SensorProcessor.java
public class SensorProcessor implements Runnable {
protected Context mContext;
protected Activity mActivity;
private volatile boolean running = true;
//Tag for Logging
private final String LOG_TAG = SensorProcessor.class.getSimpleName();
public SensorProcessor(Context mContext, Activity mActivity){
this.mContext = mContext;
this.mActivity = mActivity;
}
public void run() {
while (running){
try {
final String raw = getSensorValue();
mActivity.runOnUiThread(new Runnable() {
public void run() {
final TextView textfield_sensor_value;
textfield_sensor_value = (TextView) mActivity.findViewById(R.id.text_sensor);
textfield_sensor_value.setText("Sensor Value: " + raw); // <-------- Does not update the field, when app resumes
Log.v(LOG_TAG, raw); // <-------- Still working after the app resumes
}
});
Thread.sleep(100);
} catch (InterruptedException e) {
//When an interrupt is called, we set running to false, so the thread can exit nicely
running = false;
}
}
Log.v(LOG_TAG, "Sensor Thread finished");
}
}
MainActivity.java
public class MainActivity extends Activity implements OnClickListener, OnInitListener {
//Start the Thread, when the button is clicked
public void onClick(View v) {
if (v.getId() == R.id.button_start) {
runnable = new SensorProcessor(this.getApplicationContext(),this);
thread = new Thread(runnable);
thread.start();
}
}
將onDestroy方法設置運行標誌爲false – SKT
您需要顯示代碼在哪裏以及如何創建新的'Thread'以及創建'runnable'的位置。 – eleven
添加了代碼,我在那裏創建新的線程 –