`

Broadcast Receiver(广播接收器)

 
阅读更多

Braodcast Receiver顾名思义就是广播接收器,它和时间处理机制类似,但是事件处理机制是程序组件级别的(比如:按钮的单击事件),而广播事件处理机制是系统级别的。我们可以用Intent来启动一个组件,也可以用sendBroadcast()方法发起一个系统级别的事件广播来传递消息。我们同样可以在自己的应用程序中实现Broadcast Receiver来监听和响应广播的Intent。

事件的广播通过创建Intent对象并调用sendBroadcast()方法将广播发出。事件的接受是通过定义一个继承BroadcastReceiver的类来实现的,继承该类后覆盖其onReceive()方法,在该方法中响应时间。

下面是android系统中定义了很多标准的Broadcast Action来响应系统的广播事件。

①ACTION_TIME_CHANGED(时间改变时触发)

②ACTION_BOOT_COMPLETED(系统启动完成后触发)--比如有些程序开机后启动就是用这种方式来实现的

③ACTION_PACKAGE_ADDED(添加包时触发)

④ACTION_BATTERY_CHANGED(电量低时触发)

详细:标准广播ACTION常量

 

常量名称

常量值

意义

ACTION_BOOT_COMPLETED

android.intent.action.BOOT_COMPLETED

系统启动完成

ACTION_TIME_CHANGED

android.intent.action.ACTION_TIME_CHANGED

时间改变

ACITON_DATE_CHANGED

android.intent.action.ACTION_DATE_CHANGED

日期改变

ACTION_TIMEZONE_CHANGED

android.intent.action.ACTION_TIMEZONE_CHANGED

时区该表

ACTION_BATTERY_LOW

android.intent.action.ACTION_BATTERY_LOW

电量低

ACTION_MEDIA_EJECT

android.intent.action.ACTION_MEDIA_EJECT

插入或拔出外部媒体

ACTION_MEDIA_BUTTON

android.intent.action.ACTION_MEDIA_BUTTON

按下媒体按钮

ACTION_PACKAGE_ADDED

android.intent.action.ACTION_PACKAGE_ADDED

添加包

ACTION_PACKAGE_REMOVED

android.intent.action.ACTION_PACKAGE_REMOVED

删除包

 

在这里,要练习3个内容

①自定义Broadcast Receiver

②Notification和NotificationManager的使用

③AlarmManager的使用

 

1、首先看一个自定义的广播事件的例子

Java代码  收藏代码
  1. package org.hualang.broadcast;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.Intent;  
  5. import android.os.Bundle;  
  6. import android.view.View;  
  7. import android.view.View.OnClickListener;  
  8. import android.widget.Button;  
  9.   
  10. public class BroadCastTest extends Activity {  
  11.     /** Called when the activity is first created. */  
  12.     private static final String MY_ACTION="org.hualang.broadcast.action.MY_ACTION";  
  13.     private Button btn;  
  14.     @Override  
  15.     public void onCreate(Bundle savedInstanceState) {  
  16.         super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.main);  
  18.         btn=(Button)findViewById(R.id.button);  
  19.         btn.setOnClickListener(new OnClickListener()  
  20.         {  
  21.   
  22.             @Override  
  23.             public void onClick(View arg0) {  
  24.                 // TODO Auto-generated method stub  
  25.                 Intent intent=new Intent();  
  26.                 intent.setAction(MY_ACTION);  
  27.                 intent.putExtra("msg""同志们好!同志们辛苦啦!");  
  28.                 sendBroadcast(intent);  
  29.             }  
  30.               
  31.         });  
  32.     }  
  33. }  

 

MyReceiver.java

Java代码  收藏代码
  1. package org.hualang.broadcast;  
  2.   
  3. import android.content.BroadcastReceiver;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.widget.Toast;  
  7.   
  8. public class MyReceiver extends BroadcastReceiver {  
  9.   
  10.     @Override  
  11.     public void onReceive(Context arg0, Intent arg1) {  
  12.         // TODO Auto-generated method stub  
  13.         String msg=arg1.getStringExtra("msg");  
  14.         Toast.makeText(arg0, msg, Toast.LENGTH_LONG).show();  
  15.     }  
  16.       
  17. }  

 

注意:在AndroidManifest.xml文件中注册

Java代码  收藏代码
  1. <receiver android:name="MyReceiver">  
  2.             <intent-filter>  
  3.                 <action android:name="org.hualang.broadcast.action.MY_ACTION"/>  
  4.             </intent-filter>  
  5.         </receiver>  

 

 

我们还可以在AndroidManifest.xml文件中注销一个广播接收器,一般在Activity.onResume()方法中使用Context.registerReceiver()方法来注册一个广播接收器,在Activity.onPause()中使用unregisterReceiver(r)方法注销一个广播接收器,例如:

//实例化intent过滤器

IntentFilter filter = new IntentFilte();

//实例化Receiver

MyReceiver r = new Receiver();

//注册Receiver

registerReceiver(r,filter);

 

为了注销一个BroadcastReceiver,应使用Context.unregisterReceiver方法,传入一个BroadcastReceiver实例

//注销

unregisterReceiver(r);

 

2、下面的是Notification的例子,比如手机来短信的时候,会在屏幕最上边有一个通知,那个就是Notification

DisplayActivity.java

Java代码  收藏代码
  1. package org.hualang.notify;  
  2.   
  3. import android.app.Activity;  
  4. import android.app.Notification;  
  5. import android.app.NotificationManager;  
  6. import android.app.PendingIntent;  
  7. import android.content.Intent;  
  8. import android.os.Bundle;  
  9. import android.view.View;  
  10. import android.view.View.OnClickListener;  
  11. import android.widget.Button;  
  12.   
  13. public class DisplayActivity extends Activity {  
  14.     private Button cancelbtn;  
  15.     private Notification n;  
  16.     private NotificationManager nm;  
  17.     private static final int ID=1;  
  18.     public void onCreate(Bundle savedInstanceState)  
  19.     {  
  20.         super.onCreate(savedInstanceState);  
  21.         setContentView(R.layout.main2);  
  22.         cancelbtn = (Button)findViewById(R.id.button2);  
  23.         String service = NOTIFICATION_SERVICE;  
  24.         nm = (NotificationManager)getSystemService(service);  
  25.           
  26.         n = new Notification();  
  27.         int icon = n.icon =R.drawable.icon;  
  28.         String tickerText = "喜欢HTC的样子,喜欢defy的配置";  
  29.         long when = System.currentTimeMillis();  
  30.         n.icon = icon;  
  31.         n.tickerText = tickerText;  
  32.         n.when = when;  
  33.           
  34.         Intent intent = new Intent(this,NotifyTest2.class);  
  35.         PendingIntent pi = PendingIntent.getActivity(this0 , intent , 0);  
  36.         n.setLatestEventInfo(this"My Title""My Content", pi);  
  37.         nm.notify(ID, n);  
  38.         cancelbtn.setOnClickListener(cancelListener);  
  39.     }  
  40.     private OnClickListener cancelListener=new OnClickListener()  
  41.     {  
  42.         public void onClick(View v)  
  43.         {  
  44.             nm.cancel(ID);  
  45.         }  
  46.     };  
  47. }  

 MyReceiver.java

Java代码  收藏代码
  1. package org.hualang.notify;  
  2.   
  3. import android.content.BroadcastReceiver;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6.   
  7. public class MyReceiver extends BroadcastReceiver {  
  8.   
  9.     @Override  
  10.     public void onReceive(Context context, Intent intent) {  
  11.         // TODO Auto-generated method stub  
  12.         Intent i=new Intent();  
  13.         i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  14.         i.setClass(context,DisplayActivity.class);  
  15.         context.startActivity(i);  
  16.     }  
  17.       
  18. }  

 

NotifyTest2.java

Java代码  收藏代码
  1. package org.hualang.notify;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.Intent;  
  5. import android.os.Bundle;  
  6. import android.view.View;  
  7. import android.view.View.OnClickListener;  
  8. import android.widget.Button;  
  9.   
  10. public class NotifyTest2 extends Activity {  
  11.     /** Called when the activity is first created. */  
  12.     private Button btn;  
  13.     private static final String MY_ACTION="org.hualang.notify.aciton.MY_ACITON";  
  14.     @Override  
  15.     public void onCreate(Bundle savedInstanceState) {  
  16.         super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.main);  
  18.         btn=(Button)findViewById(R.id.button);  
  19.         btn.setOnClickListener(listener);  
  20.     }  
  21.     private OnClickListener listener=new OnClickListener()  
  22.     {  
  23.         public void onClick(View v)  
  24.         {  
  25.             Intent intent=new Intent();  
  26.             intent.setAction(MY_ACTION);  
  27.             sendBroadcast(intent);  
  28.         }  
  29.     };  
  30. }  

 

注册AndroidManifest.xml

Java代码  收藏代码
  1. <receiver android:name="MyReceiver">  
  2.             <intent-filter>  
  3.                 <action android:name="org.hualang.notify.aciton.MY_ACITON"/>  
  4.             </intent-filter>  
  5.         </receiver>  
  6.         <activity android:name="DisplayActivity">  
  7.         </activity>  

 

运行结果如下:




 

3、下面是AlarmManager的例子,它是一个闹钟,感兴趣的朋友可以自己写一个小闹钟

AlarmManager常用的属性和方法

 

属性或方法名称

说明

ELAPSED_REALTIME

设置闹钟时间,从系统启动开始

ELAPSED_REALTIME_WAKEUP

设置闹钟时间,从系统启动开始,如火设备休眠则唤醒

INTERVAL_DAY

设置闹钟时间,间隔一天

INTERVAL_FIFTEEN_MINUTES

间隔15分钟

INTERVAL_HALF_DAY

间隔半天

INTERVAL_HALF_HOUR

间隔半小时

INTERVAL_HOUR

间隔1小时

RTC

设置闹钟时间,从系统当前时间开始(System.currentTimeMillis())

RTC_WAKEUP

设置闹钟时间,从系统当前时间开始,设备休眠则唤醒

set(int type,long tiggerAtTime,PendingIntent operation)

设置在某个时间执行闹钟

setRepeating(int type,long triggerAtTiem,long interval,PendingIntent operation)

设置在某个时间重复执行闹钟

setInexactRepeating(int type,long triggerAtTiem,long interval,PendingIntent operation)

是指在某个时间重复执行闹钟,但不是间隔固定时间

 

AlarmTest.java

Java代码  收藏代码
  1. package org.hualang.alarm;  
  2.   
  3. import android.app.Activity;  
  4. import android.app.AlarmManager;  
  5. import android.app.PendingIntent;  
  6. import android.content.Intent;  
  7. import android.os.Bundle;  
  8. import android.util.Log;  
  9. import android.view.View;  
  10. import android.view.View.OnClickListener;  
  11. import android.widget.Button;  
  12.   
  13. public class AlarmTest extends Activity {  
  14.     /** Called when the activity is first created. */  
  15.     private Button btn1,btn2;  
  16.     private static final String BC_ACTION="org.hualang.alarm.action.BC_ACTION";  
  17.     @Override  
  18.     public void onCreate(Bundle savedInstanceState) {  
  19.         super.onCreate(savedInstanceState);  
  20.         setContentView(R.layout.main);  
  21.         btn1 = (Button)findViewById(R.id.button1);  
  22.         btn2 = (Button)findViewById(R.id.button2);  
  23.           
  24.         final AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);  
  25.         Intent intent = new Intent();  
  26.         intent.setAction(BC_ACTION);  
  27.         intent.putExtra("msg""你该起床了");  
  28.         final PendingIntent pi = PendingIntent.getBroadcast(AlarmTest.this0, intent, 0);  
  29.         final long time = System.currentTimeMillis();  
  30.   
  31.           
  32.         btn1.setOnClickListener(new OnClickListener()  
  33.         {  
  34.             public void onClick(View v)  
  35.             {  
  36.                   
  37.                 am.setRepeating(AlarmManager.RTC_WAKEUP, time, 5*1000, pi);  
  38.             }  
  39.         });  
  40.         btn2.setOnClickListener(new OnClickListener()  
  41.         {  
  42.             public void onClick(View v)  
  43.             {  
  44.                 am.cancel(pi);  
  45.             }  
  46.         });  
  47.     }  
  48. }  

 

MyReceiver.java

Java代码  收藏代码
  1. package org.hualang.alarm;  
  2.   
  3. import android.content.BroadcastReceiver;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.util.Log;  
  7. import android.widget.Toast;  
  8.   
  9. public class MyReceiver extends BroadcastReceiver {  
  10.   
  11.     @Override  
  12.     public void onReceive(Context context, Intent intent) {  
  13.         // TODO Auto-generated method stub  
  14.         String msg=intent.getStringExtra("msg");  
  15.         Log.v("SERVICE","QIAN----------------------");  
  16.         Toast.makeText(context, msg, Toast.LENGTH_LONG).show();  
  17.         Log.v("SERVICE""HOU-----------------------");  
  18.     }  
  19.   
  20. }  

 

注册AndroidManifest.xml

Java代码  收藏代码
  1. <receiver android:name="MyReceiver">  
  2.             <intent-filter>  
  3.                 <action android:name="org.hualang.alarm.action.BC_ACTION"/>  
  4.             </intent-filter>  
  5.         </receiver>  

 运行结果:


 

 点击设置闹钟后,会每隔5秒弹出一个Toast,点击取消闹钟就不会弹出了


来自:http://hualang.iteye.com/blog/1003374

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics