在Activity oncreate上,Android SharedPreferences为空

时间:2015-03-27 16:14:04

标签: android broadcastreceiver sharedpreferences

我在AndroidManifest.xml中声明了以下Receiver

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

ReferralReceiver将引用值(utm_ *)存储到SharedPreferences对象

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

但是,在创建主活动时,SharedPreferences对象是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);
            }
        }
}

我创建了一个在创建活动后手动检索SharedPreferences对象的方法,这似乎工作正常。这里可能有什么问题的线索以及对SharedPreferences对象的初始调用是空的吗?

1 个答案:

答案 0 :(得分:0)

通过&#34; onCreate&#34;中的代码验证设备日志在广播接收器更新SharedPreferences对象之前调用方法。