新人初學android
發現在退出頁面後該頁面中開啟的線程仍在不停的獲取服務器數據
求幫忙解決問題,希望最好有個Demo可以看看
代碼如下
public class WaterActivity10 extends Activity {
private final int HIGH = 0;
private LineChart mChart1=null;
private TextView Servera1=null;
private LineChart mChart2=null;
private TextView Servera2=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_water10);
Servera1=(TextView) findViewById(R.id.Servera1);
Servera2=(TextView) findViewById(R.id.Servera2);
//refreshChart();
new Thread(){
public void run(){
try {
while (true) {
Thread.sleep(900);
new AnotherTask().execute("JSON");
Log.d("Thread1", "Thread one cnt: ");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}.start();
}
private class AnotherTask extends AsyncTask<String, Void, String> {
@Override
protected void onPostExecute(String result) {
//對UI組件的更新操作
addEntry(mChart1);
addEntry(mChart2);
}
@Override
protected String doInBackground(String... params) {
//耗時的操作
return params[0];
}
}
private void addEntry(LineChart mChart) {
LineData data = mChart.getData();
data.addXValue((data.getXValCount()) + "");
MyApplication app=(MyApplication)getApplication();
int str1= Tools.getnumber(app.getServerAddress());
int str2= Tools.getnumber(app.getServerAddress());
Servera1.setText(String.valueOf(str1)+"號車");
Servera2.setText(String.valueOf(str2)+"t");
}
}
這種寫法不太推薦,提供一個解決你說的問題:設置線程的執行條件,在onDestroy中將條件置成不可執行。
while (true) {}