0

我有监听的服务,ACTION_BATTERY_CHANGED我希望能够传递(到我的活动)或保存(供以后在我的活动中使用)接收到的数据。我尝试了共享首选项,但没有帮助。

也许您可以帮助保存或传递收到的数据。

已编辑

@Override
      public int onStartCommand(Intent intent, int flags, int startId) {
        appPrefs = new AppPreferences(getApplicationContext());

//              /* Broadcast Receiver for battery stats                                               */
        IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);


        BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver(){
            @Override
            public void onReceive(Context context, Intent intent){
                int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
                int isCharging = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
                if (isCharging==0){

                }
                else{
                    appPrefs.setIsCharging(isCharging);
                    Log.e("inFFFF","FFFF "+appPrefs.getIsCharging()); // here I get my default value, not isCharging value

                }
            }

        };

        registerReceiver(batteryLevelReceiver, batteryLevelFilter);
        return Service.START_STICKY;
      }

在 AppPrefs 文件中:

 public void setIsCharging(int text){
             prefsEditor.putInt("isCharging", text);
         }

         public int getIsCharging(){
             return appSharedPrefs.getInt("isCharging", 9);
         }
4

1 回答 1

1

数据没有保存,sharedPreferences因为您没有提交它。

public void setIsCharging(int text){
    prefsEditor.putInt("isCharging", text);
    prefsEditor.commit();  //Add this line to commit data in sharedPreferences.
}
于 2013-03-10T11:42:20.830 回答