android EventBus

news2024/10/7 6:40:42

EventBus使用小案例

文件目录结构

在这里插入图片描述

MainActivity.java

package com.example.myeventbus;

import androidx.appcompat.app.AppCompatActivity;

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

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


//参考: https://www.cnblogs.com/upwgh/p/6394901.html
//参考: https://wenku.baidu.com/view/450ba942986648d7c1c708a1284ac850ac020453.html?_wkts_=1668663664745
//参考: https://www.jianshu.com/p/a040955194fc
public class MainActivity extends AppCompatActivity {
    public ProgressBar progressBar = null;
    public int time = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (time < 100) {
                            time += 15;

                            //发送EventBus事件
                            //① 普通事件
                            // EventBus.getDefault().post(new TestEvent(time));

                            //② 粘性事件
                            EventBus.getDefault().postSticky(new TestEvent(time));

                            try {
                                Thread.sleep(200);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();
            }
        });

        progressBar = (ProgressBar) findViewById(R.id.progressbar);

        //注册 EventBus
        EventBus.getDefault().register(this);

        findViewById(R.id.goto_second_activity).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, SecondActivity.class));
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //注销 EventBus
        EventBus.getDefault().unregister(this);
    }

    //事件处理函数, 注解方式(使用注解方式的时候,函数名称可以任意取,不在局限于下面的这个4个函数了),注解分为 ThreadMode.MAIN, ThreadMode.BACKGROUND, ThreadMode.POSTING, ThreadMode.ASYNC
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(TestEvent event) {
        progressBar.setProgress(event.getMsg());
    }

    /*
    public void onEventMainThread(param)
    {
    //如果使用onEventMainThread作为订阅函数,那么不论事件是在哪个线程中发布出来的,onEventMainThread都会在UI线程中执行,接收事件就会在UI线程中运行,
    //这个在Android中是非常有用的,因为在Android中只能在UI线程中跟新UI,所以在onEvnetMainThread方法中是不能执行耗时操作的。
    }

    public void onEventPostThread(param)
    {
     //如果使用onEvent作为订阅函数,那么该事件在哪个线程发布出来的,onEvent就会在这个线程中运行,也就是说发布事件和接收事件线程在同一个线程。  
     //使用这个方法时,在onEvent方法中不能执行耗时操作,如果执行耗时操作容易导致事件分发延迟。
    }

    public void onEventBackgroundThread(param)
    {
     //如果使用onEventBackgrond作为订阅函数,那么如果事件是在UI线程中发布出来的,那么onEventBackground就会在子线程中运行,如果事件本来就是子线程中发布出来的,那么onEventBackground函数直接在该子线程中执行。
    }

    public void onEventAsync(param)
    {
   //使用这个函数作为订阅函数,那么无论事件在哪个线程发布,都会创建新的子线程在执行onEventAsync.
    }
     */
}

SecondActivity.java

package com.example.myeventbus;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

// EventBus 粘性事件
public class SecondActivity extends AppCompatActivity {
    private TextView textView = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        textView = (TextView) findViewById(R.id.test);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //处理粘性事件
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void wgh2(TestEvent event) {
        Log.e("AAA", "" + event.getMsg());
        textView.setText("同样接收到了msg" + event.getMsg());
        textView.setTextSize(25f);//调整字体大小
    }
}

TestEvent.java

package com.example.myeventbus;


public class TestEvent {
    private int mMsg;

    public TestEvent(int msg) {
        this.mMsg = msg;
    }

    public int getMsg() {
        return this.mMsg;
    }
}

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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ProgressBar
        android:id="@+id/progressbar"
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="150dp"
        android:max="100" />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="开始下载" />

    <Button
        android:id="@+id/goto_second_activity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="跳转到第二个Activity" />
</LinearLayout>

activity_second.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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <TextView
        android:id="@+id/test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="默认default..." />

</LinearLayout>

AndroidManifest.xml

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

    <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.MyEventBus">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".SecondActivity"/>
    </application>

</manifest>

build.gradle

plugins {
    id 'com.android.application'
}

android {
    compileSdkVersion 31
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.myeventbus"
        minSdkVersion 24
        targetSdkVersion 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    
    //主要是添加该选项: EventBus
    implementation('org.greenrobot:eventbus:3.0.0')
}

效果截图

普遍EventBus事件粘性事件
在这里插入图片描述在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/13988.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

两万字长文带你深入Go语言GC源码

介绍 三色标记法 三色标记法将对象的颜色分为了黑、灰、白&#xff0c;三种颜色。 黑色&#xff1a;该对象已经被标记过了&#xff0c;且该对象下的属性也全部都被标记过了&#xff08;程序所需要的对象&#xff09;&#xff1b;灰色&#xff1a;该对象已经被标记过了&#…

一段JS去除畅言免费版广告

畅言广告怎么去掉&#xff1f;去除畅言免费版广告方法是什么&#xff1f;现在很多站长都使用的社会化评论系统&#xff0c;可以让网站拥有免费的评论区&#xff0c;活化你的网站&#xff0c;但是随着很多社会化评论提供网站的关闭&#xff0c;畅言一家独大&#xff0c;现在免费…

企业网络自动化配置

更新的技术、合规性标准和不断变化的业务需求使管理当今的网络成为一项具有挑战性的任务。这解释了网络自动化在当今世界的重要性。IT 管理员现在的任务是确保网络的敏捷性和演进不会影响提供给最终用户的网络服务的稳定性、可用性和可靠性。但是&#xff0c;在此任务中&#x…

【JMX】JMX远程监控JVM参数配置

目录基本用法命令示例jconsole连接新建连接确认连接方式查看监控信息jvisualvm连接添加主机增加JMX连接查看监控信息参数说明基本参数jmxremote.access文件说明jmxremote.password文件说明文件权限异常无法验证基本用法 命令示例 #参考命令 java -Dcom.sun.management.jmxrem…

【Java学习】语法:包、权限修饰符、final、常量、枚举、抽象类、接口

文章目录一、包二、权限修饰符三、final四、常量五、枚举六、抽象类七、接口一、包 什么是包? 包是用来分门别类的管理各种不同类的&#xff0c;类似于文件夹、建包利于程序的管理和维护。建包的语法格式: package公司域名倒写.技术名称。报名建议全部英文小写&#xff0c;且…

WebRTC系列<二> 案例与工具

阅读关于webRTC的其他文章&#xff1a; WebRTC系列&#xff1c;一&#xff1e; 什么是WebRTC&#xff1f; WebRTC系列&#xff1c;二&#xff1e; 案例与工具 ---------------------------------案例--------------------------------- webrtc官网 : 官网示例代码github地址…

【Raspberry Pi】搭建NAS流媒体播放器 + ARIA2 + YAAW + 迅雷下载系统

由于种&#xff08;gu&#xff09;种&#xff08;ji&#xff09;原&#xff08;cuo&#xff09;因&#xff08;wu&#xff09;新买的Pi并没有用于任何项目上&#xff0c;看着它一天一天的封尘&#xff0c;于心不忍终于让它也做了点事。恰好这几天家里网络晚上有点卡&#xff0c…

数字集成电路设计(四、Verilog HDL数字逻辑设计方法)(二)

文章目录3. 时序电路的设计3.1 触发器3.1.1 最简单的D触发器3.1.2 带复位端的D触发器3.1.3 复杂功能的D触发器&#xff08;没有太大必要&#xff09;3.1.4 T触发器3.2 计数器3.2.1 二进制计数器3.2.2 &#xff08;重要&#xff09;任意进制计数器3.3 移位寄存器3.4 序列信号发生…

docker命令整理

第一次安装 查看docker是否安装成功 docker version 测试hello-world docker run hello-world –help 帮助 查看详细信息 docker info 搜索docker镜像网址&#xff1a;https://hub.docker.com/search 查看 查看cpu实时内存 docker stats 镜像关键字&#xff1a;images -…

MySQL-Redis进阶生成全局唯一ID

单体全局ID 场景一、随着我们商城规模越来越大&#xff0c;mysql的单表的容量不宜超过500W&#xff0c;数据量过大之后&#xff0c;我们要进行拆库拆表&#xff0c;但拆分表了之后&#xff0c;他们从逻辑上讲他们是同一张表&#xff0c;所以他们的id是不能一样的&#xff0c; …

阿里最新财报:中国商业分部收入下滑1%,年内股价累计下跌34%

11月17日&#xff0c;阿里巴巴集团&#xff08;下称“阿里巴巴”&#xff0c;HK:09988、NYSE:BABA&#xff09;公布2023财年第二季度&#xff08;对应自然年2022年第三季度&#xff09;业绩。财报显示&#xff0c;阿里巴巴2022年第三季度的收入为人民币2071.76亿元&#xff08;…

[附源码]java毕业设计流浪动物领养系统

项目运行 环境配置&#xff1a; Jdk1.8 Tomcat7.0 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技术&#xff1a; SSM mybatis Maven Vue 等等组成&#xff0c;B/S模式 M…

计算机中的加法器和比较器

本节展示了计算机中的加法器和比较器的底层实现电路设计。 加法器 计算机中加法器的实现依赖门的结构&#xff0c;如果是两个十进制进行加减&#xff0c;则首先把右边的两个0-9之间的数相加&#xff0c;它们的总和在0-18之间&#xff0c;如果答案是0-9之间&#xff0c;则直接写…

Vue--》详解vue组件及其组件化的使用

目录 Vue组件 非单文件组件 单文件组件 组件的组成部分 组件中定义methods方法 vue-cli中组件的使用步骤 vue-cli中注册全局组件 组件的props属性 props中的常用属性 组件间的样式冲突 Vue组件 vue是一个支持组件化开发的前端框架。什么是组件化开发&#xff1f;组件…

那些年我们遇到过的奇葩面试官

做了几年软件开发&#xff0c;我们都或多或少面试过别人&#xff0c;或者被别人面试过。大家最常吐槽的就是面试造火箭&#xff0c;进厂拧螺丝。今天就来吐槽一下那些奇葩&#xff08;gou&#xff09;一样的面试官 A 那是在我刚工作1年的时候&#xff0c;出去面试前端开发。 那…

虚拟筛选、高通量实验筛选化合物库

Kynurenine Pathway Library (含12,300种化合物) 靶向犬尿氨酸代谢途径关键酶的新型化合物库 KynureninePathway (犬尿氨酸途径, KP)是色氨酸代谢的主要途径&#xff0c;参与多个病理、生理过程。研究发现阿尔茨海默病、帕金森氏症等多种神经退行性疾病中的 KP 代谢产物水平…

hevc 继续色度半像素差值

1 前面已经讲了亮度的半像素差值&#xff0c;接下来讲一下色度的半像素差值。 亮度分量的运动估计已经精确到了1/4的精度&#xff0c;并且速度分量的分辨率是亮度分量的一般&#xff0c;所以色度插值需要精确到1/8的精度&#xff0c;色度分数像素插值按照基于离散余玄变换的4抽…

写代码有这20个好习惯,可以减少90%非业务的bug

每一个好习惯都是一笔财富&#xff0c;本文整理了写代码的20个好习惯&#xff0c;每个都很经典&#xff0c;养成这些习惯&#xff0c;可以规避多数非业务的bug&#xff01;希望对大家有帮助哈&#xff0c;谢谢阅读&#xff0c;加油哦~ 修改完代码&#xff0c;记得自测一下 「改…

C++初探 5-2(while循环 do while循环 输入 二维数组)

目录 注 while循环 for 与 while 编写延时循环 do while循环 基于范围的for循环&#xff08;C11&#xff09; 循环和文本输入 使用原始的cin进行输入 使用cin.get(char)进行补救 使用不同的cin.get( ) 文件尾条件 另一个cin.get( )版本 嵌套循环和二维数组 初始化…

长视频又添新变数

配图来自Canva可画 互联网广告市场依旧没有等来春天。据QuestMobile数据显示&#xff0c;2021下半年&#xff0c;中国互联网广告市场规模为3578.2亿元&#xff0c;而在2022年上半年这一数值下降至2903.6亿元&#xff0c;且同比增长率为-2.3%。 反应到具体的互联网平台上&…