1. 程式人生 > >《老羅Android》監聽電量變化、Broadcast實現開機啟動

《老羅Android》監聽電量變化、Broadcast實現開機啟動

1. Broadcast監聽電量變化
   如果我們閱讀軟體,可能是全屏閱讀,這個時候使用者就看不到剩餘的電量,我們就可以為他們提供電量的資訊。要想做到這一點,我們需要接收一條電量變化的廣播,然後獲取百分比資訊.
public class MainActivity extends Activity {
private BatteryBroadCastReceiver receiver;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	textView = (TextView) this.findViewById(R.id.textView1);
}
public class BatteryBroadCastReceiver extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
			// 獲取當前電量
			int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
			// 電量的總刻度
			int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 1);
			textView.setText("電池電量為" + ((level * 100) / scale) + "%");
			// if (level < 15) {
			// // dosomething/////
			// }
		}
	}
}
protected void onResume() {
	super.onResume();
	receiver = new BatteryBroadCastReceiver();
	// 監聽電量變化的意圖
	IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
	registerReceiver(receiver, filter);
}
@Override
protected void onPause() {
	super.onPause();
	unregisterReceiver(receiver);
}
}
上面是動態註冊,也可以採用靜態註冊:
<receiver android:name=".BatteryBroadCastReceiver">  
    <intent-filter>  
        <action android:name="android.intent.action.BATTERY_CHANGED"/>  
        <category android:name="android.intent.category.DEFAULT" />  
    </intent-filter>  
</receiver>
在Manifest中新增授權:
   <uses-permission android:name="android.permission.BATTERY_STATS"/>
假如你在Activity.onResume()中註冊了receiver廣播,那麼你要在Activtity.onPause()方法中登出它。
      當然,有些時候我們是要立即獲取電量的,而不是等電量變化的廣播,比如當閱讀軟體開啟時立即顯示出電池電量。我們可以按以下方式獲取:
Intent batteryIntent = getApplicationContext().registerReceiver(null,  
        new IntentFilter(Intent.ACTION_BATTERY_CHANGED));  
int currLevel = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);  
int total = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 1);  
int percent = currLevel * 100 / total;  
Log.i("battery", "battery: " + percent + "%");  
2. Broadcast實現開機啟動
    我們經常會有這樣的應用場合,比如啟動一個Activity,需要實現開機啟動的功能。要實現這個功能,我們就可以訂閱系統“啟動完成”這條廣播,接收到這條廣播後我們就可以啟動自己的服務了。
要實現開機啟動,就要在 Manifest中監聽:
新增許可權:  <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
註冊 receiver: 

<receiver android:name=".StartBootComplete" >
      <intent-filter>
       <action android:name="android.intent.action.BOOT_COMPLETED" ></action> <!-- 註冊開機廣播地址-->
       <category android:name="android.intent.category.DEFAULT" ></category>
      </intent-filter>
</receiver>
實現一個廣播接收者:
public class StartBootComplete extends BroadcastReceiver {
	static final String action_boot="android.intent.action.BOOT_COMPLETED"; 
	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equals(action_boot)){ 
            Intent bootStartIntent=new Intent(context,MainActivity.class); 
            bootStartIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
            context.startActivity(bootStartIntent); 
        }
	}
}
  也可以啟動一個service,如訊息推送服務:
public void onReceive(Context context, Intent intent) {  
        Intent service = new Intent(context, MsgPushService.class);  
        context.startService(service);  
        Log.i(TAG, "Boot Complete. Starting MsgPushService...");  
}  
在這個服務中可以制定你想要的操作:
public class MsgPushService extends Service {  
    @Override  
    public void onCreate() {  
        super.onCreate();  
        Log.i(TAG, "onCreate called.");  
    }        
    @Override  
    public int onStartCommand(Intent intent, int flags, int startId) {  
        Log.i(TAG, "onStartCommand called.");  
        return super.onStartCommand(intent, flags, startId);  
    }    
    @Override  
    public IBinder onBind(Intent arg0) {  
        return null;  
    }  
} 
記得要在Manifest中加入你的service宣告:
<service android:name=".MsgPushService"/>