在活动之间切换时保持特定活动的活动状态



我的应用程序包含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);
}
}
}

根据你的答案和你使用的措辞:"当它打开但首先我返回到主活动"-我假设"我返回到主活动"的意思是要么涉及onBackPressed,要么只是调用了一个简单的finish((。因此,onDestroy被调用,所以你的侦听器被取消,这就是它停止工作的原因。

不能同时有两个活动处于活动状态。您必须使用安卓服务来更新位置。

最新更新