等待定期任务中的异步回调?

时间:2017-11-06 20:55:33

标签: android locationmanager gcmtaskservice

我希望每4个小时左右检查用户的位置,我不想让我的应用程序运行来执行此操作。看起来像使用带有PeriodicTask的GcmTaskService会让我的服务被调用(WakefulBroadcastReceiver限制在Android 6+中停止应用时启动任务),并且它将兼容回Android 4.4(与JobScheduler不同) - 我支持的最低Android版。

问题是GcmTaskService的onRunTask方法是同步的,但我想用它来询问位置并处理结果(LocationManager将异步调用我的LocationListener实现)。

应如何处理?

1 个答案:

答案 0 :(得分:0)

使用简单的等待/通知:

private interface RunnableLocationListener extends Runnable, LocationListener {}

@Override
public int onRunTask (TaskParams params) {
    final Object monitor = new Object();
    final AtomicBoolean located = new AtomicBoolean();
    new Thread(new RunnableLocationListener() {
        Context context = PeriodicCollector.this;
        public void run() {
            Criteria criteria = new Criteria();
            criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
            LocationManager locationManager = locationManager = (LocationManager)PeriodicCollector.this.getSystemService(Context.LOCATION_SERVICE);
            locationManager.requestSingleUpdate(criteria, this, Looper.getMainLooper());
        }

        @Override
        public void onLocationChanged(Location location) {
            // handle location here

            synchronized (monitor) {
                located.set(true);
                monitor.notifyAll();
            }
        }

        @Override public void onProviderDisabled(String s) {}
        @Override public void onProviderEnabled(String s) {}
        @Override public void onStatusChanged(String s, int i, Bundle b) {}
    }).start();

    int status = GcmNetworkManager.RESULT_FAILURE;
    try {
        synchronized (monitor) {
            if (!located.get()) {
                monitor.wait();
            }
        }
    } catch (InterruptedException e) {
        status = GcmNetworkManager.RESULT_SUCCESS;
    }
    return status;
}