通過BroadcastReceiver實現監聽電池電量

KO_159發表於2016-01-07

Broadcast是一種在應用程式之間進行傳輸資訊的機制。BroadcastReceiver對傳送出來的Broadcast進行過濾並響應。廣播Intent的傳送是通過Context.sentBroadcast(),Context.sentOrderedBroadcast()或者Context.sendStickyBroadcast()方法來實現。通常一個廣播Intent可以被訂閱了此Intent的多個廣播接收者所接收。

廣播接收器只有一個回撥方法,即void onReceive( Context context,Intent intent)方法,當廣播訊息抵達接收器時系統將呼叫onReceive()方法並且把包括訊息的Intent物件傳遞給他。廣播接收器只有在執行這個方法的時候才處於活躍狀態,當該方法執行完畢後,廣播接收器處於失活狀態。

package com.example.android_04_demo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

	private TextView batteryTextView;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        batteryTextView = (TextView) findViewById(R.id.text);
        }

    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub//註冊廣播監聽器
    	super.onResume();
    	registerReceiver(batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    	
    }

    @Override
    protected void onPause() {
    	// TODO Auto-generated method stub登出廣播監聽器
    	super.onPause();
    	
    	unregisterReceiver(batteryInfoReceiver);
    }
    private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
		
		@Override接收廣播
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
				
				int level = intent.getIntExtra("level", 0);
				int scale = intent.getIntExtra("scale",100);
				
				batteryTextView.setText("電量:"+String.valueOf(level*100/scale)+"%");
			}
		}
	};
}


相關文章