android广播最简单使用,在需要接收广播的界面里使用如下方法:
/**
* 注册广播
*/
private void registerBroadcast() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Constant.BROADCAST_ACTION_DEPLOY_LINE);
myBroadcastReciver = new MyBroadcastReciver();
registerReceiver(myBroadcastReciver, intentFilter);
}
/**
* 自定义一个广播接收器
*
* @date 2013-10-28 下午7:59:56
* @version V1.0
*/
private class MyBroadcastReciver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
/**
* 跳到从设置界面跳发过来的广播,就将这个界面结束掉,让用户到主页上去
*/
if (action.equals(Constant.BROADCAST_ACTION_DEPLOY_LINE)) {
finish();
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// 在结束时可取消广播
if (myBroadcastReciver != null) {
unregisterReceiver(myBroadcastReciver);
}
}
在onCreate方法里注册一下广播即可:
/**
* 注册广播接
*/
registerBroadcast();
定义广播名:
/**
* 广播action名
*/
public final static String BROADCAST_ACTION_DEPLOY_LINE = "com.biao.deployline";
(2)在发送广播的地方,简单使用代码如下就可以发了:
/**
* 发送 一个无序广播
*/
Intent intent = new Intent();
intent.setAction(Constant.BROADCAST_ACTION_DEPLOY_LINE);
sendBroadcast(intent);
如我代码使用的:
private AsyncHttpResponseHandler depolylineHandler = new AsyncHttpResponseHandler(){
@Override
public void onSuccess(String content) {
try {
if(ServerDataParseUtil.deployLine(content)){
showToast("路线发布成功");
/**
* 发送 一个无序广播
*/
Intent intent = new Intent();
intent.setAction(Constant.BROADCAST_ACTION_DEPLOY_LINE);
sendBroadcast(intent);
finish();
}
} catch (JSONException e) {
showToast("数据异常!");
} catch (ResponseException e) {
showToast(e.getErrorMessage());
}
};
public void onFailure(Throwable error, String content) {
CLog.d(TAG, "deploy line failed! content:" + content);
};
};