61

我的应用程序有一个广播接收器来监听更改ACTION_POWER_CONNECTED,然后标记屏幕以保持打开状态。

我缺少的是应用程序在首次运行时检查充电状态的能力。谁能帮我用代码手动检查充电状态?

4

9 回答 9

159

感谢 CommonsWare,这是我编写的代码。

public class Power {
    public static boolean isConnected(Context context) {
        Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS;
    }
}

if (Power.isConnected(context)) {
    ...
}

或 Kotlin 版本

object Power {
    fun isConnected(context: Context): Boolean {
        val intent = context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
        val plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
        return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS
    }
}

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

于 2011-08-23T04:24:14.943 回答
33
public static boolean isPlugged(Context context) {
    boolean isPlugged= false;
    Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    isPlugged = plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;
    if (VERSION.SDK_INT > VERSION_CODES.JELLY_BEAN) {
        isPlugged = isPlugged || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS;
    }
    return isPlugged;
}

支持无线充电的小更新。

于 2014-10-27T09:57:06.810 回答
29

打电话registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED))。这将返回一个Intent定义了额外内容的函数BatteryManager,让您知道它是否已插入。

这是有效的,因为Intent.ACTION_BATTERY_CHANGED它是一个粘性广播。

于 2011-03-12T15:45:06.717 回答
11

在 Android M+ 上,您可以BatteryManager通过getSystemService(BATTERY_SERVICE). 在运行 pre-M 的设备上,您可以使用其他人提到的粘性广播。例子:

public static boolean isCharging(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        BatteryManager batteryManager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
        return batteryManager.isCharging();
    } else {
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent intent = context.registerReceiver(null, filter);
        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        if (status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL) {
            return true;
        }
    }
    return false;
}
于 2018-01-04T08:14:29.303 回答
6

您的答案在 android 参考资料中

这是示例代码:

// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                 status == BatteryManager.BATTERY_STATUS_FULL;

// How are we charging?
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
于 2014-07-01T07:31:10.743 回答
5

简单的方法是使用意图过滤器ACTION_BATTERY_CHANGED

public void checkBatteryState(View sender) {
    IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = registerReceiver(null, filter);

    int chargeState = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    String strState;

    switch (chargeState) {
        case BatteryManager.BATTERY_STATUS_CHARGING:
        case BatteryManager.BATTERY_STATUS_FULL:
            strState = "charging";
            break;
        default:
            strState = "not charging";
    }

    TextView tv = (TextView) findViewById(R.id.textView);
    tv.setText(strState);
}
于 2015-06-06T19:03:17.380 回答
3

尝试这个:

public class PowerConnectionReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = context.registerReceiver(null, ifilter);


        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging =    status == BatteryManager.BATTERY_STATUS_CHARGING ||
                                status == BatteryManager.BATTERY_STATUS_FULL;

        int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge   = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        boolean acCharge    = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;


        if (batteryStatus != null) {
            int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            float batteryPct = level / (float) scale;
        }


    }//end onReceive


}//end PowerConnectionReceiver
于 2016-05-24T06:42:37.427 回答
2
BroadcastReceiver receiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        String action = intent.getAction();
        if(action.equalsIgnoreCase(ACTION_POWER_CONNECTED))
        {


                if(chargerConnected != null )
                {
                    chargerConnected.setText("Cable Connected");
                }
                if(chargerImage != null )
                {
                    chargerImage.setImageDrawable(getResources().getDrawable(R.drawable.usb));
                }

        }else if(action.equalsIgnoreCase(ACTION_POWER_DISCONNECTED))
        {


                if(chargerConnected != null )
                {
                    chargerConnected.setText("NOT CHARGE");
                }
                if(chargerImage != null )
                {
                    chargerImage.setImageDrawable(getResources().getDrawable(R.drawable.battery_icon));
                }

            try {

                Toast.makeText(context, "Power Cable Disconnected", Toast.LENGTH_SHORT).show();
            }catch (Exception e){e.printStackTrace();}

        }
    }
};
于 2016-09-02T05:26:55.093 回答
1

这是一个粘性意图,您不需要注册 BroadcastReceiver — 通过简单地调用 registerReceiver 作为接收器传入 null ,如下一个片段所示,返回当前电池状态意图。您可以在此处传入一个实际的 BroadcastReceiver 对象,但我们将在后面的部分中处理更新,因此没有必要。

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);

您可以提取当前的充电状态,如果设备正在充电,无论是通过 USB 还是 AC 充电器充电:

// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                     status == BatteryManager.BATTERY_STATUS_FULL;

// How are we charging?
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

每当设备连接或断开电源时,BatteryManager 都会广播一个操作。即使在您的应用程序没有运行时接收这些事件也很重要——特别是因为这些事件会影响您启动应用程序以启动后台更新的频率——因此您应该在清单中注册一个 BroadcastReceiver 以通过以下方式监听这两个事件在意图过滤器中定义ACTION_POWER_CONNECTEDACTION_POWER_DISCONNECTED 。

<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>

在关联的 BroadcastReceiver 实现中,您可以提取当前的充电状态和方法,如上一步中所述。

public class PowerConnectionReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                            status == BatteryManager.BATTERY_STATUS_FULL;

        int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
    }
}
于 2017-02-27T22:32:58.353 回答