(八)Android广播接收器BroadcastReceiver
一、使用Broadcast Reciver
1.右击java文件夹,new->other->Broadcast Receiver后会在AndroidManifest.xml文件中生成一个receiver项
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.shiyanshi.learnbroadcast" > <application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true" >
</receiver>
</application> </manifest>
2.同时生成了一个MyReceiver 的类,该类中onReceive用于响应sendBroadcast函数发送的消息
package com.example.shiyanshi.learnbroadcast; import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent; public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
} @Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
// throw new UnsupportedOperationException("Not yet implemented");
System.out.println("Recv Data:"+intent.getStringExtra("data"));
}
}
3.调用sendBroadcast函数进行发送消息,该函数需要一个Intent
package com.example.shiyanshi.learnbroadcast; import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View; public class MainActivity extends Activity implements View.OnClickListener { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); findViewById(R.id.btnSendMsg).setOnClickListener(this);
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
} @Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId(); //noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
} return super.onOptionsItemSelected(item);
} @Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btnSendMsg:
Intent intent =new Intent(this,MyReceiver.class);
intent.putExtra("data","henry");
sendBroadcast(intent);
break;
}
}
}
二、动态注册和注销
1.删去AndroidManifest.xml文件中的receiver时,需要动态注册和注销,才能发送和接收消息
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true" >
</receiver>
2.MainActivity更改如下:发送消息消息时,Intent要使用隐式Intent(MyReceiver.ACTION为定义的一个常量字符串
public static final String ACTION="com.example.shiyanshi.learnbroadcast.intent.action.MyReceiver";//前半部分时包名,后半部分时intent的格式,MyReceiver是上述中用于
响应sendBroadcast的类),注册时使用registerReceiver函数,注销时使用unregisterReceiver函数
函数原型为:
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter)
public void unregisterReceiver(BroadcastReceiver receiver)
receiver是我们新建Broadcast时声称的用于响应sendBroadcast的MyReceiver类,filter是过滤器,需想起传递隐式Intent类似的参数。
public class MainActivity extends Activity implements View.OnClickListener {
private MyReceiver receiver=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); findViewById(R.id.btnSendMsg).setOnClickListener(this);
findViewById(R.id.btnRegister).setOnClickListener(this);
findViewById(R.id.btnUnregister).setOnClickListener(this);
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
} @Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId(); //noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
} return super.onOptionsItemSelected(item);
} @Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btnSendMsg:
// Intent intent =new Intent(this,MyReceiver.class);
//动态注册和注销时要使用隐式Intent,而不能使用显示Intent了
Intent intent=new Intent(MyReceiver.ACTION);
intent.putExtra("data","henry");
sendBroadcast(intent);
break;
case R.id.btnRegister:
if (receiver==null){
receiver=new MyReceiver();
registerReceiver(receiver,new IntentFilter(MyReceiver.ACTION));
}
break;
case R.id.btnUnregister:
if(receiver!=null){
unregisterReceiver(receiver);
receiver=null;
}
break;
}
}
}
三、Broadcast的优先级
当发送数据时,采用隐式Intent的形式(如上),两个receiver中的action name相同时,二者可以同时接收到数据。
默认情况下最后写的那个receiver所对应的优先级高,此外可以显示的在receiver下的Intent-filter中指明优先级priority,其数值越大,优先级越高,越先响应数据
<receiver
android:name=".MyReceiver1"
android:enabled="true"
android:exported="true" >
<intent-filter android:priority="2">
<action android:name="com.example.shiyanshi.learnbroadcast.intent.action.MyReceiver"/>
</intent-filter>
</receiver>
<receiver android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1">
<action android:name="com.example.shiyanshi.learnbroadcast.intent.action.MyReceiver"/>
</intent-filter>
</receiver>
</application>
此外,当优先级高的那个onReceive执行后,可以在其中调用abortBroadcast来终止数据的传递,优先级别低的onReceive便不会执行了.
注意:若想使用abortBroadcast函数,发送时需使用sendOrderedBroadcast而非sendBroadcast,否则会弹出错误java.lang.RuntimeException: BroadcastReceiver trying to return result during a non-ordered broadcast。
Intent intent=new Intent(MyReceiver.ACTION);
intent.putExtra("data","henry");
// sendBroadcast(intent);
sendOrderedBroadcast(intent,null);
其中sendOrderedBroadcast的第二个参数用来指明权限,可以为空
(八)Android广播接收器BroadcastReceiver的更多相关文章
- android广播接收器BroadcastReceiver
首先看一下什么是 BroadcastReceiver BroadcastReceiver:直译是"广播接收者",所以它的作用是用来接收发送过来的广播的. 那我们有必要知道:什么是广 ...
- android广播接收器
Android程序创建广播接收器继承BroadcastReceiver Android广播接收器需要在AndroidManifest.xml文件中声明: <recevie android:nam ...
- android在广播接收器BroadcastReceiver里面再进行发送广播,造成当前广播接收器不断循环执行问题
最近在公司处理项目时,用到锁屏状态弹出activity进行提示,类似QQ消息弹屏提示的功能.当中用到了,假如该弹出activity已经位于锁屏界面外时,将不进行再次弹窗,而是发送广播进行通知数据更新, ...
- Xamarin.Android广播接收器与绑定服务
一.前言 学习了前面的活动与服务后,你会发现服务对于活动而言似乎就是透明的,相反活动对于服务也是透明的,所以我们还需要一中机制能够将服务和活动之间架起一座桥梁,通过本节的学习,你将会学到广播与绑定服务 ...
- Android - 广播接收者 - BroadcastReceiver
BroadcastReceiver 介绍: 广播是一种广泛运用的在应用程序之间传输信息的机制 .而 BroadcastReceiver 是对发送出来的广播 进行过滤接收并响应的一类组件 接受一种或者多 ...
- Android广播接收器Broadcast Receiver-android学习之旅(十二)
首先继承BroadcastReceiver类,并在manifest中注册 public class MyReceiver extends BroadcastReceiver { public MyRe ...
- Android广播接收器和Activity间传递数据
Activity向广播接收器传递数据很简单,只需要在发送广播前将数据put进Intent中就行了. 广播接收器怎么向Activity传送数据?这里要用到接口,通过在广播接收器里定义一个接口,然后让接收 ...
- Android广播接收器里弹出对话框
不多说,直接上车... public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(fina ...
- Android学习之基础知识八—Android广播机制
一.广播机制简介 Android提供了一套完整的API,允许应用程序自由的发送和接受广播,发送广播借助于我们之前学过的:Intent,而接收广播需要借助于广播接收器(Broadcast Receive ...
随机推荐
- 基于Vue 和 webpack的项目实现
Vue.js 是一款极简的 mvvm 框架,如果让我用一个词来形容它,就是 “轻·巧” .如果用一句话来描述它,它能够集众多优秀逐流的前端框架之大成,但同时保持简单易用.废话不多说,来看几个例子: & ...
- QUdpSocket Class
翻译自:QT官网文档QUdpSocket类 QUdpSocket类提供一个UDP套接字. Header: #include <QUdpSocket> qmake: QT += networ ...
- mysql源码安装(5.1)
下载mysql源码包并解压.wget http://dev.mysql.com/get/Downloads/MySQL-5.1/mysql-5.1.73.tar.gztar -zxvf mysql-5 ...
- mysql跟踪提交的SQL语句
http://www.cnblogs.com/wuyifu/p/3328024.html
- git使用经验
一直想写一点关于git的文章,但是平时太懒了,没有写,现在写些经验这里,方便以后自己忘记了.
- NPOI新建和读取EXCEL
//基本NPOI 1.2.5.0 static void Main(string[] args) { string path = string.Format("E:\\export{0}.x ...
- CSS学习笔记——盒模型,块级元素和行内元素的区别和特性
今天本来打算根据自己的计划进行前端自动化的学习的,无奈早上接到一个任务需求需要新增一个页面.自从因为工作需要转前端之后,自己的主要注意力几 乎都放在JavaScript上面了,对CSS和HTML这方面 ...
- 【转】SSIS 2012 – Package Configurations Menu Option Missing
原文:http://dataqueen.unlimitedviz.com/2012/01/ssis-2012-package-configurations-menu-option-missing/ I ...
- 命名空间 - PHP手册笔记
概述 命名空间是一种封装事物的方法.在很多地方都可以见到这种抽象概念,比如在操作系统中,目录用来将相关文件分组,对于目录中的文件来说,目录就扮演了命名空间的角色.这个原理应用到程序设计领域就是命名空间 ...
- IBM Minus One(water)
IBM Minus One Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Tot ...