使用asyncTask更新LocationListener

时间:2014-01-03 03:58:40

标签: android android-asynctask android-location

即时通讯已经在寻找在这个论坛aswer但没有工作,即时创建一个Android应用程序和IM试图让从的AsyncTask协调LocationListener的更新(我的AsyncTask作业只更新latitute和经度) 主线程通过位置管理器从asyncTask获取coodinate,它昨天工作,今天它不再工作了, 这是我的asyncTask代码:

 private class LoopMsg extends AsyncTask<String,Void,Void>{
        protected Void doInBackground(String... urls){

            Looper.prepare();

            LocationListener listen = new LocationListener() {

                @Override
                public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onProviderEnabled(String arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onProviderDisabled(String arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onLocationChanged(Location loc) {
                    // TODO Auto-generated method stub

                    Log.d(TAG,"Latitude :"+String.valueOf(loc.getLatitude()));
                    Log.d(TAG,"Longitude :"+String.valueOf(loc.getLongitude()));
                    Glatitude = loc.getLatitude();
                    Glongitude = loc.getLongitude();
                }
            };          
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 0, listen);
            Looper.loop();


            return null;

        }
    }

请帮我解决这里出了什么问题?以及如何解决这个问题?它之前运行良好 第二天我在Looper.prepare()得到例外 它说每个线程只能创建一个looper,然后我删除Looper.prepare和Looper.loop Part,错误更改变为

*FATAL EXCEPTION: asyncTask #1
*java.lang.RuntimeException: an error occured while executing do in background
我真的不知道为什么,因为我没有在我的doInBackground方法中更新ui线程

为什么我知道我的应用无效: 1.onLocationChanged再也没有打过电话 2.如果我不使用looper.prepare和looper.loop

,应用程序崩溃

我也尝试过这样:

lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 0, listen, Looper.getMainLooper());

和此:

Looper.Mylooper.prepare();
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 0, listen, Looper.getMyLooper());

但仍然没有运气,该应用仍未运行

这是我在AsyncTask中移除Looper后得到的logCat(并且应用程序总是崩溃)

-Fatal Exception: AsyncTask#2
-java.lang.RuntimeException: An error occured while executing doInBackground()
-at android.os.AsyncTask$3.done(AsyncTask.java:299)
-at java.util.concurrent.FutureTask.finishCompletion(FutureTask.Java:219)
-at java.util.concurrent.FutureTask.run(FutureTask.Java:239)
-at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
-at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
-at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
-at java.lang.Thread.run(Thread.java:838)
-Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not  called Looper.prepare()
-at android.os.Handler.<init>(Handler.java:197)
-at android.os.Handler.<init>(Handler.java:111)
-at android.location.LocationManager$ListenerTransport$1.<init>(LocationManager.java:199)
-at android.location.LocationManager$ListenerTransport.<init>(LocationManager.java:199)
-at android.location.LocationManager.wrapListener(LocationManager.java:822)
-at android.location.LocationManager.requestLocationUpdates(LocationManager.java:835)
-at android.location.LocationManager.requestLocationUpdates(LocationManager.java:432)
-at android.location.ZTEPrivacyLocationManager.requestLocationUpdates(ZTEPrivacyLocationManager.java:107)
-at com.login.absen.MyService$LoopMsg.doInBackground(MyService.java:244)
-at com.login.absen.MyService$LoopMsg.doInBackground(MyService.java:1)
-at android.os.AsyncTask$2.call(AsyncTask.java:287)
-at java.util.concurrent.FutureTask.run(FutureTask.java:234)
-... 4 more

更新

我是客人,我可以简单地解决问题 其实这个问题是onLocationChange方法在(中兴n986 - 安卓4.2)不叫,我尝试在其他设备代码(旅程 - 安卓2.3.3)的行为是一样的,同样的AsyncTask停在Looper.loop但onLocationChange运行方法正在运行,因此位置更新仍在运行

4 个答案:

答案 0 :(得分:0)

首先,不需要AsyncTask来监听位置更新。 LocationLintener本身是异步运行的,所以只需注册位置更新并更新

中的ui
 public void onLocationChanged(Location loc) {
                    // TODO Auto-generated method stub


                }

答案 1 :(得分:0)

使用服务,您可以在那里使用位置监听器,无需

答案 2 :(得分:0)

public class LocateDeviceService extends Service {

private static final String TAG = "";

double lat = 0;
    double lng = 0;



@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    customHandler.postDelayed(updateTimerThread, 0);
    return super.onStartCommand(intent, flags, startId);
}

private Handler customHandler = new Handler();

private Runnable updateTimerThread = new Runnable() {

    public void run() {
        try {
            //send location

    LocationManager locman = (LocationManager) context
            .getSystemService(Context.LOCATION_SERVICE);

    Criteria criteria = new Criteria();
    String provider = locman.getBestProvider(criteria, false);
    Location location = locman.getLastKnownLocation(provider);

    if (location != null) {
        lat = location.getLatitude();
        lng = location.getLongitude();

    }

            customHandler.postDelayed(this,60000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

};



public void sendLocationToServer(Double lat,Double lng )
        throws InterruptedException {
    //do ur job here

}

@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    if (null != customHandler && null != updateTimerThread) {
        customHandler.removeCallbacks(updateTimerThread);
    }
}
}

答案 3 :(得分:0)

AsyncTask无需获取位置更改。可以将位置发送到在主线程上运行的已注册类。如果要将位置上载到服务器,则仅对该部分使用AsynTask。

以下是步骤:
1.在扩展Service的类上实现“LocationListener”。
2.然后,您需要在LocationListener中实现未实现的方法。位置传递给您的是:


    @Override
    public void onLocationChanged(Location location) {
        //Use AsyncTask only to upload the location information
        uploadLocationToServerThroughAsyncTask(location);   
    }


3.现在,注册LocationManager,以便在更改时将位置发送到您的班级,如下所示:


    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    String provider = lm.getBestProvider(criteria, true);
    if (provider == null || provider.trim().isEmpty()) {
        // No provider hence return.
        return;
        }
    // If there are any available provider, then register for location updates.
    lm.requestLocationUpdates(locProvider, 1000, 200, this); // 1 sec and 200 meter updates 



4.在适当的时间从位置经理取消注册,如下所示:


    try {
        lm.removeUpdates(this);
        } catch (Exception e) {
        e.printStackTrace();
    }