【发布时间】:2011-02-01 08:34:40
【问题描述】:
我想创建一个后台线程(即使我的活动终止也执行)更新我的数据位置并使用 http 请求将其发送到我的服务器。但是出现异常:
02-01 07:50:18.172: ERROR/Exception1(277): Can't create handler inside thread that has not called Looper.prepare()
我的代码:
public class Messagerie extends Activity {
private LocationManager locationManager;
private String locationProvider = LocationManager.NETWORK_PROVIDER;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.messagerie);
new UpdateLocation().execute();
}
public void majCoordonnes() {
StringBuilder stringBuilder = new StringBuilder("Fournisseur :");
stringBuilder.append("\n");
stringBuilder.append(locationProvider);
stringBuilder.append(" : ");
Location location = locationManager.getLastKnownLocation(locationProvider);
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
String lat = String.valueOf(latitude);
String lon = String.valueOf(longitude);
stringBuilder.append(latitude);
stringBuilder.append(", ");
stringBuilder.append(longitude);
//Send location to server in an AsyncTask
new sendLocation().execute(lat, lon);
} else {
stringBuilder.append("Non déterminée");
}
Log.d("MaPositionMaj", stringBuilder.toString());
}
/**
* Ecouteur utilisé pour les mises à jour des coordonnées
*/
class MajListener implements android.location.LocationListener {
public void onLocationChanged(Location location) {
majCoordonnes();
}
public void onProviderDisabled(String provider){
}
public void onProviderEnabled(String provider){
}
public void onStatusChanged(String provider, int status, Bundle extras){
}
};
//Requête GET, mise à jour des infos
private class UpdateLocation extends AsyncTask<String, Void, String> {
String resp;
@Override
protected String doInBackground(String... params) {
try {
//Recuperation Location
String locationContext = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(locationContext);
if (locationManager != null && locationProvider != null) {
majCoordonnes();
locationManager.requestLocationUpdates(locationProvider, 120000, 500, new MajListener());
}
} catch (Exception e){
Log.e("Exception1", e.getMessage());
}
return resp;
}
@Override
protected void onPostExecute(String result) {
}
@Override
protected void onPreExecute() {
// Things to be done before execution of long running operation. For example showing ProgessDialog
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
编辑:我认为我必须使用 Service 而不是 asyncTask。
【问题讨论】:
-
@user40574:您好,请用更清楚的方式解释您的问题,您的 Logcat 是否有任何期望或前台线程未能更新数据???????????? ?????????/
-
我刚刚用 logcat 更新了我的帖子。
标签: android multithreading android-asynctask handler