我正在开发的 Android 应用程序要求每 15 分钟记录一次 GPS 位置。为了尽量减少 GPS 使用以延长电池生命周期,我想使用 ScheduledExecutorService 开始请求位置更新,然后在发生位置更改后关闭请求。由于错误,我当前的实现不允许这样做:
Can't create handler inside thread that has not called Looper.prepare()
我知道这是因为我无法在后台线程中调用 LocationManager。
我启动调度程序的代码:
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);
LocationFinder 类:
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 的情况下执行此操作?
最佳答案
您在设置时会遇到的问题是,如果应用程序被操作系统终止或用户滑动应用程序将其关闭,它将停止记录您的位置更新。实际上,您可以采用 2 种方法来获得定时位置更新间隔,而不管您的应用程序处于何种状态(应用程序被强制终止时除外)。
使用
LocationManager
的requestLocationUpdates()
方法设置 15 分钟的更新间隔,使用PendingIntent
而不是LocationListener
以确保您继续接收更新,而不必保留对监听器的引用。如果您需要知道您是否已经请求更新,只需使用SharedPreferences
保留一个 boolean 标志。另一个正在使用
AlarmManager
安排将调用IntentService
的更新(用于在后台运行)或BroadcastReceiver
(在前台运行)调用LocationManager
的requestSingleUpdate()
方法获取 GPS 更新。
关于java - 在预定线程上请求位置更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42706389/