获取手机电量百分比

获取手机电量百分比。
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.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private TextView text;
	BatteryBroadcastReciver reciver;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		initUI();
	}

	private void initUI() {
		// TODO Auto-generated method stub
		text = (TextView)findViewById(R.id.text);
		reciver=new BatteryBroadcastReciver();
		//registerReceiver(new BatteryBroadcastReciver(), new IntentFilter(Intent.ACTION_BATTERY_CHANGED));  	
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		unregisterReceiver(reciver);//取消注册
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		 //创建一个过滤器
	    IntentFilter intentFilter=new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
	    registerReceiver(reciver, intentFilter);
	}
	/**
	 * 获取手机当前电量广播
	 * @author nsc
	 *
	 */
	public class BatteryBroadcastReciver extends BroadcastReceiver{
		 public void onReceive(Context context, Intent intent) {
		        // TODO Auto-generated method stub
			 //判断当前电量是否改变
		        if(intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){
		            //获取手机当前电量		        	
		            int level=intent.getIntExtra("level", 0);
		            //获取手机总电量
		            int total=intent.getIntExtra("scale", 100);
		            text.setText("当前电量:"+(level*100)/total+"%");
		            //当电量小于15%时提示电量
		            if(level<15){
		                Toast.makeText(MainActivity.this, "当前电量已小于15%!",Toast.LENGTH_LONG).show();
		            }             
		        }
		    }
	}

}

使用权限

 <uses-permission android:name="android.permission.BATTERY_STATS"/>

 

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