如何检查电池何时充满 100%?

How to check when battery gets 100% charged?

这是我目前拥有的功能,当单击 UI 上的按钮时执行,它会在 TextView 上显示字符串 str(充电状态)。

public void checkStatus (View view) {
    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Context context = this;
    Intent batteryStatus = context.registerReceiver(null, ifilter);
    // Are we charging / charged?
    int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;

    int perc = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);

    String str;
    if (perc == 100) {
        str = "Fully charged";
    } else if (isCharging) {
        str = "Charging";
    } else {
        str = "Not Charging";
    }

    TextView textview = (TextView) findViewById(R.id.textView);
    textview.setText(str);
}

现在我要做的是定期检查电池,一旦电量为 100%(充满电),然后调用一个函数,我们称它为 DiscntCharger()

根据我的研究,我需要在这里使用 IntentService 来监控充电状态,一旦它发现电池充满电,它需要调用我的 main activity 中的函数。但是,由于我对 android 开发还很陌生,所以我无法理解如何实现它。

如果有人能指出正确的方向,我将不胜感激。

试试这个。 在您的 activity class 中创建广播接收器并在电池充满后执行任何操作

private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context ctxt, Intent intent) {
      int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
      textview.setText(String.valueOf(level) + "%");
      //  do your stuff here
    }
  };

并在 onCreate() 中注册广播 class

registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

Monitoring the Battery Level and Charging State

你需要写一个BroadcastReceiver来实现你想要的。

  1. AndroidManifest.xml

    中添加接收者
    <receiver android:name=".PowerConnectionReceiver">
       <intent-filter>
         <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
         <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
       </intent-filter>
    </receiver>
    
  2. BroadcastReceiver

    public class PowerConnectionReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
           int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
           boolean isFull = status == BatteryManager.BATTERY_STATUS_FULL;
           // Do your job after checking for isFull
        }
    }
    

在此处阅读更多相关信息:Monitoring Device Battery Status

注意事项: 使用 Android O,您可能需要转移到 JobSchedulerJobDispatcher,因此请在此处阅读 Background Services in Android O

您需要设置一个广播接收器。

https://developer.android.com/training/monitoring-device-state/battery-monitoring.html