我正在使用不同的进程(在我的 list 中使用 android:process)以便能够在我的应用程序中使用多个 mapView ( How to use multiple MapActivities/MapViews per Android application/process )。这 2 个 map 位于我的常规标签主机的不同 Activity 和不同标签中。
不,我想缩放到特定位置,这是通过用户在其他 Activity 中选择的。使用静态变量不起作用。之后,我尝试将数据保存到 SharedPreferences 文件中,并在 MapActivity 中再次读取它。但这也行不通。数据写入成功,但是MapActivity在SharedPreferences中没有找到任何数据。
是否有可能在两个或多个进程之间共享数据?
保存位置数据:
public static boolean addLocationToShared(float lat, float lon){
Log.i(TAG, "addLocationToShared: " + lat + "," + lon);
if(mapShared==null)
mapShared = TLApplication.getAppContext().getSharedPreferences(MAP_SHARED_PREFS, Context.MODE_PRIVATE);
return mapShared.edit().putFloat(PREF_LAT, lat).putFloat(PREF_LON, lon).commit();
}
读取位置数据:
mapShared = TLApplication.getAppContext().getSharedPreferences(MAP_SHARED_PREFS, Context.MODE_PRIVATE);
float lat = mapShared.getFloat(PREF_LAT, 1000);
float lon = mapShared.getFloat(PREF_LON, 1000);
Log.d(TAG, "zoom to " + lat + ", " + lon);
if(lat != 1000 && lon != 1000){
GeoPoint point = new GeoPoint((int)(lat * 1E6), (int)(lon * 1E6));
zoomToLocation(point, 15);
}
最佳答案
一个简单的方法是 SharedPreferences。使用“Context.MODE_MULTI_PROCESS”标志获取您的共享首选项。
在写入过程中:
SharedPreferences preferencesWriter = basedContext.getSharedPreferences("Keeps_a_constant_preferences_file_name", Context.MODE_MULTI_PROCESS);
preferencesWriter.edit().putString(someKey, savingValue).commit();
在读者进程中:
SharedPreferences preferencesReader = basedContext.getSharedPreferences("Keeps_a_constant_preferences_file_name", Context.MODE_MULTI_PROCESS);
String savedValueInWriterProcess = preferencesWriter.getString(someKey, defaultValue);
注意:在读取进程中,您必须每次都检索一个新的 SharedPreferences 变体,以确保刷新共享值。
其他方法: 1.发送带有额外数据的广播; 2. 内容提供者。
关于android - 如何在两个进程之间共享数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9179090/