android 广播监控手机电量

问题很简单 直接给出代码



    

        
    



监听需要权限

package cn.itcast.BatteryChecker;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private TextView tv_cell;
	private BatteryReceiver batteryReceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		tv_cell = (TextView) findViewById(R.id.tv_cell);
		// 注册广播接受者java代码
		IntentFilter intentFilter = new IntentFilter(
				Intent.ACTION_BATTERY_CHANGED);
		batteryReceiver = new BatteryReceiver();
		// 注册receiver
		registerReceiver(batteryReceiver, intentFilter);
	}

	/**
	 * 广播接受者
	 */
	private class BatteryReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
				int level = intent.getIntExtra("level", 0);
				tv_cell.setText("电池电量为" + level + "%");

				if (level < 15) {
					Toast.makeText(MainActivity.this, "电池电量不足15%,请及时充电", 0)
							.show();
				}
			}
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(batteryReceiver);
	}
}


你可能感兴趣的:(android四大组件)