简体   繁体   中英

Android SharedPreferences empty on Activity oncreate

I have declared the following Receiver in the AndroidManifest.xml

<receiver android:name="com.xxx.ReferralReceiver"
          android:exported="true">
    <intent-filter>
        <action android:name="com.android.vending.INSTALL_REFERRER" />
    </intent-filter>
</receiver>

ReferralReceiver stores the referral values (utm_*) to the SharedPreferences object

public void onReceive(Context context, Intent intent) {
    SharedPreferences storage = context.getSharedPreferences("ReferralParamsFile", 0);
    Editor editor = storage.edit();
    editor.putString("test", "test");
    editor.commit();
}

However when the main activity is created the SharedPreferences object is emtpy.

public class MainActivity extends Activity {

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
SharedPreferences storage = context.getSharedPreferences(ReferralReceiver.PREFS_FILE_NAME, Context.MODE_PRIVATE);
Map<String,String> referralParams = new HashMap<String,String>();
for(String key : ReferralReceiver.EXPECTED_PARAMETERS)
        {
            String value = storage.getString(key, null);
            if(value != null)
            {
                params.put(key, value);
            }
        }
}

I created a method to manually retrieve the SharedPreferences object after the creation of the activity and this seems to work fine. Any clues what could be wrong here and the initial call to the SharedPreferences object is empty?

从设备日志验证,在广播接收器更新SharedPreferences对象之前,将调用“ onCreate”方法中的代码。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM