Android Studio Beginner Example: Broadcasting

This chapter will not explain in detail first, and will be supplemented later. If you have any questions, please type them out in the comment area~~~

There are two examples: dining in the dining hall and counting ducks

The effect of the first instance:

Effect drawing of counting ducks

 Canteen example:

First the layout code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white">
    <RelativeLayout
        android:id="@+id/ll_horn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp">
        <ImageView
            android:id="@+id/image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/horn" />
        <TextView
            android:id="@+id/tv_right_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/image"
            android:background="@drawable/content_right_bg"
            android:gravity="center"
            android:text="点击喇叭"
            android:textColor="@android:color/white" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/tv_right_content"
            android:layout_marginTop="20dp"
            android:layout_toRightOf="@id/image"
            android:src="@drawable/foods" />
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/ll_horn"
        android:layout_marginTop="100dp" >
        <ImageView
            android:id="@+id/iv_rabbit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:src="@drawable/rabbit" />
        <TextView
            android:id="@+id/tv_left_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@id/iv_rabbit"
            android:background="@drawable/content_left_bg"
            android:gravity="center"
            android:text="开饭啦!"
            android:textColor="@android:color/white"
            android:visibility="gone" />
    </RelativeLayout>
</RelativeLayout>

 Corresponding logic java code

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity62 extends AppCompatActivity {
    private ImageView image;
    private TextView tv_left_content, tv_right_content;
    private MyBroadcastReceiver receiver;

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

    private void init() {
        image = findViewById(R.id.image);
        tv_left_content = findViewById(R.id.tv_left_content);
        tv_right_content = findViewById(R.id.tv_right_content);
        receiver = new MyBroadcastReceiver();
        String action = "Open_Rice";
        IntentFilter intentFilter = new IntentFilter(action);
        registerReceiver(receiver, intentFilter);
        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_right_content.setText("开饭啦!");
                Intent intent = new Intent();
                intent.setAction("Open_Rice");
                sendBroadcast(intent);
            }
        });
    }

    class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("Open_Rice")) {
                tv_left_content.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}

 Interface code for counting ducks

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/count_ducks_bg">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_marginLeft="80dp">
        <ImageView
            android:id="@+id/iv_horn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:src="@drawable/horn" />
        <TextView
            android:id="@+id/tv_left_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@id/iv_horn"
            android:background="@drawable/content_left_bg"
            android:gravity="center"
            android:text="有序报数"
            android:textColor="@android:color/white"
            android:visibility="gone" />
    </RelativeLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:gravity="center_horizontal">
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <TextView
                android:id="@+id/tv_one"
                style="@style/badge_style"/>
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/duck" />
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <TextView
                android:id="@+id/tv_two"
                style="@style/badge_style"/>
            <ImageView
                style="@style/duck_style" />
        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <TextView
                android:id="@+id/tv_three"
                style="@style/badge_style"/>
            <ImageView
                style="@style/duck_style" />
        </LinearLayout>
    </LinearLayout>
</RelativeLayout>

 Corresponding logic Java code

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
//相比无序广播,有序广播的广播效率较低,但此类型是有先后顺序的,并可被拦截。
//同样的 继承BroadcastReceiver
//动态注册MyReceiver广播
//MyReceiver  one = new MyReceiver ();
//IntentFilter filter = new IntentFilter();
数值越大,优先级越高。如果两个广播接收者的优先级相同,则先注册的广播接收者优先级高。
//filter.setPriority(1000);
//filter.addAction("Intercept_Stitch");
//registerReceiver(one,filter);
public class MainActivity63 extends AppCompatActivity {
    private MyBroadcastReceiverOne one;
    private MyBroadcastReceiverTwo two;
    private MyBroadcastReceiverThree three;
    private ImageView iv_horn;
    private TextView tv_left_content, tv_one, tv_two, tv_three;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main63);
        registerReceiver();
        init();
    }

    private void init() {
        iv_horn = findViewById(R.id.iv_horn);
        tv_left_content = findViewById(R.id.tv_left_content);
        tv_one = findViewById(R.id.tv_one);
        tv_two = findViewById(R.id.tv_two);
        tv_three = findViewById(R.id.tv_three);
        iv_horn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_left_content.setVisibility(View.VISIBLE);
                iv_horn.setClickable(false);  //设置喇叭图片为不可点击的状态
                Intent intent = new Intent();
                intent.setAction("Count_Ducks");      // 定义广播的事件类型
                //这里与无序广播会有不同 sendBroadcast方法为发送无序
                sendOrderedBroadcast(intent, null);  // 发送有序广播

//                MyBroadcastReceiverThree receiver = new MyBroadcastReceiverThree();
//                sendOrderedBroadcast(intent,null,receiver, null, 0, null, null); // 发送有序广播
            }
        });
    }

    private void registerReceiver() {
        // 动态注册MyBroadcastReceiverTwo广播
        two = new MyBroadcastReceiverTwo();
        IntentFilter filter2 = new IntentFilter();
        filter2.setPriority(1000);
        filter2.addAction("Count_Ducks");
        registerReceiver(two, filter2);
        // 动态注册MyBroadcastReceiverOne广播
        one = new MyBroadcastReceiverOne();
        IntentFilter filter1 = new IntentFilter();
        filter1.setPriority(1000);
        filter1.addAction("Count_Ducks");
        registerReceiver(one, filter1);
        // 动态注册MyBroadcastReceiverThree广播
        three = new MyBroadcastReceiverThree();
        IntentFilter filter3 = new IntentFilter();
        filter3.setPriority(600);
        filter3.addAction("Count_Ducks");
        registerReceiver(three, filter3);
    }
    //同样的 继承BroadcastReceiver  重写onReceive方法 当接收时控制图片、鸭子数量等
    private int num = 0; // 存放接收到广播消息时鸭子图片上方需要显示的序号
    class MyBroadcastReceiverOne extends BroadcastReceiver {
        @Override
//        用于接收程序发送的有序广播
        public void onReceive(Context context, Intent intent) {
            tv_one.setVisibility(View.VISIBLE);     //将第一只鸭子图片上方的序号控件tv_one设置为显示状态
            num = num + 1;
            tv_one.setText(num + "");       //将变量num显示到控件tv_one上
            Log.i("BroadcastReceiverOne", "广播接收者One,接收到了广播消息");
            delay();        //将广播消息延迟500毫秒后传递到下一个广播接收者中

        }
    }

    class MyBroadcastReceiverTwo extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            tv_two.setVisibility(View.VISIBLE);
            num = num + 1;
            tv_two.setText(num + "");
            Log.i("BroadcastReceiverTwo", "广播接收者Two,接收到了广播消息");
//            abortBroadcast(); //拦截有序广播
//            Log.i("BroadcastReceiverTwo","我是广播接收者Two,广播消息被我拦截了");
            delay();
        }
    }

    class MyBroadcastReceiverThree extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            tv_three.setVisibility(View.VISIBLE);
            num = num + 1;
            tv_three.setText(num + "");
            Log.i("BroadcastReceiverThree", "广播接收者Three,接收到了广播消息");
            delay();


            //终结广播,若在第一只鸭子中执行  二和三都不会接收到广播  终结后面执行的广播  根据优先级
//            abortBroadcast();
        }
    }

    /**
     * 延迟500毫秒
     */
    private void delay() {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(one);
        unregisterReceiver(two);
        unregisterReceiver(three);
    }
}

おすすめ

転載: blog.csdn.net/m0_59558544/article/details/130717471