Android 获取手机电量

package com.example.androidtest;

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

public class MainActivity extends Activity {

	private TextView textView1=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		textView1=(TextView)findViewById(R.id.textView1);
		batteryLevel();
	}
	/*获取电量*/
	private void batteryLevel() {  
        BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {  
            public void onReceive(Context context, Intent intent) { 
                context.unregisterReceiver(this); 
                /*获得当前电量  */
                int rawlevel = intent.getIntExtra("level", -1);
                /*获得总电量  */
                int scale = intent.getIntExtra("scale", -1);
                int level = -1;  
                if (rawlevel >= 0 && scale > 0) {  
                    level = (rawlevel * 100) / scale;  
                }  
                textView1.setText("Battery Level Remaining: " + level + "%");  
            }  
        };  
        IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);  
        registerReceiver(batteryLevelReceiver, batteryLevelFilter);  
    } 
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

你可能感兴趣的:(android,获取手机电量)