简体   繁体   English

GPS在异步任务中不起作用

[英]GPS not working in Async Task

I have implemented a simple GPS program that fetches the co-ordinates and displays them on the screen. 我已经实现了一个简单的GPS程序,该程序可获取坐标并将其显示在屏幕上。 When I tried to improve on this design and implement an async task, the GPS doesn't seem to work for some reason or another. 当我尝试改进此设计并实现异步任务时,GPS出于某种原因似乎无法正常工作。 Is there some issue with regards to using async task with GPS? 关于将异步任务与GPS一起使用是否存在一些问题? Here is my code: 这是我的代码:

private class DownloadTask extends AsyncTask<String, Void, Object> {
        protected Object doInBackground(String... args) {
            Log.i("MyApp", "Background thread starting");

            LocationManager mLocationManager;
            Gpslistener Gpslistener;

            Gpslistener = new Gpslistener();

            try{

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

               mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,Gpslistener);

            }catch (Exception e) {

                test_gps = true;
           }


        return null;
    }

    protected void onPostExecute(Object result) {

        if(test_gps == true){
            if (ParkingActivity.this.progressDialog != null) {
                ParkingActivity.this.progressDialog.dismiss();
            }               
            AlertMessage("GPS Error", "Unable to get location");
        }



public class Gpslistener implements LocationListener
{
        @Override
        public void onLocationChanged(Location loc)
        {
            loc.getLatitude();
            loc.getLongitude();
        }

        @Override
        public void onProviderDisabled(String provider)
        {       
        }

        @Override
        public void onProviderEnabled(String provider)
        {
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras)
        {
        }
    }

Each time I run it, it always catches an exception. 每当我运行它时,它总是会捕获异常。 The GPS permissions are set in the manifest and I'm always using a different application to ensure that a GPS connection is online so I eliminated those as potential errors. GPS权限是在清单中设置的,我一直在使用其他应用程序来确保GPS连接在线,因此我消除了这些潜在的错误。 Honestly I can't think of anything else, without the async task it works perfectly! 老实说,如果没有异步任务,那么我什么也想不起来! Any help is much appreciated, thanks! 非常感谢任何帮助,谢谢!

Edited My exception logcat: 编辑了我的异常logcat:

05-09 22:56:20.199: E/EXCEPTION:(8874): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
05-09 22:56:20.199: E/EXCEPTION:(8874): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
05-09 22:56:20.199: E/EXCEPTION:(8874):     at android.os.Handler.<init>(Handler.java:121)
05-09 22:56:20.199: E/EXCEPTION:(8874):     at android.location.LocationManager$ListenerTransport$1.<init>(LocationManager.java:173)
05-09 22:56:20.199: E/EXCEPTION:(8874):     at android.location.LocationManager$ListenerTransport.<init>(LocationManager.java:173)
05-09 22:56:20.199: E/EXCEPTION:(8874):     at android.location.LocationManager._requestLocationUpdates(LocationManager.java:579)
05-09 22:56:20.199: E/EXCEPTION:(8874):     at android.location.LocationManager.requestLocationUpdates(LocationManager.java:446)
05-09 22:56:20.199: E/EXCEPTION:(8874):     at stefan.testservice.ParkingActivity$DownloadTask.doInBackground(ParkingActivity.java:163)
05-09 22:56:20.199: E/EXCEPTION:(8874):     at stefan.testservice.ParkingActivity$DownloadTask.doInBackground(ParkingActivity.java:1)
05-09 22:56:20.199: E/EXCEPTION:(8874):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
05-09 22:56:20.199: E/EXCEPTION:(8874):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
05-09 22:56:20.199: E/EXCEPTION:(8874):     at java.util.concurrent.FutureTask.run(FutureTask.java:138)
05-09 22:56:20.199: E/EXCEPTION:(8874):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
05-09 22:56:20.199: E/EXCEPTION:(8874):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
05-09 22:56:20.199: E/EXCEPTION:(8874):     at java.lang.Thread.run(Thread.java:1019)

You can't do that. 你不能那样做。 The thread dies as soon as doInBackground() returns. 只要doInBackground()返回,线程就会死亡。 The GPS listener is a Handler which requires a Looper thread to operate. GPS侦听器是一个处理程序,需要使用Looper线程进行操作。 At the beginning of doInBackground() you need to call Looper.prepare() then at the end call Looper.loop() . doInBackground()的开头,您需要调用Looper.prepare()然后在结尾处调用Looper.loop() It will loop forever until you call quit() on the thread's Looper object. 它将永远循环,直到您在线程的Looper对象上调用quit()为止。

AsyncTask is really designed for one-shot temporary threads though, so I'd use a normal thread for this. AsyncTask实际上是为单次临时线程设计的,因此我将为此使用普通线程。 Although, there's no reason you couldn't I suppose. 尽管,我没有理由没有。 You just have to make 100% sure that you end the loop or it will run forever even after the user closes the app. 您只需100%确保结束循环,否则即使用户关闭应用程序,循环也将永远运行。

Java Can't create handler inside thread that has not called Looper.prepare() Java无法在尚未调用Looper.prepare()的线程内创建处理程序

like many other things , gps listener can only be listened to by a loopy thread (like the ui thread) . 像许多其他事情一样,gps侦听器只能由循环线程(如ui线程)侦听。 the easiest thing to do would be to it via the ui thread . 最简单的方法是通过ui线程。

also , the gps listener isn't named like this for no reason . 同样,gps监听器的名字也不无缘无故。 only when it gets a location (and that could take time) , it will call the method "onLocationChanged" . 仅当它获得位置(可能需要花费时间)时,才会调用方法“ onLocationChanged”。 you don't need to have asyncTask for this , since all of the calls to "requestLocationUpdates" are asynchronous anyway... 您不需要为此拥有asyncTask,因为无论如何,对“ requestLocationUpdates”的所有调用都是异步的...

If you want a dirty and not much sensual way: 如果您想要一种肮脏且不多感性的方式:

mLocationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
Looper.prepare();
Looper.loop();
if(mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){    
  mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, GPS_MINIMUM_TIME, GPS_MINIMUM_DISTANCE, MyFragment.this);
}
Looper.myLooper().quit();

Basically, it makes the current thread, a main thread on which messages will be executed, after shortly you give up this thread being a main thread. 基本上,它使当前线程成为将在其上执行消息的主线程,不久之后您就放弃了该线程成为主线程。 I'm not sure of the consequences of this. 我不确定这样做的后果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM