Android:广播机制

来源:互联网 发布:护肤品市场数据 编辑:程序博客网 时间:2024/06/14 09:44

Android:广播机制

在Android中,Broadcast是一种广泛运用的在应用程序之间传输信息的机制。而BroadcastReceiver是对发送出来的 Broadcast进行过滤接受并响应的一类组件。

 

下面将详细的阐述如何发送Broadcast和使用BroadcastReceiver过滤接收的过程:

 

  首先在需要发送信息的地方,把要发送的信息和用于过滤的信息(如Action、Category)装入一个Intent对象,然后通过调用 sendOrderBroadcast()或sendStickyBroadcast()方法,把 Intent对象以广播方式发送出去。

 

  当Intent发送以后,所有已经注册的BroadcastReceiver会检查注册时的IntentFilter是否与发送的Intent相匹配,若匹配则就会调用BroadcastReceiver的onReceive()方法。所以当我们定义一个BroadcastReceiver的时候,都需要实现onReceive()方法。

 

  注册BroadcastReceiver有两种方式:

 

  静态注册:在AndroidManifest.xml中用标签生命注册,并在标签内用标签设置过滤器。

 

  <receiverandroid:name="myRecevice">   //继承BroadcastReceiver,重写onReceiver方法

 

    <intent-filter>   

 

      <actionandroid:name="com.dragon.net"></action> //使用过滤器,接收指定action广播

 

      </intent-filter>

 

  </receiver>

 

  动态注册:

 

  IntentFilterintentFilter = new IntentFilter();

 

  intentFilter.addAction(String);   //为BroadcastReceiver指定action,使之用于接收同action的广播

 

     registerReceiver(BroadcastReceiver,intentFilter);

 

  一般:在onStart中注册,onStop中取消unregisterReceiver

 

  指定广播目标Action:Intent intent = newIntent(actionString);

 

  并且可通过Intent携带消息:intent.putExtra("msg", "hi,我通过广播发送消息了");

 

  发送广播消息:Context.sendBroadcast(intent)

 

短信拦截案例:

java代码:

public class SmsBroadCastReceiver extendsBroadcastReceiver   

{  

 

   @Override 

   public void onReceive(Context context, Intent intent)  

   {  

       Bundle bundle = intent.getExtras();  

       Object[] object = (Object[])bundle.get("pdus");  

       SmsMessage sms[]=new SmsMessage[object.length];  

       for(int i=0;i<object.length;i++)  

       {  

           sms[0] = SmsMessage.createFromPdu((byte[])object[i]);  

           Toast.makeText(context, "来自"+sms[i].getDisplayOriginatingAddress()+" 的消息是:"+sms[i].getDisplayMessageBody(),Toast.LENGTH_SHORT).show();  

       }  

       //终止广播,在这里我们可以稍微处理,根据用户输入的号码可以实现短信防火墙。  

       abortBroadcast();  

   }  

       

}

 

AndroidManifest.xml中配置广播:

<?xml version="1.0"encoding="utf-8"?> 

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

     package="spl.broadCastReceiver" 

     android:versionCode="1" 

     android:versionName="1.0"> 

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

       <activity android:name=".BroadCastReceiverActivity" 

                 android:label="@string/app_name"> 

           <intent-filter> 

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

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

           </intent-filter> 

       </activity> 

          

       <!--广播注册--> 

       <receiver android:name=".SmsBroadCastReceiver"> 

           <intent-filter android:priority="20"> 

                <actionandroid:name="android.provider.Telephony.SMS_RECEIVED"/> 

           </intent-filter> 

       </receiver> 

          

   </application> 

      

   <uses-sdk android:minSdkVersion="7" /> 

      

   <!-- 权限申请--> 

   <uses-permissionandroid:name="android.permission.RECEIVE_SMS"></uses-permission> 

      

</manifest>  

 

Android:notification

在 Android 手机界面最上方有一条显示时间,信号强度和电池状态等信息的区域,这是 Android 手机的状态栏Status Bar。当系统有一些重要的信息要通知手机用户时,例如收到新短信,或者是收到新邮件,或者是有未接电话等等,系统通常会把信息显示在状态栏中,有的仅显示小图片,有的则显示文字和小图片,用手指按住状态栏往下拉,还可以展开状态栏,查看所有系统发出的信息。

    Notification 可以在屏幕最顶部的状态栏上显示一个图标通知,通知的同时可以播放声音,以及振动来提示用户,点击通知还可以进入指定的 Activity 。

 

NotificationManager

·获取实例:

  NotificationManager nm= (NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);

·公共方法:

Notification

  

状态栏提醒必须设置的三个方面

·提示图标

·提醒的标题和提醒的内容文本

·PendingIntent

状态栏提醒的可选设置

·提醒文本( ticker-text )

·声音提醒

·振动提醒

·灯光闪烁

 

使用步骤

1、获取NotificationManager:

   NotificationManagerm_NotificationManager = 

     (NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);

2、定义一个Notification: 

   Notification m_Notification = new Notification();

3、设置 Notification的各种属性:

   //设置通知在状态栏显示的图标
  m_Notification.icon = R.drawable.icon;

   //当我们点击通知时显示的内容
  m_Notification.tickerText = "Button1 通知内容.....";     

   //通知时发出的默认声音
   m_Notification.defaults= Notification.DEFAULT_SOUND;

   //设置通知显示的参数

   Intent m_Intent =new Intent(this, DesActivity.class); 

   PendingIntent m_PIntent= PendingIntent.getActivity(NotificationDemo.this, 0, m_Intent, 0);

  m_Notification.setLatestEventInfo(this, "Button1", "Button1通知", m_PIntent );

   //这个可以理解为开始执行这个通知
  m_NotificationManager.notify(0, m_Notification);

4、既然可以增加同样我们也可以删除,当然是只是删除你自己增加的。

  m_NotificationManager.cancel(0); //这里的0是一个ID号码,和notify第一个参数0一样。

 

提醒的更新

每一个提醒都对应有一个唯一标识符ID,在发布提醒时指定的:

NotificationManager.notify(ID, notification)   

在更新提醒的时候,只需要在修改Notification的一些属性之后,再调用其setLatestEventInfo(),然后重新发送一次通知即可。

 

Notification丰富的提示方式

a) tickerText :显示文本提示

   notification.tickerText = "hello";

b) sound :发出提示音

    notification.defaults|= Notification.DEFAULT_SOUND;

    notification.sound= Uri.parse("file:///sdcard/notification/ringer.mp3");

    notification.sound= Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");

c) vibrate :手机振动

    notification.defaults |= Notification.DEFAULT_VIBRATE;

     long[] vibrate= {0,100,200,300};

    notification.vibrate = vibrate;

d) ledARGBledOnMSledOffMS :LED灯闪烁

    notification.defaults |= Notification.DEFAULT_LIGHTS;

    notification.ledARGB = 0xff00ff00;

    notification.ledOnMS = 300;

    notification.ledOffMS = 1000;

    notification.flags |= Notification.FLAG_SHOW_LIGHTS;

 

声音提醒

·使用默认声音

  notification.defaults |=Notification.DEFAULT_SOUND;

·使用自定义声音

  notification.sound =Uri.parse("file:///sdcard/notification/ringer.mp3");

·注:如果定义了默认声音,那么自定义声音将被覆盖

 

振动提醒

·使用默认振动

  notification.defaults |=Notification.DEFAULT_VIBRATE;

·使用自定义振动

  long[] vibrate ={0,100,200,300}; 
  notification.vibrate = vibrate;

·注:如果定义了默认振动,那么自定义振动将被覆盖

//使用震动要设权限

<uses-permission android:name="android.permission.VIBRATE">

</uses-permission>

 

灯光闪烁提醒

·使用默认闪烁

  notification.defaults |=Notification.DEFAULT_LIGHTS;

·使用自定义闪烁

  notification.ledARGB =0xff00ff00; // LED灯的颜色,绿灯
 notification.ledOnMS = 300; //LED灯显示的毫秒数,300毫秒
 notification.ledOffMS = 1000; //LED灯关闭的毫秒数,1000毫秒
  notification.flags|= Notification.FLAG_SHOW_LIGHTS;//必须加上这个标志

 

更多特性

利用Notification的属性和标志位,可以给通知添加更多的特性。

下面列出了其中一些常用的特性:

“FLAG_AUTO_CANCEL”标志

flags属性中增加此标志,则在通知窗口点选后能自动取消通知。

“FLAG_INSISTENT”标志

flags属性中增加此标志,则在用户响应前一直循环播放声音。

“FLAG_ONGOING_EVENT”标志

flags属性中增加此标志,则将通知放入通知窗口的正在运行Ongoing)组中。表示应用程序正在运行——进程仍在后台运行,即使应用程序不可见(比如播放音乐或接听电话)。

“FLAG_NO_CLEAR”标志

flags属性中增加此标志,表示通知不允许被清除通知按钮清除。这在期望通知保持运行时特别有用。

本文转载自上海Android培训教程,转载请注明。

 

 

 

0 0