我有一项服务可以跟踪电池信息并将其存储在共享首选项中。然后从我的主要活动中BroadcastReceiver
(OnReceive
用于聆听ACTION_BATTERY_CHANGED
)
每次 OnReceive 发生电池电量和温度变化时,但我的共享首选项保持不变,直到我改变我的屏幕方向(我认为是因为活动的娱乐)。请帮助我以某种方式使 onReceive 方法也更新共享首选项。
我的主要活动:
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
appPrefs = new AppPreferences(getApplicationContext());
}
......
/* Broadcast Receiver for battery stats */
BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
.....
private TextView text;
int level = -1;
@Override
public void onReceive(Context context, Intent intent) {
level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
text=(TextView) findViewById(R.id.TV_text);
text.setText("level"+level+"something from Shared Pref"+appPrefs.getAnything());
}
}
}
我的共享偏好:
public class AppPreferences extends PreferenceActivity {
private static final String APP_SHARED_PREFS = "com.aydabtu.BroadcastSMS_preferences"; // Name of the file -.xml
private SharedPreferences appSharedPrefs;
private Editor prefsEditor;
public AppPreferences(Context context)
{
this.appSharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
public long getAnything() {
return appSharedPrefs.getLong("Anything", 9);
}
public void setAnything(long a) {
prefsEditor.putLong("Anything", a);
prefsEditor.commit();
}
我的服务:
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
......
appPrefs.setAnything(a);
那么,为什么共享首选项在 OnReceive 方法中没有更新为级别或温度?怎么办?任何帮助将不胜感激。:)