不能调用句柄在AsyncTask的? [英] Can't call handler in an AsyncTask?

查看:152
本文介绍了不能调用句柄在AsyncTask的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个后台线程(即使我死了活动执行)的更新我的数据的位置等发送到我的服务器的HTTP resquest。但它发生了异常:

  7月2日至1日:50:18.172:ERROR / Exception1(277):不能内螺纹已不叫尺蠖prepare创造处理器()

我的code:

 公共类Messagerie延伸活动{
私人的LocationManager的LocationManager;
私人字符串locationProvider = LocationManager.NETWORK_PROVIDER;公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);    的setContentView(R.layout.messagerie);    新UpdateLocation()执行();}公共无效majCoordonnes(){
    StringBuilder的StringBuilder的=新的StringBuilder(Fournisseur:);
    stringBuilder.append(\\ n);
    stringBuilder.append(locationProvider);
    stringBuilder.append(:);
    地点= locationManager.getLastKnownLocation(locationProvider);    如果(位置!= NULL){        双纬度= location.getLatitude();
        双经度= location.getLongitude();        字符串经纬度=将String.valueOf(纬度);
        字符串LON =将String.valueOf(经度);        stringBuilder.append(纬度);
        stringBuilder.append(,);
        stringBuilder.append(经度);
                    //发送位置服务器在的AsyncTask
        新sendLocation()执行(纬度,经度);
    }其他{
        stringBuilder.append(非déterminée);
    }
    Log.d(MaPositionMaj,stringBuilder.toString());
}
/ **
 * Ecouteurutilisé倒莱单米塞斯怨妇DES干邑生产商
 * /
类MajListener实现android.location.LocationListener {
    公共无效onLocationChanged(地点){
        majCoordonnes();
    }
    公共无效onProviderDisabled(字符串提供商){
    }
    公共无效onProviderEnabled(字符串提供商){
    }
    公共无效onStatusChanged(字符串提供商,INT地位,捆绑演员){
    }
};
//RequêteGET,濑à怨妇DES的相关信息
私有类UpdateLocation扩展的AsyncTask<弦乐,太虚,字符串> {    串RESP;    @覆盖
    保护字符串doInBackground(字符串... PARAMS){        尝试{
        //疗养地点
        字符串locationContext = Context.LOCATION_SERVICE;
        的LocationManager =(的LocationManager)getSystemService(locationContext);
        如果(的LocationManager = NULL&放大器;!&安培;!locationProvider = NULL){            majCoordonnes();
            locationManager.requestLocationUpdates(locationProvider,120000,500,新MajListener());
        }
        }赶上(例外五){
            Log.e(Exception1,e.getMessage());
        }        返回RESP;
    }
    @覆盖
    保护无效onPostExecute(字符串结果){
    }
    @覆盖
    在preExecute保护无效(){
    //观光长时间运行的操作执行之前完成。例如显示ProgessDialog
    }
    @覆盖
    保护无效onProgressUpdate(虚空......值){    }
}

编辑:我想我必须使用一个服务,而不是一个的AsyncTask的


解决方案

  

编辑:我想我必须使用一个服务,而不是一个的AsyncTask的


precisely。创建一个单独的线程不会保证当应用/活动退出,或当操作系统需要更多的资源它不杀死。 A 服务并不能保证,要么 - 如果系统真的是重负载下它可能仍然被杀死,但它不太可能。另外(纠正我,如果我错了),一旦系统负载软化Android将重新启动该服务。

I want to create a background thread (execute even if my activity dies) that update my data location et send it to my server with an http resquest. But it occurs an exception:

02-01 07:50:18.172: ERROR/Exception1(277): Can't create handler inside thread that has not called Looper.prepare()

My code:

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) {

    }
}

EDIT: I think I have to use a Service instead of an asyncTask.

解决方案

EDIT: I think I have to use a Service instead of an asyncTask.

Precisely. Creating a separate thread will not ensure that it is not killed when the application / activity exits, or when the operating system needs more resources. A Service doesn't ensure that either -- it may still be killed if the system is under really heavy load, but it's much less likely. Also (correct me if I'm wrong), Android will restart the Service once the system load softens.

这篇关于不能调用句柄在AsyncTask的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆