我想添加一个textview,显示它是否已插入并且是否充电以及是否充电然后剩余时间
public class MainActivity extends Activity {
// Create Broadcast Receiver Object along with class definition
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
@Override
// When Event is published, onReceive method is called
public void onReceive(Context c, Intent i) {
// Get Battery %
int level = i.getIntExtra("level", 0);
// Find the progressbar creating in main.xml
ProgressBar pb = (ProgressBar) findViewById(R.id.progressbar);
// Set progress level with battery % value
pb.setProgress(level);
// Find textview control created in main.xml
TextView tv = (TextView) findViewById(R.id.textfield);
// Set TextView with text
tv.setText("Battery Level: " + Integer.toString(level) + "%");
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set layout we created
setContentView(R.layout.activity_main);
// Register the receiver which triggers event
// when battery charge is changed
registerReceiver(mBatInfoReceiver, new IntentFilter(
Intent.ACTION_BATTERY_CHANGED));
}
}
答案 0 :(得分:0)
public class PowerUtil {
public static boolean isConnected(Context context) {
Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;
}
}
<强> REF 强> Check if device is plugged in
和电池电量参考 http://mihaifonoage.blogspot.de/2010/02/getting-battery-level-in-android-using.html