(八)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 ...
随机推荐
- django学习笔记一
django作为一个python的开源项目发布,其web框架采用了mtv设计模式 在目前一些较为成熟的大型网站中有不少网站的应用基于django开发,django作为一个重量型的web框架提供了以下的 ...
- UITableView 隐藏多余的分割线
//隐藏多余的分割线 - (void)setExtraCellLineHidden: (UITableView *)tableView { UIView *view =[ [UIView alloc] ...
- Binary Tree Level Order Traversal,Binary Tree Level Order Traversal II
Binary Tree Level Order Traversal Total Accepted: 79463 Total Submissions: 259292 Difficulty: Easy G ...
- L - 辗转相除法(第二季水)
Description The least common multiple (LCM) of a set of positive integers is the smallest positive i ...
- wamp出现问题#1045 - Access denied for user 'root'@'localhost' (using password: NO)的解决方法
打开wamp->apps->phpmyadmin目录下面的config.inc.php文件 cfg['Servers'][$i]['verbose'] = 'localhost';$cfg ...
- 判断浏览器IE6
<!--[if lte IE 6]><LINK rel="stylesheet" type="text/css" href="ima ...
- listview滚动到底部
方法一: // msgListView是ListView控件 // adapter是ListView绑定的Adapter,如果不方便直接使用,也可以通过ListView的getAdapter()方法获 ...
- Win32 多线程的创建方法和基本使用
Win32多线程的创建方法主要有: (1)CreateThread() (2)_beginthread()&&_beginthreadex() (3)AfxBeginThread() ...
- C语言学习second--C语言基础学习
1.标准C语言 C语言诞生于20世纪70年代,年龄比我们自己还要大,期间产生了很多标准,但是各种编译器对标准的支持不尽相同. ANSI C是使用的最广泛的一个标准,也是第一个正式标准,被称为“标准C语 ...
- iOS项目生成通用Windows应用
WinObjc - 使用iOS项目生成通用Windows应用 Github上一周年的WinObjc项目最近发布了预览版本,终于等到了这一天.WinObjc项目就是Build 2015大会上微软宣布 ...