广播接收器-BroadcastReceiver 电池电量显示

参考《Android移动开发入门与进阶》

 

广播接收器是一种专门用来接收广播通知信息的,并作出相应的处理的组件。比如通知电量过低,拍照,发短信,来电等

Broadcast Recevier有两种注册方式:一种是通过AndroidManifest.xml,另一种是通过Context.registerReceiver()进行注册。

广播接收器只有一个回调方法
void onReceive(Context context,Intent intent)

实例:电池电量显示

 

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Battery Level:"
    android:id="@+id/tvBatteryLevel"
    />
</LinearLayout>

 

BatterycastReceiver.java

 

package org.loulijun.battery;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.TextView;

public class BatteryInfoReceiver extends Activity {
    /** Called when the activity is first created. */
 private TextView tvBatteryLevel;
 private BroadcastReceiver mBatteryInfoReceiver=new BroadcastReceiver()
 {

  @Override
  public void onReceive(Context context, Intent intent) {
   // TODO Auto-generated method stub
   String action=intent.getAction();
   if(Intent.ACTION_BATTERY_CHANGED.equals(action))
   {
    int level=intent.getIntExtra("level",0);
    int scale=intent.getIntExtra("scale",100);
    tvBatteryLevel.setText("Battery Level:"+String.valueOf(level*100/scale)+"%");
   }
  }
  
 };
 
 
    @Override
 protected void onPause() {
  // TODO Auto-generated method stub
  super.onPause();
  unregisterReceiver(mBatteryInfoReceiver);
 }


 @Override
 protected void onResume() {
  // TODO Auto-generated method stub
  super.onResume();
  registerReceiver(mBatteryInfoReceiver,new IntentFilter(
    Intent.ACTION_BATTERY_CHANGED));
 }


 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tvBatteryLevel=(TextView)findViewById(R.id.tvBatteryLevel);
    }
}

 

首先,在方法onCreate(Bundle savedInstanceState)中,通过R.java文件索引获得TextView实例tvBatteryLevel,用来展示电量信息。然后再方法onResume()中注册一个广播接收器mBatteryInfoReceiver,该接收器是我们自定义的一个广播接收器BroadcastReceiver。这样,当BatteryInfoReceiver这个Activity处于前台时,就会开始监听系统电池电量状态的改变,注意,实在方法registerReceiver()中直接传递一个IntentFilter对象,而不是在manifest文件中配置。mBatteryInfoReceiver收到广播消息时,调用onReceive()方法进行处理:首先解析收的的Intent对象,解析并判断其行动,然后获得ACTION_BATTERY_CHANGED这个Intent对象的“level”和"scale"值,最后把结果显示在UI上,在方法onPause()中注销广播监听器,这样当BatteryInfoReceiver这个Activity不处于前台时,用户将不再看到电池信息,程序运行结果如下

人

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值