BroadcastReceiver(广播接收器 )
一、广播机制介绍:
Broadcast Receiver 分为标准广播和有序广播。
标准广播是一种完全异步执行的广播,当广播发出后,所有的广播接受器都同时收到此广播。
有序广播是一种同步执行的广播,同一时刻只会有一个广播接收器能接收到此广播,当前广播接受器执行完内部逻辑后,才会下发下去。有序广播是根据优先级来设置优先收到广播的广播接收器。
注册广播分为两种:
1、在代码中注册(动态广播)
动态广播好处就是非常灵活,缺点就是必须程序启动后才能接受广播,所以一些不启动程序就能接受广播的业务就需要静态广播来实现。
2、在AndroidManifest.xml中进行注册(静态广播)
二、接受系统广播
动态广播
package com.example.broadcastreceiveractivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
public IntentFilter intent;
public NetWorkBroadcastReceiver network;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new IntentFilter();
intent.addAction("android.net.conn.CONNECTIVITY_CHANGE");
network = new NetWorkBroadcastReceiver();
// 注册广播接收器
registerReceiver(network, intent);
}
public void onDestroy() {
super.onDestroy();
unregisterReceiver(network);
}
// 广播接收者
class NetWorkBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
// Toast.makeText(getApplicationContext(), "网络发生变化了~亲", 1).show();
ConnectivityManager conn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = conn.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable()) {
Toast.makeText(getApplicationContext(), "已连接网络", 1).show();
} else {
Toast.makeText(getApplicationContext(),
"无法连接网络", 1).show();
}
}
}
}
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
静态广播
package com.example.broadcastreceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class StaticBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Toast.makeText(arg0, "开机启动后自动调用这个静态广播", 1).show();
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcastreceiveractivity"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="@drawable/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="com.example.broadcastreceiver.StaticBroadcast">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
</manifest>
三、发送自定义广播.
3.1 发送标准广播
package com.example.broadcastreceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Toast.makeText(arg0, "收到了标准广播,广播内容为:" + arg1.getStringExtra("msg"), 1).show();
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sendbroadcastreceiver"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="@drawable/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="com.example.broadcastreceiver.MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.broadcastreceiver.MY_BROADCASTRECEIVER"/>
</intent-filter>
</receiver>
</application>
</manifest>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.sendbroadcastreceiver.MainActivity" >
<Button
android:id="@+id/sendBR"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送一个普通广播" >
</Button>
</RelativeLayout>
package com.example.sendbroadcastreceiver;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.sendBR);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(
"com.example.broadcastreceiver.MY_BROADCASTRECEIVER");
// 传递一些数据
intent.putExtra("msg", "快交房租啦!!");
// 发送一个标准 广播
sendBroadcast(intent);
}
});
}
}
运行效果为:
3.2 发送有序广播
Intent intent = new Intent("com.example.broadcastreceiver.MY_BROADCASTRECEIVER");
// 传递一些数据
intent.putExtra("msg", "发送有序广播!!!");
// 发送一个有序广播
sendOrderedBroadcast(intent, null);
有序广播是根据android:priority来设置广播接收器的优先级。
<receiver android:name="com.example.broadcastreceiver.MyBroadcastReceiver">
<intent-filter android:priority="1000">
<action android:name="com.example.broadcastreceiver.MY_BROADCASTRECEIVER"/>
</intent-filter>
</receiver>
如果截断广播,终止广播传递,则调用abroadcast();即可,e.g.
package com.example.broadcastreceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Toast.makeText(arg0, arg1.getStringExtra("msg"), 1).show();
//截断此广播,终止传递
abortBroadcast();
}
}
3.3 发送本地广播
package com.example.sendbroadcastreceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private IntentFilter intentFilter;
private LocalReceiver localReceiver;
private LocalBroadcastManager localBroadcastManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonLocation = (Button) findViewById(R.id.sendLocationBR);
localBroadcastManager = LocalBroadcastManager.getInstance(this);
intentFilter = new IntentFilter();
intentFilter.addAction("com.example.broadcastreceiver.MY_LOCAL_BROADCASTRECEIVER");
localReceiver = new LocalReceiver();
localBroadcastManager.registerReceiver(localReceiver, intentFilter);
buttonLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(
"com.example.broadcastreceiver.MY_LOCAL_BROADCASTRECEIVER");
// 传递一些数据
intent.putExtra("msg", "发送本地广播!!!");
localBroadcastManager.sendBroadcast(intent);
}
});
}
public void onDestroy() {
super.onDestroy();
localBroadcastManager.unregisterReceiver(localReceiver);
}
class LocalReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), arg1.getStringExtra("msg"),
Toast.LENGTH_LONG).show();
}
}
}
针对广播接受者写了一个demo,下载地址如下
链接: http://pan.baidu.com/s/1qWLoIoG 密码: h80m