如何添加一个textview,显示它是否插入及其充电与否,如果充电则剩余多少时间

时间:2015-02-24 19:20:26

标签: android

我想添加一个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));
    }
}

1 个答案:

答案 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