0

在 android 应用程序中使用 asynctask runner 时,我在每 5 秒后在 while 循环中运行 asynctaskrunner 以在文本视图中显示 gps 坐标时感到有些震惊。

包 com.example.gpsproject;

import android.content.Context;
import android.location.Location;
import android.os.AsyncTask;
import android.widget.TextView;
public class AsyncTaskRunner extends AsyncTask<Void,Void,Void> {


    private final Context mContext;
    TextView latitude,longitude;


 public AsyncTaskRunner(Context c,TextView lat,TextView lon) {
    // TODO Auto-generated constructor stub
     mContext = c;
     latitude = lat;
     longitude = lon;

}
 Location a = new Location("zfcdha");
 String lonii,latii;


 private void sleep(int i) {
    // TODO Auto-generated method stub

}


 protected void onPostExecute() {


 }


 @Override
 protected void onPreExecute() {

 }



protected Void doInBackground(Void... params) {

  try {
      GPSTracker mytracker = new GPSTracker(mContext);

    while(true){
     latii = "" + a.getLatitude();
     lonii = "" + a.getLongitude();
     latitude.setText(latii);
     longitude.setText(lonii);
            sleep(5000);
    }





  } catch (Exception e) {
   e.printStackTrace();
;
  }
 ;
return null;


 }
}
4

2 回答 2

1

onPostExecute(Result) 在 UI 线程上运行 onPreExecute() 在 UI 线程上运行

doInBackground(Void... params) 在自己的线程上运行

你永远不应该在另一个线程中更改 UI,我们更喜欢使用消息。

于 2013-10-23T02:57:23.560 回答
0

您应该在主线程中更新 UI,而不是在后台线程中。您可以使用 Handler 发送消息来设置值。或者您可以使用 runOnUiThread 方法,如下所示:

protected Void doInBackground(Void... params) {

  try {
      GPSTracker mytracker = new GPSTracker(mContext);

    while(true){
     latii = "" + a.getLatitude();
     lonii = "" + a.getLongitude();
     currentActivity.this.runOnUiThread(new Runnable() {    
            public void run()    
            {    
               latitude.setText(latii);
               longitude.setText(lonii);   
            }    

        });
     sleep(5000);
    }

  } catch (Exception e) {
   e.printStackTrace();
  }
   return null;

 }
于 2013-10-23T02:55:23.133 回答