点击按钮后,我需要等到某些信息存储在SharedPreferences
中,然后继续进行下一个活动。我尝试使用SharedPreferences.OnSharedPreferenceChangeListener()
,但它无法正常工作。
MapActivity
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (currentPosition != null ) {
SharedPreferences preferences = PreferenceHelper.getPreferences(MapActivity.this);
SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.i(TAG,"key "+key);
Intent i = new Intent(MapActivity.this, MainActivity.class);
i.putExtra("coordinates", currentPosition);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
}
};
preferences.registerOnSharedPreferenceChangeListener(preferenceChangeListener);
PreferenceHelper.saveLocation(MapActivity.this,currentPosition);
}
}
});
PreferencesHelper
public class PreferenceHelper {
public static SharedPreferences appPreference;
public static SharedPreferences getPreferences(Context context){
return context.getSharedPreferences(PREFERENCES_NAME,Context.MODE_PRIVATE);
}
public static void saveLocation(Context context,LatLng location){
appPreference=context.getSharedPreferences(PREFERENCES_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = appPreference.edit();
editor.putFloat(CURRENT_LOCATION_X, (float) location.latitude).apply();
editor.putFloat(CURRENT_LOCATION_Y, (float) location.longitude).apply();
editor.commit();
}
}
答案 0 :(得分:1)
提交更改是主线程中发生的事情......您不需要OnSharedPreferenceChangeListener。当您希望收到有关从应用程序的其他组件提交的共享首选项中的更改的通知时,更改侦听器非常有用...而不是提交更改的更改。只是做:
prefs.edit().putWhatever().commit();
startActivity(new Intent(....));