我一直在尝试使用反射,以防有人插入充电器或 USB 电缆为他们的设备充电。谁能告诉我android实现了什么来与硬件交互。
我对 USB 不完全感兴趣 我对红色(HTC 的琥珀色)更感兴趣,当我们连接我们的设备进行充电或通知时,它会发光。
我一直在尝试使用反射,以防有人插入充电器或 USB 电缆为他们的设备充电。谁能告诉我android实现了什么来与硬件交互。
我对 USB 不完全感兴趣 我对红色(HTC 的琥珀色)更感兴趣,当我们连接我们的设备进行充电或通知时,它会发光。
为ACTION_BATTERY_CHANGED
. Intent extra 将告诉您充电状态是什么——请参阅BatteryManager了解详细信息。
<application android:icon="@drawable/icon" android:label="@string/app_name">
<receiver android:name=".receiver.PlugInControlReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
</application>
然后
public void onReceive(Context context , Intent intent) {
String action = intent.getAction();
if(action.equals(Intent.ACTION_POWER_CONNECTED)) {
// Do something when power connected
}
else if(action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
// Do something when 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>
并在代码中
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;
}
}