【问题标题】:how to timeout requestLocationUpdates?如何超时 requestLocationUpdates?
【发布时间】:2019-09-05 03:41:47
【问题描述】:

当没有找到GPS 修复时,代码会无限期地卡在looper 中。 我想添加一个超时,这样如果没有找到GPS 修复,它应该从looper 出来并执行代码的剩余部分。

如果您能帮助我解决此问题,我将不胜感激。

public class service_task extends Service {

    @SuppressLint("MissingPermission")
    @Override
    public void onCreate() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    private class ServerThread extends Thread implements LocationListener {

        public LocationManager locationManager = null;
        public String msg = "default";
        public String id = "default";
        private Location mLocation = null;
        public Socket socket = null;
        public int serviceid;


        public ServerThread(LocationManager locationManager, int startid) {
            super("UploaderService-Uploader");
            this.locationManager = locationManager;
            this.serviceid=startid;          
        }

        @SuppressLint("MissingPermission")
        public void run() {


            Looper.prepare();
            this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
            Looper.loop();


            if (mLocation!=null) {
                msg = "GPS data:" + mLocation;
            }else{
                msg ="No GPS data";
            }

            stopSelf(serviceid);
        }

        @Override
        public void onLocationChanged(Location location) {
            mLocation = location;
            Log.d("D", String.valueOf(location));
            this.locationManager.removeUpdates(this);
            Looper.myLooper().quit();
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }


    }

    @SuppressLint("MissingPermission")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        Log.d("D", "startcommand");
        LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        ServerThread thread = new ServerThread(locationManager,startId);
        thread.start();
        return START_REDELIVER_INTENT;
    }
}

【问题讨论】:

    标签: android locationmanager android-gps android-looper


    【解决方案1】:

    创建一个使用您的LooperHandlerhandler = new Handler(Looper.myLooper()); 然后使用handler.postDelayed(Runnable, long) 发布一个新的Runnable,它会取消位置更新并在给定延迟后退出您的Looper

    【讨论】:

      猜你喜欢
      • 2023-03-04
      • 1970-01-01
      • 2013-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多