1 主类

package com.jli.battery;import android.app.Activity;import android.app.Service;import android.content.BroadcastReceiver;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.content.ServiceConnection;import android.content.SharedPreferences;import android.graphics.BitmapFactory;import android.os.Bundle;import android.os.IBinder;import android.widget.Button;import android.widget.ImageView;import android.widget.TextView;public class Main extends Activity {private ImageView tvBatteryChanged;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        tvBatteryChanged = (ImageView)findViewById(R.id.test);        //注册一个接受广播类型        registerReceiver(new BatteryBroadcastReceiver(), new IntentFilter(Intent.ACTION_BATTERY_CHANGED));    }        /**接受电量改变广播*/    class BatteryBroadcastReceiver extends BroadcastReceiver{        @Override    public void onReceive(Context context, Intent intent) {        if(intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){        int level = intent.getIntExtra("level", 0);  int scale = intent.getIntExtra("scale", 100);   int curPower = (level * 100 / scale)/25;   switch (curPower) {case 0:tvBatteryChanged.setImageBitmap(BitmapFactory.decodeResource(Main.this.getResources(), R.drawable.power0));break;case 1:tvBatteryChanged.setImageBitmap(BitmapFactory.decodeResource(Main.this.getResources(), R.drawable.power1));break;case 2:tvBatteryChanged.setImageBitmap(BitmapFactory.decodeResource(Main.this.getResources(), R.drawable.power2));break;case 3:tvBatteryChanged.setImageBitmap(BitmapFactory.decodeResource(Main.this.getResources(), R.drawable.power3));break;case 4:tvBatteryChanged.setImageBitmap(BitmapFactory.decodeResource(Main.this.getResources(), R.drawable.power4));break;}    }    }    }}

2 xml

<?xml version="1.0" encoding="utf-8"?>

3 然后记得要加上这句,这个应该是注册电池广播的,如果不加的话会报错,放在Manifest.xml这个文件里面


4 效果图【其实代码很好理解的,都不用怎么仔细看的】


更多相关文章

  1. 【Android】性能优化:电量消耗统计
  2. Android电池电量状态源码
  3. Android 主动获取电量的方法
  4. android 获取系统电量
  5. Android 之 监控手机电量
  6. Android电池电量更新 - BatteryService(转)
  7. android获取手机电量
  8. Delphi XE5 android 获取电池电量

随机推荐

  1. Android开发常用代码
  2. Android 网络编程 API笔记 - java.net 包
  3. Android如何动态加载jar包
  4. Android用ConnectivityManager实现网络监
  5. Android:Context的作用
  6. Android Webservices 返回多行多列数据(D
  7. Android Handler的使用!!!
  8. Android(安卓)fill_parent和wrap_content
  9. Android 视图与五大布局
  10. Android程序开发的基本框架