我正在尝试在android中为电池做充电日志,它工作正常。但问题是我无法检测到电池电量以及充电器的状态。供您参考,我是使用 android 的初学者,希望有人可以帮助我编写代码。
public class ListViewA extends Activity {
/**Called when the activity is first created.*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
ListView lv= (ListView)findViewById(R.id.listview);
// create the grid item mapping
String[] from = new String[] {"col_1", "col_2", "col_3", "col_4"};
int[] to = new int[] { R.id.item2, R.id.item3, R.id.item4, R.id.item5};
// prepare the list of all records
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = -1;
if (rawlevel >= 0 && scale > 0) {
level = (rawlevel * 100) / scale;
}
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
String strStatus = "";
switch (status) {
case BatteryManager.BATTERY_STATUS_UNKNOWN:
strStatus= "Unknown Charged";
break;
case BatteryManager.BATTERY_STATUS_CHARGING:
strStatus = "Charged Plugged";
break;
case BatteryManager.BATTERY_STATUS_DISCHARGING:
strStatus = "Charged Unplugged";
break;
case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
strStatus = "Not Charging";
break;
case BatteryManager.BATTERY_STATUS_FULL:
strStatus = "Charged Completed";
break;
}
}
};
HashMap<String, String> map = new HashMap<String, String>();
map.put("col_1", DateFormat(cal.getTime()));
int level = -1;
map.put("col_3", Integer.toString(level) + "%");
String strStatus = "";
map.put("col_4", strStatus);
fillMaps.add(map);
// fill in the grid_item layout
SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.grid_item, from, to);
lv.setAdapter(adapter);
}
private String DateFormat(Date time) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
return dateFormat.format(cal.getTime());
}
}