我想创建一个后台线程(执行即使我死了的活动),其更新我的数据位置等它有一个http resquest发送到我的服务器。但它发生了异常:无法在AsyncTask中调用处理程序?
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) {
}
}
编辑:我想我必须使用一个服务,而不是一个的AsyncTask的。
@ user40574:喜,以更清晰的方式解释你的问题,你有你的logcat的任何期望或foreround线程无法更新数据????????????????? ????/ – 2011-02-01 08:38:25
我刚刚用logcat更新了我的帖子。 – user420574 2011-02-01 08:40:17