Android广播的发送与接收

2023-05-11,,

Android广播发送接收

效果图

广播发送

广播分为有序广播和无序广播

有序广播与无序广播的区别

无序广播:只要是广播接收者指定了接收的事件类型,就可以接收到发送出来的广播消息。不能修改消息。

有序广播:发送的广播消息会按照广播接收者的优先级从高到低,一级一级的发送消息。消息可以被拦截,可以被修改。

一般发送无序广播应用的较为广泛

发送无序广播

Intent intent = new Intent();
//指定发送广播的Action
intent.setAction(getPackageName());
//设置发送的数据
intent.putExtra("msg", "发送的无序广播内容");
//发送广播消息
sendBroadcast(intent);

广播接收

注册广播

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.kongqw.myapplication"> <application
…… >
…… <receiver android:name=".KongqwBroadcastReceiver">
<!-- 优先级 1000最高 -->
<intent-filter android:priority="1000">
<!-- 接收广播的action -->
<action android:name="com.example.kongqw.myapplication"/>
</intent-filter>
</receiver> </application>
</manifest>

广播接收者

package com.example.kongqw.myapplication;

import ……;

/**
* Created by kongqw on 2015/12/22.
*/
public class KongqwBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 获得广播发送的数据
String msg = intent.getStringExtra("msg");
Toast.makeText(context, "广播接收者收到了广播 msg = " + msg, Toast.LENGTH_SHORT).show();
}
}

Android广播的发送与接收的相关教程结束。

《Android广播的发送与接收.doc》

下载本文的Word格式文档,以方便收藏与打印。