在Android Studio中如何实现广播(保姆级教程)

目录

一.本章要学习的内容

二.代码部分

(一)创建项目

(二)项目结构

(三)MainActivity

(四)ActionReceiver

(五)MyOrderReceiverOne

(六)MyReceiver

(七)StaticReceiver

(八)actionlayout.xml

(九)activity_main.xml

(十)staticlayout.xml

(十一)AndroidManifest.xml

三.运行部分

(一)打开Device Manager

(二)选择上次创建的虚拟机

(三)运行

(四)运行结果

四.广播

(一)简介

1.什么是广播

2 .广播的特性

3 .广播角色

4 .应用场景

5 .广播分类

6. 注册方式

(二)广播的使用

1.广播的发送

2.广播的实现

3.广播的终止

 (三)总结


 

一.本章要学习的内容

  1. 了解使用Intent进行组件通信的原理;
  2. 了解Intent过滤器的原理和匹配机制;
  3. 掌握发送和接收广播的方法

任务1、普通广播;

任务2、系统广播;

任务3、有序广播;

1、练习使用静态方法和动态方法注册广播接收器

2、练习发送广播消息的方法;

二.代码部分

(一)创建项目

 

(二)项目结构

(三)MainActivity

package com.example.demo5;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void staticSys(View view){
        Intent intent = new Intent(MainActivity.this, StaticReceiver.class);
        startActivity(intent);
    }
    public void actionSys(View view){
        Intent intent = new Intent(MainActivity.this, ActionReceiver.class);
        startActivity(intent);
    }
}

(四)ActionReceiver

package com.example.demo5;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;

import com.example.demo5.MyReceiver;
import com.example.demo5.R;

public class ActionReceiver extends Activity {
    protected static final String ACTION = "com.example.demo5.ACTION_CUSTOM_EVENT";

    private MyReceiver myReceiver;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.actionlayout);
    }
    public void sendAct(View view){
        Intent intent=new Intent();       //实例化Intent
        intent.setAction(ACTION);      //设置Intent的action属性
        intent.putExtra("info","动态方法");
        sendBroadcast(intent);
    }
    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    public void register(View view){
        myReceiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION);
        registerReceiver(myReceiver, filter);
    }
    public void unregister(View view){
        unregisterReceiver(myReceiver);
    }
}

(五)MyOrderReceiverOne

package com.example.demo5;

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

public class MyOrderReceiverOne extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println("我收到有序的啦");
    }
}

(六)MyReceiver

package com.example.demo5;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {
    public MyReceiver() {// 构造函数,可以在这里进行初始化操作,但通常不需要
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast t = Toast.makeText(context,"广播方式:"+intent.getStringExtra("info"), Toast.LENGTH_SHORT);//从Intent中提取名为"info"的额外信息,创建一个Toast来显示消息
        t.setGravity(Gravity.TOP,0,40);// 设置Toast的位置为屏幕顶部,并稍微偏移(x偏移为0,y偏移为40像素)
        t.show();// 显示Toast
    }
}

(七)StaticReceiver

package com.example.demo5;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.example.demo5.R;

public class StaticReceiver extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.staticlayout);
    }
    public void send(View view){
        Intent intent = new Intent();
        //intent.setAction("com.eoeAndroid.broadcastReceiver.RECEIVER_ACTION");
        intent.putExtra("info","静态方法");
        intent.setComponent(new ComponentName(getPackageName(),"com.example.demo5.MyReceiver"));
        sendBroadcast(intent);
    }
}

(八)actionlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.demo5.ActionReceiver">

    <Button
        android:id = "@+id/actBroadcast"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:text = "发送Broadcast"
        android:onClick="sendAct"
        />

    <Button
        android:id = "@+id/registerReceiver"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:text = "创建"
        android:onClick="register"
        />

    <Button
        android:id = "@+id/unregisterReceiver"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:text = "注销"
        android:onClick="unregister"
        />

</LinearLayout>


(九)activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.demo5.MainActivity">
    <Button
        android:id = "@+id/staticButton"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:text = "静态方法"
        android:onClick="staticSys"
        tools:ignore="OnClick" />

    <Button
        android:id = "@+id/actionButton"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:text = "动态方法"
        android:onClick="actionSys"
        tools:ignore="OnClick" />

</LinearLayout>

(十)staticlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.demo5.StaticReceiver">
    <Button
        android:id = "@+id/btnBroadcast"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:text = "发送Broadcast"
        android:onClick="send"
        />
</LinearLayout>

(十一)AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@drawable/ic_launcher_background"
        android:supportsRtl="true"
        android:theme="@style/Theme.Demo5"
        tools:targetApi="31">
        <activity
            android:name="com.example.demo5.MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.Demo5">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.example.demo5.StaticReceiver" />
        <activity android:name="com.example.demo5.ActionReceiver" />
        <receiver android:name=".MyReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.eoeAndroid.broadcastReceiver.RECEIVER_ACTION"/>
            </intent-filter>
        </receiver>
        <receiver android:name=".MyOrderReceiverOne" android:exported="true">
            <intent-filter android:priority="1000">
                <action android:name="Intercept_Stitch"/>
            </intent-filter>
        </receiver>



    </application>

</manifest>

三.运行部分

(一)打开Device Manager

(二)选择上次创建的虚拟机

(三)运行

(四)运行结果

四.广播

(一)简介

1.什么是广播

广播是一种用于应用程序之间或应用程序内部进行通信的机制。它允许一个应用程序发送一个广播消息,而其他应用程序可以注册接收这个广播消息并做出相应的处理。广播可以用于很多场景,比如在系统状态变化时通知应用程序、在应用程序之间传递数据、在应用程序内部进行通信等。

2 .广播的特性

广播接收者的生命周期是非常短暂的,在接收到广播的时候创建,onReceive()方法结束之后销毁
广播接收者中不要做一些耗时的工作,否则会弹出Application No Response错误对话框
最好也不要在广播接收者中创建子线程做耗时的工作,因为广播接收者被销毁后进程就成为了空进程,很容易被系统杀掉(耗时的较长的工作最好放在服务中完成)

3 .广播角色

广播分为两个角色:广播发送者、广播接收者

4 .应用场景

包括但不限于以下几种:

  • 系统状态变化通知:应用程序可以注册系统广播接收者来监听系统状态的变化,比如网络连接状态变化、电池电量变化、屏幕解锁等,以便应用程序在状态变化时做出相应的处理。
  • 应用内部通信:应用程序内部的不同模块之间可以通过广播来进行通信,比如一个模块发送广播消息,而其他模块注册广播接收者来接收消息并做出相应的处理。
  • 跨应用程序通信:应用程序之间可以通过广播来进行跨应用程序的通信,比如一个应用程序发送广播消息,而其他应用程序注册广播接收者来接收消息并做出相应的处理。
  • 后台任务处理:应用程序可以使用广播来触发后台任务的执行,比如在特定的时间点发送一个定时广播来执行后台任务或发送一个系统事件广播来触发后台服务的处理。
  • 事件通知和交互:应用程序可以使用广播来发送事件通知,比如通知用户有新消息到达、用户完成了某个操作等,也可以通过广播实现应用程序之间的交互,比如启动其他应用程序或传递数据。

5 .广播分类

  • 系统广播:Android中内置了多个系统广播:只要涉及到手机的基本操作(如开机、网络状态变化、拍照等等),都会发出相应的广波,每个广播都有特定的Intent - Filter(包括具体的action)
  • 标准广播(Normal Broadcast):一种完全异步执行的广播方式,sendBroadcast()方法来发送,通过onReceive方法接收。消息传递效率比较高,但所有receivers(接收器)的执行顺序不确定,所有接收者几乎同时接收到广播消息。缺点在于:接收者不能将处理结果传递给下一个接收者,并且无法终止广播Intent的传播,直到没有匹配的接收器广播时才能停止传播。
  • 有序广播(Ordered Broadcast):用sendOrderedBroadcast发送,有如下特点:按照接收者的优先顺序来接收广播,优先级别在intentFilter中的priority中声明,-1000到1000之间,值越大优先级越高。可以终止广播的继续传播,接受者可以修改intent的内容。同级别接收顺序是随机的,级别低的后收到能截断广播的继续传播,高级别的广播接收器接收广播后能截断广播和处理广播

6. 注册方式

  • 安卓广播可以通过静态注册和动态注册两种方式来实现广播接收者的注册。
  • 静态注册广播接收者是通过在AndroidManifest.xml文件中声明广播接收者来实现的,系统会在应用程序安装时自动注册广播接收者。
  • 动态注册广播接收者是通过代码动态注册广播接收者,可以在应用程序运行时注册和取消注册广播接收者。

(二)广播的使用


1.广播的发送

广播 是 用”意图(Intent)“标识
定义广播的本质 = 定义广播所具备的“意图(Intent)”
广播发送 = 广播发送者 将此广播的“意图(Intent)”通过sendBroadcast()方法发送出去

2.广播的实现

继承自BroadcastReceivre基类,必须复写抽象方法onReceive()方法

广播接收器接收到相应广播后,会自动回调onReceive()方法
一般情况下,onReceive方法会涉及与其他组件之间的交互,如发送Notification、启动service等
默认情况下,广播接收器运行在UI线程,因此,onReceive方法不能执行耗时操作,否则将导致ANR

3.广播的终止

// 终止广播,不再传递给下一个接收者
        abortBroadcast();

 (三)总结

广播是 Android 系统中一种用于应用组件之间进行通信的机制。广播可以分为普通广播和有序广播两种类型。

  • 普通广播是一种完全异步的广播方式,广播发出后,所有注册了相应动作的接收者都会接收到广播,但接收者之间没有顺序关系,无法拦截或修改广播。
  • 有序广播是一种按照优先级顺序依次传递给接收者的广播方式,接收者可以对广播进行拦截、修改或终止传递。有序广播通过 abortBroadcast() 方法可以终止广播,不再传递给其他接收者。
  • 广播可以通过静态注册和动态注册两种方式进行注册,静态注册通过在 AndroidManifest.xml 文件中声明 < receiver> 元素,动态注册通过调用 registerReceiver() 和 unregisterReceiver() 方法。
  • 广播可以通过 Intent 来传递数据,接收者可以通过 Intent 的方法获取传递的数据。广播可以用于监听系统事件、应用内部通信、跨应用通信等场景。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值