我正在尝试获取位置。解锁设备后,一切正常,但是锁定设备时,坐标将无法显示。
以下是我的服务示例:
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()方法,但是它的工作方式相同。
答案 0 :(得分:0)
就我而言,我是通过FirebaseJobDispatcher获取位置数据的(谷歌建议使用WorkManager,但目前仍为alpha)。 我开始每20分钟触发一次的工作,请求位置并将其存储到db。 您可以在https://github.com/firebase/firebase-jobdispatcher-android处查看FirebaseJobDispatcher的示例。
答案 1 :(得分:0)
您可以使用SimpleLocation库获取当前的纬度和经度。
在build.gradle(Module:app)文件中的库下面添加
implementation 'com.github.delight-im:Android-SimpleLocation:v1.0.1'
并在服务类中使用以下代码
SimpleLocation simpleLocation = new SimpleLocation(LocationService.this);
double lat = simpleLocation.getLatitude();
double lon = simpleLocation.getLongitude();
不要忘记在清单文件中添加LOCATION权限。