0

我有一项服务可以跟踪电池信息并将其存储在共享首选项中。然后从我的主要活动中BroadcastReceiverOnReceive用于聆听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 方法中没有更新为级别或温度?怎么办?任何帮助将不胜感激。:)

4

1 回答 1

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);
于 2013-03-11T22:40:15.277 回答