Android学习之BroadcastReceiver总结

来源:互联网 发布:买数据 编辑:程序博客网 时间:2024/05/16 17:08

Android学习之BroadcastReceiver总结

代码下载:http://download.csdn.net/detail/nuptboyzhb/4482544

关于BroadcastReceiver的概述:
①广播接收器是一个专注于接收广播通知信息,并做出对应处理的组件。很多广播是源自于系统代码的──比如,通知时区改变、电池电量低、拍摄了一张照片或者用户改变了语言选项。应用程序也可以进行广播──比如说,通知其它应用程序一些数据下载完成并处于可用状态。
②应用程序可以拥有任意数量的广播接收器以对所有它感兴趣的通知信息予以响应。所有的接收器均继承自BroadcastReceiver基类
广播接收器没有用户界面。然而,它们可以启动一个activity来响应它们收到的信息,或者用NotificationManager来通知用户。通知可以用很多种方式来吸引用户的注意力──闪动背灯、震动、播放声音等等。一般来说是在状态栏上放一个持久的图标,用户可以打开它并获取消息。

BroadcastReceiver事件分类

①   系统广播事件,比如:ACTION_BOOT_COMPLETED(系统启动完成后触发),ACTION_TIME_CHANGED(系统时间改变时触发),ACTION_BATTERY_LOW(电量低时触发)等等。

②   用户自定义的广播事件。

BroadcastReceiver事件的编程流程

①   注册广播事件:注册方式有两种,一种是静态注册,就是在 AndroidManifest.xml文件中定义,注册的广播接收器必须要继承BroadcastReceiver;另一种是动态注册,是在程序中使用Context.registerReceiver注册,注册的广播接收器相当于一个匿名类。两种方式都需要IntentFIlter

②   发送广播事件:通过Context.sendBroadcast来发送,由Intent来传递注册时用到的Action。

③   接收广播事件:当发送的广播被接收器监听到后,会调用它的onReceive()方法,并将包含消息的Intent对象传给它。onReceive中代码的执行时间不要超过5s,否则Android会弹出超时dialog。

BroadcastReceiver事件的编程举例

说明:该项目举例说明了4种情况的广播事件,静态注册的系统广播事件、静态注册的用户自定义广播事件、动态注册的系统广播事件和动态注册的用户自定义广播事件。

1.    MainActivity.java文件内容

package com.byread;

 

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.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.Toast;

 

publicclass MainActivityextends Activity {

   private ButtonsendStaticBtn;

   private ButtonsendDynamicBtn;

   private ButtonsendSystemBtn;

   privatestaticfinal StringSTATICACTION ="com.byread.static";

privatestaticfinal StringDYNAMICACTION ="com.byread.dynamic";

   //系统Action:

privatestaticfinal StringSYSTEMACTION = Intent.ACTION_BATTERY_CHANGED;

   //重写ActivityonCreate方法

   @Override

   publicvoid onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

      setContentView(R.layout.main);

      sendStaticBtn = (Button)findViewById(R.id.send_static);

      sendDynamicBtn = (Button)findViewById(R.id.send_dynamic);

      sendSystemBtn = (Button)findViewById(R.id.send_system);

      sendStaticBtn.setOnClickListener(newMyOnClickListener());

      sendDynamicBtn.setOnClickListener(newMyOnClickListener());

      sendSystemBtn.setOnClickListener(newMyOnClickListener());

   }

//内部类,用于监听按钮消息

   class MyOnClickListenerimplements OnClickListener{

      @Override

      publicvoid onClick(View v) {

         //发送自定义静态注册广播消息

         if(v.getId() == R.id.send_static){

            Log.e("MainActivity","发送自定义静态注册广播消息");

            Intentintent =newIntent();

            intent.setAction(STATICACTION);

            intent.putExtra("msg","接收静态注册广播成功!");

            sendBroadcast(intent);

         }

         //发送自定义动态注册广播消息

         elseif(v.getId() == R.id.send_dynamic){

            Log.e("MainActivity","发送自定义动态注册广播消息");

            Intentintent =newIntent();

            intent.setAction(DYNAMICACTION);

            intent.putExtra("msg","接收动态注册广播成功!");

            sendBroadcast(intent);

         }

// 发送系统动态注册广播消息。当手机连接充电设备时会由系统自己发送广播消息。

         elseif(v.getId() == R.id.send_system){

            Log.e("MainActivity","发送系统动态注册广播消息");

            Intentintent =newIntent();

            intent.setAction(SYSTEMACTION);

            intent.putExtra("msg","正在充电。。。。");

         }

      }

   }

    //重写MainActivityonStart()函数

   @Override

   protectedvoid onStart() {

      super.onStart();

      Log.e("MainActivity","注册广播事件");

      // 1注册自定义动态广播消息

      IntentFilterfilter_dynamic =new IntentFilter();

      filter_dynamic.addAction(DYNAMICACTION);

      registerReceiver(dynamicReceiver, filter_dynamic);

      // 1注册系统动态广播消息

      IntentFilterfilter_system =new IntentFilter();

      filter_system.addAction(SYSTEMACTION);

      registerReceiver(systemReceiver, filter_system);

   }

    // 2自定义动态广播接收器,内部类

   private BroadcastReceiverdynamicReceiver =new BroadcastReceiver() {

     

      @Override

      publicvoid onReceive(Context context, Intent intent) {

         Log.e("MainActivity","接收自定义动态注册广播消息");

         if(intent.getAction().equals(DYNAMICACTION)){

            String msg = intent.getStringExtra("msg");

            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();

         }

      }

   };

// 2 系统动态广播接收器,内部类

   private BroadcastReceiversystemReceiver =new BroadcastReceiver() {

     

      @Override

      publicvoid onReceive(Context context, Intent intent) {

         Log.e("MainActivity","接收系统动态注册广播消息");

         if(intent.getAction().equals(SYSTEMACTION)){

            String msg = intent.getStringExtra("msg");

            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();

         }

      }

   };

}

2.    自定义静态注册广播消息接收器

package com.byread;

 

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.widget.Toast;

/**

 *自定义静态注册广播消息接收器

 * @authorzuolongsnail

 *

 */

publicclass StaticReceiverextends BroadcastReceiver {

 

   @Override

   publicvoid onReceive(Context context, Intent intent) {

      String msg= intent.getStringExtra("msg");

      Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();

   }

}

 

3.    系统静态注册广播消息接收器

package com.byread;

 

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.util.Log;

import android.widget.Toast;

 

/**

 *系统静态注册广播消息接收器

 *

 * @authorzuolongsnail

 *

 */

publicclass SystemReceiverextends BroadcastReceiver {

 

   @Override

   publicvoid onReceive(Context context, Intent intent) {

      if(intent.getAction().equals(Intent.ACTION_BATTERY_LOW)) {

         Log.e("SystemReceiver","电量低提示");

         Toast.makeText(context,"您的手机电量偏低,请及时充电", Toast.LENGTH_SHORT).show();

      }

   }

}

4.    main.xml布局文件

<?xmlversion="1.0"encoding="utf-8"?>

<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"

   android:orientation="vertical"android:layout_width="fill_parent"

   android:layout_height="fill_parent">

   <TextViewandroid:layout_width="fill_parent"

      android:layout_height="wrap_content"android:text="@string/hello"/>

   <Buttonandroid:id="@+id/send_static"android:layout_width="wrap_content"

      android:layout_height="wrap_content"android:text="发送自定义静态注册广播"/>

   <Buttonandroid:id="@+id/send_dynamic"android:layout_width="wrap_content"

      android:layout_height="wrap_content"android:text="发送自定义动态注册广播"/>

   <Buttonandroid:id="@+id/send_system"android:layout_width="wrap_content"

      android:layout_height="wrap_content"android:text="发送系统动态注册广播"/>

</LinearLayout>

5. AndroidManifest.xml文件

<?xmlversion="1.0"encoding="utf-8"?>

<manifestxmlns:android="http://schemas.android.com/apk/res/android"

   package="com.byread"android:versionCode="1"android:versionName="1.0">

   <applicationandroid:icon="@drawable/icon"android:label="@string/app_name">

      <activityandroid:name=".MainActivity"android:label="@string/app_name">

         <intent-filter>

            <actionandroid:name="android.intent.action.MAIN"/>

            <categoryandroid:name="android.intent.category.LAUNCHER"/>

         </intent-filter>

      </activity>

      <!--注册自定义静态广播接收器-->

      <receiverandroid:name=".StaticReceiver">

         <intent-filter>

            <actionandroid:name="com.byread.static"/>

         </intent-filter>

      </receiver>

      <!--注册系统静态广播接收器-->

      <receiverandroid:name=".SystemReceiver">

         <intent-filter>

            <actionandroid:name="android.intent.action.BATTERY_LOW"/>

         </intent-filter>

      </receiver>

   </application>

</manifest>

模块二:LocalBroadcastManager

优点:

1.应用内的广播,比Broadcast更安全

2.不牵涉到进程间通信,更有效

3.更安全

使用方式:

1.注册:

IntentFilter intentFilter = new IntentFilter();intentFilter.addAction("XLocalBroadcast");LocalBroadcastManager.getInstance(this).registerReceiver(receiver, intentFilter);

2.写一个广播接收器:

private BroadcastReceiver receiver = new BroadcastReceiver(){@Overridepublic void onReceive(Context context, Intent intent) {//在intent中获取广播中的参数};};

3.发送广播

Intent intent = new Intent();intent.putExtra("message", "send local broadcast");LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

4.注销广播:

LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);