Search code examples
androidbatteryreceiver

How to get information when battery status sets full


my question is... how to get information when battery status sets full. I've tried do this by receiver on ACTION_BATTERY_CHANGED, but this isn't working, I'm almost sure that receiver not even get this broadcast. Maybe i don't understand this properly, action_battery_changed means that is signalized when our battery get another % ? Or only in particular events like disconnected or connected, because this actions works in my application(in another class receiver).

<receiver android:name="com.lily.chargingscheduler.ChangingBatteryStatsOnReceiver"   >
      <intent-filter>
          <action android:name="android.intent.action.ACTION_BATTERY_CHANGED" />
      </intent-filter>
</receiver>

And class :

 public class ChangingBatteryStatsOnReceiver  extends BroadcastReceiver {
    static BDHelper db_helper;
    private String data;
    String level_;
    String answer;

@Override
public void onReceive(Context context, Intent intent) {
    db_helper = new BDHelper(context);
    data = (new SimpleDateFormat("MM/dd/yyyy HH:mm")).format(new Date());
    level_ = batteryLevel(context);

    if(db_helper.getLastRow().get_TO_D().equals("")){
        if(level_ == "100%"){// level return % as a String
            answer = calculate();//calculate returns date and other things
            ending_charging(context);//adding to table and notification of this event   
        }
    }
}

[edit]

Maybe i wasn't specific enough, i don't have problem with getting information about battery level, I've problem with getting information when my battery is full.


Solution

  • public void onReceive(Context context, Intent intent) {
                 context.unregisterReceiver(this);
                 int currentLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                 int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
                 int level = -1;
                 if (currentLevel >= 0 && scale > 0) {
                     level = (currentLevel * 100) / scale; // level will returns 99 or 100 when battery is full
                 }
                 batteryPercent.setText("Battery Level Remaining: " + level + "%");
             }
         }; 
         IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
         registerReceiver(batteryLevelReceiver, batteryLevelFilter);
    }
    

    As additional, if you want to listen the battery on low status, add this <intent-filter/>:

    <receiver android:name=".ChangingBatteryStatsOnReceiver">
    <intent-filter>
      <action android:name="android.intent.action.ACTION_BATTERY_LOW"/>
      <action android:name="android.intent.action.ACTION_BATTERY_OKAY"/>
      </intent-filter>
    </receiver>