第二部分基本组件---2.4BroadCastReceiver用法

BroadCastReceiver比较重要在系统框架中经常用到,主要有几个步骤

1. Sendbroadcast发送广播

发送广播时需要携带一个intent对象做为参数,intent生成时需要制定在系统中注册所用的唯一字符串,当然intent可以带一些需要传递的额外参数

public static final String  BOARDACTION_1 ="com.derek.xie.action1";

Intent intent = new Intent(BOARDACTION_1);

      intent.putExtra("name", "derek.xie");

      this.sendBroadcast(intent);

1.       系统中注册广播接收者,类似于界面布局可以用静态注册和动态注册两种方式

2.1)静态注册,即在xml文件中加上标签如

<receiver android:name ="NotificationTest">

      <intent-filter>

      <action android:name = "com.derek.xie.action1"></action>

      </intent-filter>

</receiver>

标签中指定receiver和此receiver可以接收的广播标识

2.2动态注册,即在java代码中动态定义注册

IntentFilter ift = new IntentFilter();

      ift.addAction(BOARDACTION_1);

 this.getApplicationContext().registerReceiver(new  NotificationTestActivity(), ift);

一定别忘了取消注册(一般在OnCreate中注册,onStop中对应取消注册)

this.getApplicationContext().unregisterReceiver()

2.  实现接收者类,接收者类需要继承BroadCastReceiver类,复写其OnReceive方法,即在收到广播时的一系列反馈动作

例子,  接到broadcast后触发了一个notification:

public void onReceive(Context context, Intent intent) {

      this.context = context;

      Bundle b=intent.getExtras();

      notiStr =(String)b.get("name");

      showNotification();

           

      }

 

      private void showNotification() {

            // TODO Auto-generated method stub

      NotificationManager nm= (NotificationManager)this.context.getSystemService(android.content.Context.NOTIFICATION_SERVICE);

      Notification n= new Notification(R.drawable.icon,notiStr,System.currentTimeMillis());

      PendingIntent pi = PendingIntent.getActivity(context, 0, new Intent(context,TabDemoActivity.class), 0);

      n.setLatestEventInfo(context, "new Broadcast", "newnew", pi);

      nm.notify(0, n);

     

      }

你可能感兴趣的:(java,android,框架,String,service,action)