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

摘要:
发送通知。这封电子邮件将讨论如何获取Android设备上的电源状态。为了实现这一目标,我们将使用无线电。
 

发送通知

 
header_battery_level_article

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

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.
battery_level_screen

在Android Studio 中新建一个工程


Create a project in Android Studio step1

Create a project in Android Studio step2

Create a project in Android Studio step3

Create a project in Android Studio step3

在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>

Change battery level to 50% use terminal
Next step is change battery level on emulator.
 Change battery level to 12% use terminal
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

免责声明:文章转载自《用广播监听安卓设备电量状态》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇iOS开发:第一个iOS程序分析——AppDelegate.h文件和视图View、视图控制器ViewController【 java版坦克大战--绘图技术】 绘制坦克下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

csv文件转换json文件

import java.io.*; import java.util.Arrays; import java.util.List; // CSV文件转 json文件 // 使用csvToJSon对象的.ConvertToJson方法 带入 csv文件路径及导出路径。 public class CSVToJSon { //cvs文件 pri...

Java 的ArrayList构造方法

目录 ArrayList 构造方法使用 ArrayList 类常用方法 ArrayList集合存储字符串遍历 简单的学生管理系统   1、ArrayList 构造方法 ArrayList类概述  什么是集合   提供一种存储空间可变的存储模型,存储的数据容量可以发生改变 ‘   ArrayList集合的特点 底层是数组实现的,长度可以变化   泛型的...

NETCore Bootstrap Admin 通用后台管理权限 [2]: Blazor 版本介绍

前言 上一篇介绍过了前后台分离的 NET Core 通用权限管理系统 在这篇文章简要的介绍了 Bootstrap Admin 后台管理框架的一些功能。本篇文章带来的是微软最新出的 Blazor 版本的 NET Core 通用权限管理系统 Blazor 简介 至于 Blazor 是什么,Blazor 的优缺点小伙伴们可以自行在园子里搜索一下,相关介绍还是非常...

Effective Modern C++:05右值引用、移动语义和完美转发

         移动语义使得编译器得以使用成本较低的移动操作,来代替成本较高的复制操作;完美转发使得人们可以撰写接收任意实参的函数模板,并将其转发到目标函数,目标函数会接收到与转发函数所接收到的完全相同的实参。右值引用是将这两个不相关的语言特性连接起来的底层语言机制,正是它使得移动语义和完美转发成了可能。 23:理解std::move和std::forw...

android xml 布局文件中 android:ems="10"

宽度为10个字符的宽度xml中 android:ems属性 ,作为EditText 默认生成 的属性,其含义是需要编辑的 字符串长度 。设置为10时,最多编辑 10个em ,一个em单位是 两个inch ,但是随着自动调整,在Android中 em代表‘M’的数量 。但是 EditText的属性 ,只有在 android:layout_width=“wra...

C# 互操作性入门系列(二):使用平台调用调用Win32 函数

本文转载自:https://www.cnblogs.com/zhili/archive/2013/01/21/PInvoke.html 本专题概要: 引言 如何使用平台调用Win32 函数——从实例开始 当调用Win32函数出错时怎么办?——获得Win32函数的错误信息 小结 一、引言 上一专题对.NET 互操作性做了一个全面的概括,其中讲到.NET平...