Android 获取电池信息

/*
 * 取得手机电池的剩余量
 * Android API中的BroadcastReceiver(Android.content.BroadcastReceiver)
 * 类有点像Button中的Listener,当Receiver被注册后,会在后台等待其他程序
 * 的调用,程序将通过注册BroadcastReceiver时设置的IntentFilter来捕捉系统
 * 发出的Intent.ACTION_BATTERY_CHANGED这个action,再以此取得手机电池的剩
 * 余量。
 */ 

import 略;
[java] 
public class Ex06_02Activity extends Activity { 
    private int intLevel; 
    private int intScale; 
    private Button mButton01; 
    private AlertDialog d; 
    // 创建BroadcastReceiver 
    private BroadcastReceiver mBatInfoReveiver = new BroadcastReceiver() { 
 
        @Override 
        public void onReceive(Context context, Intent intent) { 
            // TODO Auto-generated method stub 
            String action = intent.getAction(); 
            // 如果捕捉到action是ACRION_BATTERY_CHANGED 
            // 就运行onBatteryInfoReveiver() 
            if (intent.ACTION_BATTERY_CHANGED.equals(action)) { 
                intLevel = intent.getIntExtra("level", 0); 
                intScale = intent.getIntExtra("scale", 100); 
                onBatteryInfoReceiver(intLevel, intScale); 
            } 
        } 
    }; 
 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
        mButton01 = (Button) findViewById(R.id.myButton1); 
        mButton01.setOnClickListener(new OnClickListener() { 
 
            @Override 
            public void onClick(View v) { 
                // TODO Auto-generated method stub 
                // 注册一个BroadcastReceiver,作为访问电池计量之用 
                registerReceiver(mBatInfoReveiver, new IntentFilter( 
                        Intent.ACTION_BATTERY_CHANGED)); 
            } 
        }); 
    } 
 
    // 拦截到ACTION_BATTRY_CHANGED后要执行的动作 
    private void onBatteryInfoReceiver(int intLevel, int intScale) { 
        // TODO Auto-generated method stub 
        d = new AlertDialog.Builder(Ex06_02Activity.this).create(); 
        d.setTitle(R.string.str_dialog_title); 
        d.setMessage(getResources().getString(R.string.str_dialog_body) 
                + String.valueOf(intLevel * 100 / intScale) + "%"); 
        d.setButton(getResources().getString(R.string.str_button2), 
                new DialogInterface.OnClickListener() { 
 
                    @Override 
                    public void onClick(DialogInterface dialog, int which) { 
                        // TODO Auto-generated method stub 
                        // 取消注册,并关闭对话框 
                        unregisterReceiver(mBatInfoReveiver); 
                        d.dismiss(); 
                    } 
                }); 
        d.show(); 
    }; 

下面我们来看看程序运行后的结果:www.2cto.com


在Android API中有提到,要注册Intent.ACTION_BATTERY_CHANGED的Receiver只能在程序中以
Context.register Receiver()方法来注册,而不能直接在AndroidManifest.xml中注册。

你可能感兴趣的:(#,电池开发)