我一直在尝试使用反射以防有人插入充电器或usb电缆为他们的设备充电。有谁能告诉我android是如何与硬件交互的吗?
我对USB不太感兴趣我对红色(HTC是琥珀色)led更感兴趣,当我们连接设备充电或通知时,它会发光。
为ACTION_BATTERY_CHANGED
设置BroadcastReceiver。一个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;
}
}