• [置顶] Android代码广播检测手机电池


    使用广播检测手机电池代码如下:

    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>


  • 相关阅读:
    如何在Centos官网下载所需版本的Centos
    Zabbix微信告警
    CentOS 7.4 源码编译安装 Redis
    zabbix源码安装后,设置为服务启动和关闭
    MySQL 快速入门教程
    mysql解决 ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)的报错
    转:Centos7安装zabbix3.4超详细步骤解析
    centos7使用Gogs搭建Git服务器
    Centos7 使用firewall管理防火墙
    zabbix登录密码重置方法
  • 原文地址:https://www.cnblogs.com/anjon520/p/3249929.html
Copyright © 2020-2023  润新知