您的位置:首页 > 其它

案例——有序广播

2017-06-04 22:18 211 查看
案例——有序广播通过sendOrderedBroadcast()方法发送一条有序广播1.编写用户交互界面:
<?xml version="1.0" encoding="utf-8"?>
2.点击发送有序广播按钮时事件处理
package bzu.edu.cn.guangbo;

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.创建广播接收者
package bzu.edu.cn.guangbo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class MyBroadcastReceiverOne extends BroadcastReceiver {
public MyBroadcastReceiverOne() {
}

@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
//throw new UnsupportedOperationException("Not yet implemented");
Log.i("MyBroadcastReceiverOne","自定义的广播者one,接收到了广播事件");

}

}

package bzu.edu.cn.guangbo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class MyBroadcastReceiverTwo extends BroadcastReceiver {
public MyBroadcastReceiverTwo() {
}

@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
//throw new UnsupportedOperationException("Not yet implemented");
Log.i("MyBroadcastReceiverTwo","自定义的广播者two,接收到了广播事件");

}
}

package bzu.edu.cn.guangbo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class MyBroadcastReceiverThree extends BroadcastReceiver {
public MyBroadcastReceiverThree() {
}

@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
//throw new UnsupportedOperationException("Not yet implemented");
Log.i("MyBroadcastReceiverThree","自定义的广播者three,接收到了广播事件");
}
}
清单文件:
<?xml version="1.0" encoding="utf-8"?>
效果图:问题1:程序启动后,点击“发送有序广播”按钮,发出一条广播事件,此事观察LogCat窗口下的提示信息,输出什么?为什么?
输出这样的顺序,是因为在清单文件中的
android:priority="600"
属性,值越大,越先输出。
问题2:若将广播接收者MyBroadcastReceiverTwo优先级同样设置为1000,并将MyBroadcastReceiverTwo注册在MyBroadcastOne前面,再来运行程序,观察结果,你能得出什么结论?
清单文件中 android:priority="1000" 
属性值一样时,哪一个先注册,则先输出哪一个
问题3:修改MyBroadcastReceiverTwo如下,观察结果。
android:priority="1000"此属性值比MyBroadcastReceiverTwo低的
以及晚于它注册的广播全都拦截了。

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: