• [置顶] 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>


  • 相关阅读:
    POJ 3687 Labeling Balls()
    POJ 2777 Count Color(线段树之成段更新)
    POJ 1961 Period( KMP )*
    POJ 2406 Power Strings (KMP)
    hdu 2199 Can you solve this equation?(二分搜索)
    10679 多少个1
    POJ 2823 Sliding Window
    POJ 2299 Ultra-QuickSort(线段树入门)
    最短路径—Dijkstra算法和Floyd算法
    poj1125&zoj1082Stockbroker Grapevine(Floyd算法)
  • 原文地址:https://www.cnblogs.com/anjon520/p/3249929.html
Copyright © 2020-2023  润新知