无序广播:
public class MainActivity extends Activity {
privateMyBroadCast myBroadCast;
privateButton button;
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBroadCast=new MyBroadCast();
button=(Button) findViewById(R.id.button1);
button.setOnClickListener(newOnClickListener() {
@Override
publicvoid onClick(View v) {
Intent intent=newIntent();
intent.setAction("heheh");
intent.putExtra("name","jajaja");
sendBroadcast(intent);
}
});
}
@Override
protectedvoid onResume() {
IntentFilter filter=newIntentFilter("heheh");
registerReceiver(myBroadCast, filter);
super.onResume();
}
@Override
protectedvoid onPause() {
// TODO Auto-generated method stub
unregisterReceiver(myBroadCast);
super.onPause();
}
}
package com.qianfeng.lx_broadcastsend;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyBroadCast extends BroadcastReceiver {
@Override
publicvoid onReceive(Context context, Intent intent) {
String message=intent.getStringExtra("name");
System.out.println("=========================================="+message);
}
}
静态定义广播接收者
只要在清单文件中进行如下配置就可以了:
<receiverandroid:name="com.jason.android23_broadcastreceiver.MyBroadcastReceiver">
<intent-filter>
<actionandroid:name="SIMPLE_BROADCAST" />
</intent-filter>
</receiver>
有序广播 :
2.1发送有序广播
/**
* 发送有序广播
* @param view
*/
publicvoid send2(View view){
Intentintent = new Intent();
intent.setAction("com.itheima.broadcasttest.songwennuan");
//有序广播,可被拦截,可终止,可以修改数据。
sendOrderedBroadcast(intent,null, new FinalReceiver(), null, 0, "给农民兄弟发10000块钱", null);
}
2.2接收广播:
接收并修改广播:
Stringmessage = getResultData();
System.out.println("省级部门得到中央的消息:"+message);
abortBroadcast();
setResultData("给农民兄弟发5000块钱");