IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> Android学习(广播机制) -> 正文阅读

[移动开发]Android学习(广播机制)

《Android第一行代码》第2版第5章学习笔记

*广播机制
一、Android中的广播分为两种:
1.标准广播:完全异步执行,所有广播接收器几乎同时接收,无先后顺序,效率高无法被截断
2.有序广播:同步执行,广播发出后,在同一时刻只有一个接收器接收这条广播,其逻辑执行完毕后,下一个接收器才会继续接收,有先后顺序和优先级的限制,广播消息可截断,前面的接收器截断消息,后面的接收器将无法收到广播。
二、接收系统广播(比如手机电量不足、时间区域发生改变等):
接收广播需要广播接收器,广播接收器,广播接收器可以自由地对自己感兴趣的广播进行注册。注册广播的方式有2种:
1.代码注册(动态注册):

(1)创建广播接收器:新建一个类,继承自BroadcastReceiver类,并重写其onReceive方法。

package com.example.broatcasttest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;
import android.content.BroadcastReceiver;  //必须添加

public class MainActivity extends AppCompatActivity {

    private IntentFilter intentFilter;

    private NetworkChangReceiver networkChangReceiver;   //创建一个广播接收器类

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intentFilter = new IntentFilter();  //创建类一个IntentFilter类的实例
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");  //对应监听广播的action,即网络状态发生变化时,系统发出一条android.net.conn.CONNECTIVITY_CHANGE广播
        networkChangReceiver = new NetworkChangReceiver();  //创建一个NetworkChangeReceiver类的实例
        registerReceiver(networkChangReceiver, intentFilter);
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        unregisterReceiver(networkChangReceiver);  //动态注册的广播接收器一定要取消注册
    }

    class NetworkChangReceiver extends BroadcastReceiver{  //定义一个内部类NetworkChangeReceiver,这个类继承自BroadcastReceiver

        @Override
        public void onReceive(Context context, Intent intent){  //重写父类BroadcastReceiver的onReceive方法,每当网络状态发生变化时,该方法会得到执行
            Toast.makeText(context,"network changes",Toast.LENGTH_SHORT).show();   //使用Toast简单提示
        }
    }
}

运行程序的结果:首先注册完成收到一条广播"network changes",将程序挂起(不要Back),修改手机网络状态,会看到有Toast"network changes"提示用户网络状态发生变化。

(2)进一步准确告诉用户是否有网络:修改NetworkChangReceiver的onReceive方法。

class NetworkChangReceiver extends BroadcastReceiver{  //定义一个内部类NetworkChangeReceiver,这个类继承自BroadcastReceiver

        @Override
        public void onReceive(Context context, Intent intent){  //重写父类BroadcastReceiver的onReceive方法,每当网络状态发生变化时,该方法会得到执行
            //Toast.makeText(context,"network changes",Toast.LENGTH_SHORT).show();   //使用Toast简单提示

            //注:安卓系统为保护用户设备的安全和隐私,作出了严格的规定,程序进行敏感操作,需在配置文件里面声明权限
            ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);//ConnectivityManager为系统服务类,专门用于管理网络连接
            NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();//得到NetworkInfo实例
            if (networkInfo != null && networkInfo.isAvailable()){//networkInfo.isAvailable()方法可以判断是否有网络
                Toast.makeText(context,"network is available", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(context,"network is unavailable", Toast.LENGTH_SHORT).show();
            }
        }
    }

2.静态注册实现开机启动:
动态注册灵活性大,但必须在程序启动后才能接收到广播(注册逻辑在onCreate()中)。但要让程序在未启动状态下接收广播,需要静态注册。
例 :让程序接收一条开机广播,当收到这条广播就在onReceive()方法里面执行相应的逻辑,从而实现开机启动的功能。
使用AS提供的快捷方式创建广播接收器,右击java文件夹下的包名com.example.工程名->点击New->Other->Broadcast Receiver,弹出的窗口中选中Exported、Enable属性,Exported属性表示是否允许广播接收器接收本程序以外的广播,Enable属性表示是否启用这个广播接收器。

package com.example.broatcasttest;

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

public class BootCompleteReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        Toast.makeText(context, "Boot Complete", Toast.LENGTH_SHORT).show();
    }
}

静态的广播接收器一定要在AndroidManifest.xml文件中注册才可以使用。

<receiver
    android:name=".BootCompleteReceiver"
    android:enabled="true"
    android:exported="true">
</receiver>

所有静态的广播接收器都是在<receiver></receiver>标签内注册的。android:name指定具体注册哪一个广播接收器。仅完成上述步骤的广播接收器仍然不能接收到开机广播,还需要对AndroidManifest.xml文件进行修改:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
//打开监听系统开机广播的权限

<receiver
    android:name=".BootCompleteReceiver"
    android:enabled="true"
    android:exported="true">
            
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>  //由于安卓系统启动完成会发出一条android.intent.action.BOOT_COMPLETED的广播,因此在<intent-filter>标签里添加了相应的action
    </intent-filter>
            
</receiver>

注:不要在广播接收器的onReceive()方法中添加过多逻辑或进行耗时操作,indie广播接收器中不允许开启线程,onReceive()运行较长时间没有结束就会报错。所以广播接收器一般用来打开程序其他组件(如创建状态栏通知、启动服务等)。

三、发送自定义广播
1.发送标准广播:
(1)定义一个广播接收器用于接收广播,新建MyBroadcastReceiver类:

package com.example.mybroadcasttest;

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

public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent){
        Toast.makeText(context,"received in MyBroadcastReceiver", Toast.LENGTH_SHORT).show();
    }
}

(2)修改AndroidManifest.xml文件:

<receiver
    android:name=".MyBroadcastReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
         <action android:name="com.example.broadcasttest.MY_BROADCAST"/>
    </intent-filter>
</receiver>

(3)在主活动对应的布局文件内,添加一个按钮,用于发送广播。主活动内为按钮注册监听事件:

package com.example.mybroadcasttest;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button)findViewById(R.id.send_broadcast);  //获取控件send_broadcast
        button.setOnClickListener(new View.OnClickListener() {   //为按钮控件send_broadcast注册监听器
            @Override
            public void onClick(View v) {  //当点击按钮时,发送标准广播
                Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");
                sendBroadcast(intent);//发送标准广播
            }
        });
    }
}

按照《第一行代码》第2版的例子编程,发现无法接收自定义广播,解决方案:在Intent实例定义下,添加一句:
?? ?intent.setComponent(new ComponentName(getPackageName(),"com.example.mybroadcasttest.MyBroadcastReceiver"));
setComponent()方法与ComponentName()的作用是给当前intent指定启动的活动。
运行程序:点击Send按钮,发送一条广播。

2.发送有序广播:
(1)新建BroadcastTestTwo项目,创建一个广播接收器,用于接收第一个项目中的自定义广播:

package com.example.broadcasttesttwo;

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

public class AnotherBroadcastReceiver extends BroadcastReceiver {  //定义一个广播接收器,用于接收第一个项目的自定义广播
    @Override
    public void onReceive(Context context, Intent intent) {   //接收到自定义广播弹出Toast"received in AnotherBroadcastReceiver"
        Toast.makeText(context,"received in AnotherBroadcastReceiver", Toast.LENGTH_SHORT).show();
    }
}

(2)修改注册信息:

	<receiver
            android:name=".AnotherBroadcastReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.example.broadcasttest.MY_BROADCAST"/>
            </intent-filter>
        </receiver>

(3)将mybroadcasttest工程的主活动内发送广播代码sendBroadcast(intent);修改为sendOrderedBroadcast(intent,null);
运行程序:弹出两条广播
(4)可以广播截断,设置广播接收器的优先级:

        <receiver
            android:name=".AnotherBroadcastReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter android:priority="100">
                <action android:name="com.example.mybroadcasttest.MY_BROADCAST"/>
            </intent-filter>
        </receiver>

修改MyBroadcastReceiver中的代码:

public class MyBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"received in MyBroadcastReceiver", Toast.LENGTH_SHORT).show();
        abortBroadcast();//截断广播
    }
}

四、本地广播
安卓引入本地广播机制,使用这个机制发出的广播只能在应用程序内部进行传递,并且广播接收器也只能接收来自本应用程序发出的广播。
实现方法:修改BroadcastTest工程的主活动代码:

public class MainActivity extends AppCompatActivity {
    private IntentFilter intentFilter;
    private LocalReceiver localReceiver;
    private LocalBroadcastManager localBroadcastManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        localBroadcastManager = LocalBroadcastManager.getInstance(this);//获取实例
        Button button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST");
                localBroadcastManager.sendBroadcast(intent);//发送本地广播
            }
        });
        intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.broadcasttest.LOCAL_BROADCAST");
        localReceiver = new LocalReceiver();
        localBroadcastManager.registerReceiver(localReceiver,intentFilter);//注册本地广播监听器
    }

    class LocalReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context,"received local broadcast", Toast.LENGTH_SHORT).show();
        }
    }

注:本地广播是无法通过静态注册的方式来接收的。
本地广播的优势:
可以明确地知道广播不会离开我们的程序,因此不必担心机密数据泄漏。
其他程序无法将广播发送到我们的程序内部,因此不需要担心会有安全漏洞的隐患。
发送本地广播比发送系统全局广播更加高效。

*工程:广播的最佳实践-实现强制下线功能
新建项目BroadcastBestPractice,强制关闭所有活动,返回至登录界面。
(1)新建类ActivityCollector对所有活动进行管理:

package com.example.broadcastbestpractice;

import android.app.Activity;

import java.util.ArrayList;
import java.util.List;

public class ActivityCollector {  //用于整体销毁活动
    public static List<Activity> activities = new ArrayList<>();   //定义一个Activity类型的列表List
    public static void addActivity(Activity activity){
        activities.add(activity);  //给列表List添加活动
    }
    public static void removeActivity(Activity activity){
        activities.remove(activity);  //从列表List中移除活动
    }
    public static void finishAll(){
        for (Activity activity : activities){  //遍历列表List,对每个活动进行finish
            if (!activity.isFinishing()){
                activity.finish();
            }
        }
    }
}

(2)创建BaseActivity类作为所有活动的父类。
(3)登陆界面的实现,创建LoginActivity活动,并生成相应的布局文件,编辑布局文件login_layout.xml的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"     //外层为纵向布局
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout    
        android:orientation="horizontal"   //第一行横向布局
        android:layout_width="match_parent"
        android:layout_height="60dp">

        <TextView    //显示用户名
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:textSize="18sp"
            android:text="Account:"/>

        <EditText   //用户名编辑框
            android:id="@+id/account"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_gravity="center_vertical"/>
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"   //第二行横向布局
        android:layout_width="match_parent"
        android:layout_height="60dp">

        <TextView   //显示密码
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:textSize="18sp"
            android:text="Password:"/>

        <EditText   //密码编辑框
            android:id="@+id/password"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_gravity="center_vertical"
            android:inputType="textPassword"/>
    </LinearLayout>

    <Button    //登录按钮
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:text="Login"/>

</LinearLayout>

LoginActivity活动的代码(实现登录功能,输入用户名与密码正确就跳转至主活动界面MainActivity,否则提示用户名密码错误):

package com.example.broadcastbestpractice;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends BaseActivity {

    private EditText accountEdit;   //用户名编辑框
    private EditText passwordEdit;   //密码编辑框
    private Button login;   //登录按钮

    @Override
    protected void onCreate(Bundle savedInstanceState) {   //带信息创建活动
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);  //绑定布局
        accountEdit = (EditText)findViewById(R.id.account);  //获取用户名编辑框控件
        passwordEdit = (EditText)findViewById(R.id.password);  //获取密码编辑框控件
        login = (Button)findViewById(R.id.login);  //获取登录按钮控件
        login.setOnClickListener(new View.OnClickListener() {   //为登录按钮注册监听事件

            @Override
            public void onClick(View v) {
                String account = accountEdit.getText().toString();  //定义字符串变量存储用户名
                String password = passwordEdit.getText().toString();  //定义字符串变量存储密码
                //如果账号是admin,密码是123456,则登录成功
                if (account.equals("admin") && password.equals("123456")){
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }else {
                    Toast.makeText(LoginActivity.this, "account or password is invalid", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

(4)MainActivity主活动界面是登录进去的界面,这里仅需要加入强制下线功能,修改activity_main.xml文件:

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

    <Button   //添加按钮用于触发强制下线功能
        android:id="@+id/force_offline"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send force offline broadcast"
        android:textAllCaps="false"/>

</LinearLayout>

主活动MainActivity的代码:

package com.example.broadcastbestpractice;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button)findViewById(R.id.force_offline);  //获取按钮控件
        button.setOnClickListener(new View.OnClickListener() {   //为按钮注册监听事件
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.example.broadcastbestpractice.FORCE_OFFLINE");//用于通知程序用户下线的广播
                sendBroadcast(intent);
            }
        });
    }
}

(5)通知用户强制下线广播就需要一个广播接收器来接收这条广播,广播接收器里面需要弹出一个对话框阻塞用户的正常操作,但如果创建的是一个静态注册的广播接收器,是无法在onReceive()方法里弹出对话框这样的UI控件,因此在BaseActivity中注册广播接收器:

package com.example.broadcastbestpractice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class BaseActivity extends AppCompatActivity {
    private ForceOfflineReceiver receiver;  //创建一个强制下线广播接收器receiver
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("BaseActivity",getClass().getSimpleName());//获取当前实例的类名并打印出来
        ActivityCollector.addActivity(this);
    }

    @Override
    protected void onResume() {   //注册广播接收器
        super.onResume();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.broadcastbestpractice.FORCE_OFFLINE");
        receiver = new ForceOfflineReceiver();
        registerReceiver(receiver,intentFilter);
    }

    @Override
    protected void onPause() {   //取消广播接收器
        super.onPause();
        if (receiver != null){
            unregisterReceiver(receiver);
            receiver = null;
        }
    }
    //注册与取消写入上面的两个函数是为了保证只有处于栈顶的活动才能接收到这条强制下线广播

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }

    class ForceOfflineReceiver extends BroadcastReceiver {  //定义一个内部类ForceOfflineReceiver强制下线接收器类,继承自BroadcastReceiver类

        @Override
        public void onReceive(final Context context, Intent intent) {  //重写BroadcastReceiver类的onReceive方法

            AlertDialog.Builder builder = new AlertDialog.Builder(context);  //构建一个对话框
            builder.setTitle("Warning");  //对话框标题
            builder.setMessage("You are forced to be offline.Please try to login again.");  //对话框内容
            builder.setCancelable(false);//设置对话框不可取消,后续不做处理
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {  //点击OK进行下面的销毁操作
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCollector.finishAll();//销毁所有活动
                    Intent intent = new Intent(context, LoginActivity.class);
                    context.startActivity(intent);//重新启动登录活动
                }
            });
            builder.show();
        }
    }
}

(6)对AndroidManifest.xml文件修改:

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.BroadcastBestPractice">
        <activity android:name=".MainActivity">
        </activity>
        <activity
            android:name=".LoginActivity"
            android:exported="true" >
            <intent-filter>

                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>
        </activity>
    </application>

</manifest>

运行项目:登录页面登录后,进入第二个页面,弹出对话框,点击OK销毁活动,返回登录页面。

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2021-08-26 12:13:18  更:2021-08-26 12:15:34 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2025年5日历 -2025/5/1 9:55:19-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码