我正在开发一个应用程序,我希望在设备电源打开时启动服务,并在设备电源关闭时停止服务。有人能告诉我如何确定设备状态(打开或关闭)吗?
答案 0 :(得分:0)
根据android documentation,您可以像这样定义BroadcastRecevier
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;
//Start/stop your service here
if(isCharging) {
context.startService(...);
} else {
context.stopService(...);
}
}
}
并在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>