最近做機(jī)頂盒開發(fā)只酥,需要從開機(jī)廣播中獲取一個“userName”的值放入到Application中丢氢。測試過程發(fā)現(xiàn)怎么也獲取不到僚纷,抓了下Log發(fā)現(xiàn)自定義的Application沒有啟動。查了下資料才發(fā)現(xiàn)是因?yàn)闆]有設(shè)置Application的name屬性楼熄,導(dǎo)致沒有關(guān)聯(lián)自定義的Application。
Receiver代碼:
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
Map result = (Map) gson.fromJson(intent.getStringExtra("params"), Map.class);
editor.putString("userName",(String)result.get("userName"));
System.out.println("MyReceiver : " + (String)result.get("userName"));
editor.commit();
}
Application代碼:
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
userName = sharedPreferences.getString("userName","");
System.out.println("MyAppliaction onActivityStarted : " + userName);
AndroidManifest.xml:
<application
android:name=".MyApplication"
android:allowBackup="true"
...
/>