请求在计划线程上的位置更新



我正在处理的Android应用程序需要每15分钟记录一次GPS位置。为了最大程度地减少GPS的使用以保持电池寿命,我想使用计划的ExecutorService开始请求位置更新,然后一旦发生位置更改,请关闭请求。我当前的实施不允许这样做,因为错误:

Can't create handler inside thread that has not called Looper.prepare()

我知道发生的是因为我无法在背景线程中拨打位置manager。

我的代码启动调度程序:

locationFinder = new LocationFinder(context);
final Runnable gpsBeeper = new Runnable()
    {
        public void run()
        {
            try {
                locationFinder.getLocation();;
            }
            catch (Exception e)
            {
                Log.e(TAG,"error in executing: It will no longer be run!: " + e.getMessage());
                e.printStackTrace();
            }
        }
    };
  gpsHandle = scheduler.scheduleAtFixedRate(gpsBeeper, 0, 15, MINUTES);

位置基础类别:

public LocationFinder(Context context)
{
    this.mContext = context;
}
public void getLocation()
{
    locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
    isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    if (isGPSEnabled)
    {
        try
        {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, updateInterval, distance, this);
        }
        catch (SecurityException s)
        {
            s.printStackTrace();
        }
    }
}
public void stopUpdates(){
    locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
    locationManager.removeUpdates(this);
}
@Override
public void onLocationChanged(Location location)
{
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    isGPSUpdated = true;
    stopUpdates();
}

如何在不依赖主线程上调用requestLocationupdates的情况下执行此操作?

您将在设置中遇到的问题是,如果该应用程序被OS杀死或用户刷卡以关闭应用程序,它将停止记录您的位置更新。实际上,无论您的应用程序状态如何

  1. 使用LocationManagerrequestLocationUpdates()方法设置15分钟的更新间隔,使用PendingIntent而不是LocationListener来确保您继续接收更新而无需对听众的参考。如果您需要知道是否已经要求更新,只需使用SharedPreferences持续一个布尔标志。

  2. 另一个正在使用AlarmManager来安排将调用IntentService(用于在后台运行)或BroadcastReceiver(用于在前景中运行)的更新,以调用LocationManager'S requestSingleUpdate()方法以获取GPS更新。

最新更新