Android广播的发送与接收

来源:互联网 发布:监控平台的端口号 编辑:程序博客网 时间:2024/05/26 17:49

Android广播的发送与接收

效果图

这里写图片描述

广播发送

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

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

无序广播:只要是广播接收者指定了接收的事件类型,就可以接收到发送出来的广播消息。不能修改消息。
有序广播:发送的广播消息会按照广播接收者的优先级从高到低,一级一级的发送消息。消息可以被拦截,可以被修改。

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

发送无序广播

Intent intent = new Intent();//指定发送广播的Actionintent.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();    }}
0 0