用广播监听安卓设备电量状态

发送通知

这次邮件我们将会讨论怎么获取电量状态在安卓设备上,为了完成这个目标,我们将会使用到广播。

What is BroadcastReceiver?
A broadcast receiver is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android application.

The system itself broadcast event all time, as example when system gets booted or an SMS arrived, etc.

Application description
Application display of battery level and update this value when battery level changed.

在Android Studio 中新建一个工程

在String.xml中添加一个常量

  1. <string name="battery_level">Battery level:</string>
    

      

更新布局文件,在这里我叫 “activity_main.xml”

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:text="@string/battery_level"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_marginTop="8dp"
        android:layout_marginLeft="12dp"
        android:layout_marginRight="12dp"
        android:max="100"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"
        android:layout_toRightOf="@+id/textView"
        android:layout_toEndOf="@+id/textView" />

</LinearLayout>

创建一个内部类为我们的广播实现

private class BatteryBroadcastReceiver extends BroadcastReceiver {

    private final static String BATTERY_LEVEL = "level";

    @Override
    public void onReceive(Context context, Intent intent) {
        int level = intent.getIntExtra(BATTERY_LEVEL, 0);

        mBatteryLevelText.setText(getString(R.string.battery_level) + " " + level);
        mBatteryLevelProgress.setProgress(level);
    }
}

更新Activity的代码如下:

public class MainActivity extends Activity {

    private TextView mBatteryLevelText;
    private ProgressBar mBatteryLevelProgress;
    private BroadcastReceiver mReceiver;

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

        mBatteryLevelText = (TextView) findViewById(R.id.textView);
        mBatteryLevelProgress = (ProgressBar) findViewById(R.id.progressBar);

        mReceiver = new BatteryBroadcastReceiver();

        registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }

    @Override
    protected void onStop() {
        unregisterReceiver(mReceiver);
        super.onStop();
    }

    private class BatteryBroadcastReceiver extends BroadcastReceiver {

        private final static String BATTERY_LEVEL = "level";

        @Override
        public void onReceive(Context context, Intent intent) {
            int level = intent.getIntExtra(BATTERY_LEVEL, 0);

            mBatteryLevelText.setText(getString(R.string.battery_level) + " " + level);
            mBatteryLevelProgress.setProgress(level);
        }
    }
}

我们必须反注册你的接收者当activity 停止,因为如果不反注册,当你的应用程序关闭时候,进程会一直在后台接受一些信息

注册广播:

We can register receiver in AndroidManifest.xml:

<receiver android:name="BatteryBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BATTERY_CHANGED" />
</intent-filter>
</receiver>
or register our BroadcastReceiver in application
BatteryBroadcastReceiver mReceiver = new BatteryBroadcastReceiver();
registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

运行程序
We can change battery level of our emulator use console. We must connect to out AVD Emulator use console / terminal. If we run many emulator, each emulator will have unique port. Port number your emulator you can find in title of emulator window. As example port of my emulator is 5554.
Connect to emulator:

  1. telnet localhost <PORT>

Change battery level of emulator:

  1. power capacity <BATTERY_LEVEL_IN_PERCENT>


Next step is change battery level on emulator.

As you can see TextView and ProgressBar were updated.

from:http://alexzh.com/tutorials/android-battery-status-use-broadcastreceiver/?utm_source=Android+Weekly&utm_campaign=bce41f280c-Android_Weekly_149&utm_medium=email&utm_term=0_4eb677ad19-bce41f280c-337902977

时间: 2024-10-15 21:30:10

用广播监听安卓设备电量状态的相关文章

Android开发之使用广播监听网络状态变化

我们经常需要判断网络状态的变化,如有无网络,所以需要监听网络状态的变化,比如网络断开,网络连接给予友好提示.如何监听网络状态的变化呢,最近工作中需要用到这个,于是就用广播机制来实现了网络状态的监听. 使用广播机制来监听网络状态主要涉及到以下几点: 1.需要自己编写个网络广播接收器,该接收器继承BroadcastReceiver类,用来接收系统发出的广播.比如我自己写了个NetStatusReceiver广播接收器.代码如下: package com.log.system; import andr

Android 广播监听wifi

第一步:配置AndroidManifest.xml,在application结点下面添加如下代码 <receiver android:name=".NetworkConnectChangedReceiver" > <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> <action android:name="a

监听Listview的滚动状态,是否滚动到了顶部或底部

/** * @author:Jack Tony * @description : 监听listview的滑动状态,如果到了顶部就刷新数据 * @date :2015年2月9日 */ private class ListViewListener implements OnScrollListener { @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int t

Android开机和关机广播监听

Android开机.关机广播监听 一.开机广播的监听 1.在AndroidManifest.xml文件注册接收开机广播 <receiver android:name=".XXXBroadcastReceiver" > <intent-filter> <!-- 开机广播 --> <action android:name="android.intent.action.BOOT_COMPLETED" /> </inte

关于 Android ios cocos2d 中的广播监听

1. 关于广播监听 第一次使用是在Android中,broadcast.主要用在2个activity之间进行传递数据,发出一个广播,对这个广播有兴趣的就去监听它,做出相应的回应即可.主要是传递数据,触发机制比较好,跟全局变量或者单例有点像,但是使用场合有区别,比如2个activity之间传递数据,activity这种有生命周期的弄成全局变量和单例就不合适了. 2.Android的广播 发送广播: Intent intent = new Intent("OUR_BLE_CENTRAL_MANAGE

Android -- 使用广播监听Home键

//广播监听事件类 public class HomeKeyEventBroadCastReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { //do what you want System.exit(0); } } private HomeKeyEventBroadCastReceiver homeKeyEventReceiver; prote

Android利用广播监听按下HOME和电源键

package cc.testhome; import cc.testhome.HomeKeyObserver.OnHomeKeyListener; import cc.testhome.PowerKeyObserver.OnPowerKeyListener; import android.os.Bundle; import android.app.Activity; /** * Demo描述: * 利用广播监听Home键的按下和长按Home键 * 利用广播监听电源键的按下(关闭屏幕) * *

QT 监听 USB 设备 插入、拔出动作

参考网上资料,通过QT 实现 #ifndef WIDGET_H #define WIDGET_H #include <QtGui/QWidget> #include <windows.h> #include <QString> class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = 0); ~Widget(); protected: bool winEvent(MSG *msg,

vue+hbuilder监听安卓返回键问题

1.监听安卓返回键问题 效果:在一级页面按一下返回键提示退出应用,按两下退出应用;在其它页面中,按一下返回上个历史页面 1 2 import mui from './assets/js/mui.min.js' Vue.prototype.$mui = mui; 在一级页面mounted时 1 this.$mui.plusReady( () =>{ 2 var backcount = 0; 3 this.$mui.back = ()=> { 4 if (this.$mui.os.ios) ret