当用户杀死应用程序时,我的服务在后台运行。它有一个按钮,我可以返回到Map活动。但是,当用户在销毁应用程序后通过通知按钮返回到应用程序时,Map已创建,但我正在从我的服务传输到我的Map活动的信息为空。
当用户没有终止应用程序并通过通知按钮返回时,数据存在。
这是我的密码:
//Map Activity
//OnPause = transfer the data to service intent(Working fine)
BackgroundLocation backgroundLocation = new BackgroundLocation();
mServiceIntent = new Intent(this, backgroundLocation.getClass());
if (!isMyServiceRunning(backgroundLocation.getClass())) {
mServiceIntent.putExtra("AddressBackgound",mAddress);
mServiceIntent.putExtra("AddressLatBackgound",destinationLat);
mServiceIntent.putExtra("AddressLngBackgound",destinationLng);
startService(mServiceIntent);
}
// OnMapReady = Getting the data from service intent(return null for all data)
if (myLocation != null) {
BackgroundLocation backgroundLocation = new BackgroundLocation();
mServiceIntent = new Intent(this, backgroundLocation.getClass());
Bundle extras = getIntent().getExtras();
if (isMyServiceRunning(backgroundLocation.getClass()) && extras != null) {
String mAddress2 = extras.getString("AddressBackgound22");
Double destinationLat2 = extras.getDouble("AddressLatBackgound22");
Double destinationLng2 = extras.getDouble("AddressLngBackgound22");
Log.e("onResume", "onResume stats");
Log.e("Address", "" + mAddress2);
Log.e("Lat", String.valueOf(destinationLat2));
Log.e("Lng", String.valueOf(destinationLng2));
Log.e("OnMapReady","Service is running....");
}
else{
Log.e("OnMapReady","Service is not running");
}
}
后台位置(服务意图)=从mapsactivity获取信息并将信息返回到mapsactivity。
//Service Intent
// OnStartCommand
Bundle extras = intent.getExtras();
if (extras != null) {
//getting the data to the service is working fine even when the app killed the service still working with the data.
mAddress = extras.getString("AddressBackgound");
destinationLat = extras.getDouble("AddressLatBackgound");
destinationLng = extras.getDouble("AddressLngBackgound");
//This is what I am trying to send to MapsActivity:
extras.putString("AddressBackgound22",mAddress);
extras.putDouble("AddressLatBackgound22",destinationLat);
extras.putDouble("AddressLngBackgound22",destinationLng);
Log.e("onStartCommand", "onStartCommand started");
Log.e("Address","" + mAddress);
Log.e("Lat", "" + destinationLat);
Log.e("Lng", "" + destinationLng);
}
谢谢你抽出时间。
3条答案
按热度按时间4c8rllxm1#
您可以使用eventbus或广播接收器将数据从服务发送到活动/片段
mhd8tkvw2#
有很多方法,我说其中一些:
1-在服务中使用存储数据(如SharedPreferences、db和…),在活动中使用检索
2-使用eventbus或广播接收器
3-使用从服务到活动的回调数据的回调模式
hgqdbh6s3#
因此,感谢@mohammadreza,我在服务意图上使用了sharedpref,并且它起了作用。
我就是这么做的:
//保存sharedpref(backgroundactivity):
//读取sharedpref(mapsactivity):
backgroundlocation backgroundlocation=新的backgroundlocation();
IsMyService正在运行: