我有一项跟踪电池信息并将其存储在共享首选项中的服务。然后,从我的主要活动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方法中更新为级别或温度? 怎么办?任何帮助将不胜感激。 :)
答案 0 :(得分:1)
最后,经过这么多研究,我可以让它发挥作用:只需添加:
private Intent starterIntent;
在类名称上方的类成员区域中,在我的主要类下面的示例中:
public class MainActivity extends Activity {
private Intent starterIntent;
然后,您可以在任何地方放置代码来刷新活动而不向用户显示。:
finish();
starterIntent.setFlags(intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(starterIntent);
overridePendingTransition(0,0);