新人初学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) {}
应该没必要开子线程里再开启异步任务吧,本来异步任务就是线程池+Handler。
你可以写成这样:
AnotherTask anotherTask = new AnotherTask();
anotherTask .execute("JSON");//执行异步任务
这两句完全可以取代New Thread(...).start()这部分;
在Activity退出时:
onDestroy(){
anotherTask.cancel();//取消异步任务
}
你已经使用了意不任务,就没必要再自己开启一个线程
new AnotherTask().execute("JSON");
这句话直接在oncreat()里面执行就行
一般不建议直接在UI里开启线程。
在AsyncTask中一般有三个抽象方法需要重写onPreExecute(),doInBackground,onPostExecute,分别是任务执行前,执行和执行后的操作,
像你UI创建的那个线程里的睡眠操作可以在onPreExecute()中进行,像提示框等之前操作也可以放里面。
最后取消也是和楼上说的一样。在ondestory()中操作。
还有就是在doInBackground()中才是耗时操作,onPostExecute()中是进行后续操作,和UI线程对接的一些方法可以放里面。
使用线程池管理,退出去后将线程池的任务终结。