【发布时间】:2020-11-13 16:43:20
【问题描述】:
我的应用程序包含 6 个独立的活动,其中一个返回 GPS 协调,此活动在打开时完美运行,但首先我返回到主活动它停止更新位置。
详情:
我创建了一个GPS services 并在Manifest.xml 中调用它
<service android:name=".Services.GPS_Service" />
这是服务:
public class GPS_Service extends Service {
private LocationListener listener;
private LocationManager locationManager;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@SuppressLint("MissingPermission")
@Override
public void onCreate() {
listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Intent i = new Intent("location_update");
i.putExtra("Longitude", location.getLongitude());
i.putExtra("Latitude", location.getLatitude());
final Date date = new Date(location.getTime());
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
i.putExtra("time", sdf.format(date));
sendBroadcast(i);
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
};
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//noinspection MissingPermission
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 0, listener);
}
@SuppressLint("MissingPermission")
@Override
public void onDestroy() {
super.onDestroy();
if (locationManager != null) {
//noinspection MissingPermission
locationManager.removeUpdates(listener);
}
}
}
【问题讨论】:
-
您必须创建一个前台服务才能在后台运行。更多详情请点击以下链接。 developer.android.com/guide/components/foreground-services
标签: android android-manifest locationmanager