使用广播检测手机电池代码如下:
private static final String SYSTEMACTION_BATTERY_CHANGED = Intent.ACTION_BATTERY_CHANGED; IntentFilter filter_system = new IntentFilter(); filter_system.addAction(SYSTEMACTION_BATTERY_CHANGED); registerReceiver(systemReceiver, filter_system);
[BroadcastReceive方法代码]
private BroadcastReceiver systemReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(SYSTEMACTION_BATTERY_CHANGED)) { int status = intent.getIntExtra("status", -1); boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL; int chargePlug = intent.getIntExtra("plugged", -1); boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB; boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC; if ((isCharging && usbCharge) || (isCharging && acCharge)) { Toast.makeText(context, "------", Toast.LENGTH_SHORT) .show(); Intent intet = new Intent("com.charging.Broadcast.music"); context.stopService(intet); } else { Intent intet = new Intent("com.charging.Broadcast.music"); context.startService(intet); } } } };
[MusicService.java]
public class MusicService extends Service { private MediaPlayer mPlayer; @Override public void onCreate() { super.onCreate(); mPlayer = MediaPlayer.create(this, R.raw.a); } @Override public void onDestroy() { super.onDestroy(); mPlayer.release(); stopSelf(); } @Override @Deprecated public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub super.onStart(intent, startId); mPlayer.start(); } @Override public IBinder onBind(Intent intent) { return null; } }
清单文件里注册代码
<service android:name="com.charging.Broadcast.MusicService" > <intent-filter> <action android:name="com.charging.Broadcast.music" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </service>