android - 设备锁定时获取位置
问题描述
我正在尝试获取位置。当设备解锁时,一切正常,但当设备被锁定时,坐标就不会出现。
这是我的服务示例:
public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{
@Override
public void onCreate() {
super.onCreate();
buildGoogleApiClient();
mGoogleApiClient.connect();
startForeground(1131, new NotificationCompat.Builder(this, "default")
.setContentText("App")
.setContentTitle("App Service")
.setSmallIcon(R.mipmap.enter_icon)
.build());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
@Override
public void onConnected(Bundle bundle) {
startCheckLocation()
}
private void startCheckLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
locationRequest.setFastestInterval(interval);
locationRequest.setInterval(interval);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
Intent intent = new Intent(this, LocationService.class);
mPendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mFusedLocationClient.requestLocationUpdates(locationRequest, mPendingIntent);
}
public static void start(Context context) {
Intent intent = new Intent(context, LocationService.class);
context.startService(intent);
}
}
我尝试使用 getBroadcast() 而不是 getService() 方法,但它的工作方式相同。
解决方案
就我而言,我通过 FirebaseJobDispatcher 获取位置数据(谷歌推荐使用 WorkManager,但目前它是 alpha 版)。我开始每 20 分钟触发一次的工作,请求位置并将其存储到数据库。您可以在此处查看 FirebaseJobDispatcher 的示例https://github.com/firebase/firebase-jobdispatcher-android。
推荐阅读
- python - 如何通过多个页面申请循环并将每个页面添加到 csv 文件
- c# - 允许依赖于 AttributeUsage 的 Attribute 构造函数
- python - 如何在不更改尺寸的情况下减小 PNG 图像的文件大小?
- python - 将 np 矩阵及其索引转换为两个列表
- python - 如何将 static_test 运行到多个 python 文件?
- tensorflow - 如何在张量流模型内转换后打印特征值
- scala - 如何在scala中编程一个适合的圆
- amazon-redshift - 将数据插入红移表时在结果中获取 2 条记录
- android - Android NDK“Hello From C++”应用程序出错
- ubuntu-16.04 - 如何在 ubuntu 16 中通过离线安装安装梨形图