AndroidOSHTCXML

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. }
  29. }

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. }
  13. }

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. };
  43. }

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. }
  14. }

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. };
  28. }

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. }
  42. }

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. }
  16. }

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,点击取消闹钟就不会弹出了

转载于:https://blog.51cto.com/gswxr/718967

玩转Android---组件篇---Broadcast Receiver(广播接收器)相关推荐

  1. Broadcast Receiver广播接收器

    1.概述 广播接收器不仅能接受来自系统的内容,也可以接受来自其他app的内容.广播分为标准广播和有序广播. 2.标准广播 一种完全异步执行的广播,在广播发出之后几乎所有的广播接收器都在同一时刻接受到广 ...

  2. Android学习笔记 88. Broadcast receivers 广播接收器

    Android学习笔记 Android 开发者基础知识 (Java) -- Google Developers 培训团队 文章目录 Android学习笔记 Android 开发者基础知识 (Java) ...

  3. Xamarin Android组件篇教程RecylerView动画组件RecylerViewAnimators(1)

    Xamarin Android组件篇教程RecylerView动画组件RecylerViewAnimators(1) RecyclerView是比ListView和GridView更为强大的布局视图, ...

  4. Android应用程序注冊广播接收器(registerReceiver)的过程分析

    前面我们介绍了Android系统的广播机制,从本质来说,它是一种消息订阅/公布机制,因此,使用这样的消息驱动模型的第一步便是订阅消息:而对Android应用程序来说,订阅消息事实上就是注冊广播接收器, ...

  5. Android 基础知识3:四大组件之 Broadcast(广播)

    目录 一.Broadcast 的定义 Broadcast 是一种广泛运用的.在应用程序之间传输信息的机制,Android 中的广播与传统意义上的电台广播类似,一个广播可以有任意个接收者,当然也可能不被 ...

  6. BroadCast Receiver(广播)详解

    目录 静态广播 1.首先在这边创建广播接收器 2.在AndroidManifest.xml中写入静态接收名 3.在主方法把广播发送给静态广播接收者 4.在广播接收器里面接收广播 动态广播: 1.创建广 ...

  7. [2021.07.12]Android系统广播机制(Broadcast Receiver)

    广播(Broadcast)是一种在组件之间进行消息传递的方式.这些组件可以运行在同一个进程中,也可以在不同的进程中.事实上,广播机制就是在Binder进程间通信的基础上实现的.那么,有了Binder通 ...

  8. Android——Broadcast Receivers广播接收器

    BroadCastReceiver简介 BroadCastReceiver源码位于:framework/base/core/java/android.content.BroadcastReceiver ...

  9. Android组件之BroadCast简单实践

    作为Android的四大组件之一,没有理由不介绍一下BroadCast,BroadCast中文简单翻译就是广播,前阵子浙江某大学的啦啦操,广场舞的大妈,其中大妈和学生从喇叭和音响上听到的声音就是事件源 ...

  10. Broadcast Receiver广播

    广播一般情况下用来监听手机内部的状态的,也可有消息推送 广播有两种注册方式: 静态注册(常驻型广播): 特点:当App运行的时候,广播就应经存在了,即使是退出应用,广播依然存在. 通过清单文件的方式注 ...

最新文章

  1. Linux常用20条命令
  2. ROS Master IP
  3. 关于Remote Desktop Users组
  4. 博客园 创始人 杜勇
  5. Keepalived的VRRPD配置
  6. 中英翻译(基于百度翻译)
  7. pyqt 把控制台信息显示到_(基础篇 01)在控制台创建对应的应用
  8. NPOI读写Excel sheet操作
  9. 美颜重磅技术之GPUImage源码分析
  10. 51单片机驱动——DS18B20
  11. ArcFace 论文阅读及 pytorch 实现
  12. 硬盘数据恢复原理与方法(转)
  13. 今日开放式基金净值表
  14. 抱团股会一直涨?无脑执行大小盘轮动策略,轻松跑赢指数5倍【附Python代码】
  15. 基于AT89C51单片机的抢答器的设计(数码管:四位一体共阳)
  16. React Native 警告 Animated: `useNativeDriver` is not supported 的解决方案
  17. 分贝(dB)的计算与理解
  18. 防火墙导致mysql登录不上_防火墙导致MySQL无法访问的问题解决案例
  19. Unity 运行状态下动态保存 预制体/预制体上脚本参数
  20. install ubuntu source code

热门文章

  1. overcommit_memory 内核参数
  2. Linux设备驱动程序 之 中断和锁
  3. Python学习中的知识点小记录(廖雪峰)
  4. 2016 CSU - 1803
  5. Spark项目 error while loading <root>, error in opening zip file
  6. 插入排序 java实现
  7. MongoDB最佳实践
  8. 计算机指针知识,指针_计算机基础知识142页.ppt
  9. pycharm python脚本如何调试_Pycharm调试程序技巧小结
  10. hdu1243----最长公共子序列