我有一个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
添加了代码,我在那里创建新的线程 –