zoukankan      html  css  js  c++  java
  • [置顶] 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>


  • 相关阅读:
    模板与继承之艺术——空基类优化
    模板的多态(静多态)威力
    Linux在vi编辑模式下如何查找
    PHP var_dump() 函数
    PHP empty() 函数
    IOS连接代理后自动关闭
    charles:屏蔽web网页的抓包信息(proxy)
    Python-unittest单元测试框架总结
    fiddler过滤域名:仅显示指定的域名
    Java中System.getProperties()方法获取的系统属性
  • 原文地址:https://www.cnblogs.com/anjon520/p/3249929.html
Copyright © 2011-2022 走看看