Android 发送有序广播

xiaoxiao2021-02-28  78

   这次案例运行的效果就是点击下面运行图上的发送有序广播,会有在Android Studio上出现广播接收的提示信息。

这是此次案例的布局图:

1、首先要根据要求进行布局,具体的布局的代码如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/stitch_one" tools:context="com.example.bz0209.myapplication.MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="80dp" android:onClick="send" android:text="发送有序广播" android:paddingLeft="5dp" android:paddingRight="5dp" android:background="#FBFBFF" android:textSize="20sp"/> </RelativeLayout> 2、然后编写MainActivity实现界面交互,利用sendOrderedBroadcast方法发送一条有序广播。具体代码如下:

import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void send(View view){ Intent intent=new Intent(); intent.setAction("Intercept_Stitch"); sendOrderedBroadcast(intent,null); } } 3、然后创建广播接收者,需要注意有序广播只有一个广播者接受,区分优先级。我在这里按照要求定义了三个广播接收者。具体实现如下:

第一个接受者:

import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * Created by Administrator on 2017/6/7. */ public class MyBroadcastReceiverOne extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Log.i("MyBroadcastReceiverOne","自定义的广播接受者One,接收到了广播事件"); } } 第二个,第三个类似。

4、然后在清单文件中需要注册三个receiver,分别对应三个广播接收者。具体代码如下:

<receiver android:name=".MyBroadcastReceiverOne"> <intent-filter android:priority="1000"> <action android:name="Intercept_Stitch"/> </intent-filter> </receiver> <receiver android:name=".MyBroadcastReceiverTwo"> <intent-filter android:priority="200"> <action android:name="Intercept_Stitch"/> </intent-filter> </receiver> <receiver android:name=".MyBroadcastReceiverThree"> <intent-filter android:priority="600"> <action android:name="Intercept_Stitch"/> </intent-filter> </receiver>

最后点击运行后,会出现以下信息:

 

                                                                          ~感谢浏览~

转载请注明原文地址: https://www.6miu.com/read-59461.html

最新回复(0)