之前讲过了activity,服务service和内容提供者,四大组件就还差广播没讲,所以就顺便讲讲吧。当然,这里都是很基础的讲解,没有深入,要是深入的话光一个activity就可以讲很久。所以这里只做基础使用的讲解了。
时间紧迫,直接上代码吧。
首先,广播有两种注册方式,一种在清单文件中注册,注册后程序一运行广播就开始监听。一种在代码中注册,根据需求注册注销广播。
我们先看广播的第一种注册方式,首先定义一个广播接受者
package com.batways.apopo.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* @ClassName: TestReciver
* @author victor_freedom (x_freedom_reddevil@126.com)
* @createddate 2015年2月28日 下午9:31:23
* @Description: TODO
*
*/
public class TestReciver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
}
}
然后再清单文件中注册
<receiver android:name="com.batways.apopo.receiver.TestReciver" >
<intent-filter>
<action android:name="aaa.bbb.ccc" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
这样,当程序启动的时候,广播就开始监听动作为“aaa.bbb.ccc”的意图。
接下来再看在代码中注册广播
首先在代码中new一个广播接受者
private class UpdateCreditsBroadCast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
}
}
然后用代码注册:category可以填可以不填
mUpdateCreditsBroadCast = new UpdateCreditsBroadCast();
IntentFilter filter = new IntentFilter("com.batways.apopo_core.service");
//filter.addCategory(Intent.ACTION_DEFAULT);
registerReceiver(mUpdateCreditsBroadCast, filter);
一般而言,在该注册文件的生命周期函数中的起始函数注册广播,在结束函数中注销广播:
unregisterReceiver(mUpdateCreditsBroadCast);
mUpdateCreditsBroadCast = null;
这样,就完成了再代码中广播的注册与注销。
那么,我们发送广播的时候,该怎么弄呢。这里博主提供一个广播工具类吧,一般的都能满足使用了。这里需要特别注意,如果广播注册的时候加了category,这里就需要加,如果没有,这里就不需要加了。
public class BroadcastHelper {
/**
* 发送String 类型的值的广播
* @param context
* @param action
* @param key
* @param value
*/
public static void sendBroadCast(Context context,String action,String key,String value) {
Intent intent = new Intent();
intent.setAction(action);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.putExtra(key, value);
context.sendBroadcast(intent);
}
public static void sendBroadCast(Context context,String action,String key,int value) {
Intent intent = new Intent();
intent.setAction(action);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.putExtra(key, value);
context.sendBroadcast(intent);
}
}