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

    技术2022-05-20  38

    参考《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)