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

MyReceiver.java

Java代码

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

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

MyReceiver.java

Java代码

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

NotifyTest2.java

Java代码

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

注册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> 
<receiver android:name="MyReceiver"> <intent-filter> <action android:name="org.hualang.notify.aciton.MY_ACITON"/> </intent-filter> </receiver> <activity android:name="DisplayActivity"> </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. import android.app.Activity;  
  3. import android.app.AlarmManager;  
  4. import android.app.PendingIntent;  
  5. import android.content.Intent;  
  6. import android.os.Bundle;  
  7. import android.util.Log;  
  8. import android.view.View;  
  9. import android.view.View.OnClickListener;  
  10. import android.widget.Button;  
  11. public class AlarmTest extends Activity {  
  12. /** Called when the activity is first created. */
  13. private Button btn1,btn2;  
  14. private static final String BC_ACTION="org.hualang.alarm.action.BC_ACTION";  
  15. @Override
  16. public void onCreate(Bundle savedInstanceState) {  
  17. super.onCreate(savedInstanceState);  
  18.         setContentView(R.layout.main);  
  19.         btn1 = (Button)findViewById(R.id.button1);  
  20.         btn2 = (Button)findViewById(R.id.button2);  
  21. final AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);  
  22.         Intent intent = new Intent();  
  23.         intent.setAction(BC_ACTION);  
  24.         intent.putExtra("msg", "你该起床了");  
  25. final PendingIntent pi = PendingIntent.getBroadcast(AlarmTest.this, 0, intent, 0);  
  26. final long time = System.currentTimeMillis();  
  27.         btn1.setOnClickListener(new OnClickListener()  
  28.         {  
  29. public void onClick(View v)  
  30.             {  
  31.                 am.setRepeating(AlarmManager.RTC_WAKEUP, time, 5*1000, pi);  
  32.             }  
  33.         });  
  34.         btn2.setOnClickListener(new OnClickListener()  
  35.         {  
  36. public void onClick(View v)  
  37.             {  
  38.                 am.cancel(pi);  
  39.             }  
  40.         });  
  41.     }  
package org.hualang.alarm; import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class AlarmTest extends Activity { /** Called when the activity is first created. */ private Button btn1,btn2; private static final String BC_ACTION="org.hualang.alarm.action.BC_ACTION"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btn1 = (Button)findViewById(R.id.button1); btn2 = (Button)findViewById(R.id.button2); final AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE); Intent intent = new Intent(); intent.setAction(BC_ACTION); intent.putExtra("msg", "你该起床了"); final PendingIntent pi = PendingIntent.getBroadcast(AlarmTest.this, 0, intent, 0); final long time = System.currentTimeMillis(); btn1.setOnClickListener(new OnClickListener() { public void onClick(View v) { am.setRepeating(AlarmManager.RTC_WAKEUP, time, 5*1000, pi); } }); btn2.setOnClickListener(new OnClickListener() { public void onClick(View v) { am.cancel(pi); } }); } }

MyReceiver.java

Java代码

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

注册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> 
<receiver android:name="MyReceiver"> <intent-filter> <action android:name="org.hualang.alarm.action.BC_ACTION"/> </intent-filter> </receiver>

运行结果:

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