刚才介绍了广播的接收,现在介绍下广播的发送,广播的类型有如下几种:1.系统广播(wife,开机,电量,这些都是发广播的)2.普通广播(intent开发者自己定义)sendBrodacast(intent)就行
首先我们来看一下发送端的acitvity1.这是它的xml文件,里面只有一个Button
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.wj.administrator.layout.activity.sendActivity"> <Button android:id="@+id/sendbutton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Button" /> </LinearLayout>
2.这是它的acitivty文件
1.找到这个button并设置监听but=(Button)findViewById(R.id.sendbutton); but.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendData(); } });2.发送广播单独写一个方法public void sendData() {
//intent 里面什么也不用给不需要指定到哪里 Intent intent=new Intent(); intent.setAction("hhhh"); intent.putExtra("name","weism"); sendBroadcast(intent); }
下面是完整的发送端acitivty的代码
public class sendActivity extends AppCompatActivity { Button but; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_send); but=(Button)findViewById(R.id.sendbutton); but.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendData(); } }); } public void sendData() { Intent intent=new Intent(); intent.setAction("hhhh"); intent.putExtra("name","weism"); sendBroadcast(intent); } }下面来看一下接收端如何接收:
//接收发过来的信息
String name=intent.getStringExtra("name");
//筛选action
IntentFilter filter=new IntentFilter(); filter.addAction("hhhh"); this.registerReceiver(receiver,filter);
//这个是完整的动态接收
public class NotifictionActivity extends AppCompatActivity { Button but; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notifiction); BroadcastReceiver receiver=new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String name=intent.getStringExtra("name"); but.setText("name"+name ); } }; IntentFilter filter=new IntentFilter(); filter.addAction("hhhh"); this.registerReceiver(receiver,filter); but=(Button)findViewById(R.id.buttonnotifry);除了上面的广播,还有有序广播:是指接收者而言,先接收的可以对广播进行改变或者截断。2.还有一种app应用广播,本地广播此app可用,广播的是观察者模式,非常困难的模式,比如Evnetbus类也是观察者模式