Android Broadcast(广播)使用
package com.broad;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* 广播的使用
* @author XP
*
*/
public class BroadCastUse extends Activity {
/** Called when the activity is first created. */
private Button button;
//定义广播动作
private static final String BROADCASE_ID = "broadcase";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button)findViewById(R.id.buttonBC);
button.setOnClickListener(btnClick);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//注册广播
regeditBroad();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//销毁广播
destoryBroad();
}
private OnClickListener btnClick = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(BROADCASE_ID);
//发送广播
sendBroadcast(intent);
}
};
/**
* 注册广播
*/
private void regeditBroad(){
IntentFilter filter = new IntentFilter();
//过滤定义广播动作
filter.addAction(BROADCASE_ID);
registerReceiver(broadcast, filter);
}
/**
* 销毁广播
*/
private void destoryBroad(){
if(broadcast != null){
unregisterReceiver(broadcast);
}
}
private BroadcastReceiver broadcast = new BroadcastReceiver() {
//接收广播,实现逻辑判断
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(intent.getAction() == BROADCASE_ID){
Log.i("console", "onReceive");
}
}
};
}
广播发送有三种形式,即,sendBroadcast(),sendOrderedBroadcast(),sendStickyBroadcast()
sendBroadcast():普通广播 (Normal broadcasts)
发送一个广播,所以监听该广播的广播接收者都可以监听到该广播。
sendOrderedBroadcast():有序广播 (Ordered broadcasts)
按照接收者的优先级顺序接收广播 , 优先级别在 intent-filter 中的 priority 中声明 ,-1000 到1000 之间 , 值越大 , 优先级越高 . 可以终止广播意图的继续传播 . 接收者可以篡改内容 .
sendStickyBroadcast():异步广播
当处理完之后的Intent ,依然存在,这时候registerReceiver(BroadcastReceiver, IntentFilter) 还能收到他的值,直到你把它去掉 , 不能将处理结果传给下一个接收者 , 无法终止广播 .