하나의 액티비티와 브로드 캐스트 리시버가있는 앱을 개발합니다. 나는 활동에서 놓인 어떤 조정을 사용할 수있는 방법으로 브로드 캐스트 수신기를 놓고 싶다.브로드 캐스트 리시버에서 sharedpreferenced 사용
아래의 코드와 두 가지 활동 사이를 사용하지만 활동 및 브로드 캐스트 수신기 캔트 캐치 설정간에 사용합니다. 여기
내 avtivity에 저장하는 코드 :
private void savePreferences(String key, String value) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putString(key, value);
edit.commit();
}
및 braodcast 수신기에서이 코드 :
수신기는 "myPrefs"라는 이름의 파일을 사용하지만 기본 파일 이름을 사용하는@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
SharedPreferences sp = context.getSharedPreferences("myPrefs",
Context.MODE_PRIVATE);
String Password = sp.getString("PASSWORD", "1234");
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context,
"password is"+Password, duration);
toast.show();
}
당신은'PreferenceManager .getDefaultSharedPreferences (context);'로'sp'를 초기화하려고 했습니까 onReceive? –
네, 초기화 ... – M410