Android学习笔记(2)-四大组件之Broadcast使用

2020-02-24  本文已影响0人  非典型程序猿

回头看java学习笔记的进度好像快了安卓不少,感觉安卓的也得抓紧总结啊,这篇文章我会用实际的代码示例演示如何使用安卓的四大组件之一广播。

作用

广播是安卓系统中进程间通信的一种方式,可以实现不同进程之间的信息传递,在日常开发过程中使用也比较广泛。广播使用时需要先注册,分静态注册和动态注册之分,在发送广播时,有标准广播和有序广播之分,这里只演示动态注册时发送标准广播的使用。

静态注册

静态注册比较简单,只需要在AndroidMainfest.xml清单文件里声明一下,就完成了广播的注册。

      <receiver android:name=".broadcast.MyBroadCastReceiver"
            android:enabled="true"
            android:permission="com.txVideo.demo.broadcast.MYBROADCAST"
            android:exported="true">
            <intent-filter android:priority="100">
                <action android:name="com.txVideo.demo"/>
            </intent-filter>
        </receiver>

enabled 设置为 true 表示可以接收到信息 ,exported 为 true 表示能够接收到外部apk广播发送的信息,priority="100"表示该进程接收该广播的优先级,permission表示该广播的用户权限,当其他应用没有此项权限时则无法接收到我们所发的带权限的广播。

动态注册

我简单写了一个demo程序,演示了接收标准广播的动态注册使用,总共四个文件,包括一个BroadcastActivity.java,MyBroadCastReceiver.java,布局文件activity_broadcast.xml和样式文件style.xml,首先附上demo程序效果截图。


Screenshot_2020-02-24-17-49-49-04.png

BroadcastActivity代码如下:

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;

import com.txVideo.demo.broadcast.MyBroadCastReceiver;

public class BroadcastActivity extends AppCompatActivity implements View.OnClickListener {
    public static final int SHOW_MSG = 0;
    public static final int RECEIVE_MSG = 1;
    private Button registerBtn;
    private Button unregisterBtn;
    private Button sendBtn;
    private Button clearBtn;
    private static ScrollView logScrollView;
    private static TextView logTextView;
    private static StringBuffer logStringBuffer = new StringBuffer();
    private MyBroadCastReceiver receiver ;
    private boolean isRegistered; //是否已经动态注册的标志位,防止反复注册。
    private int count = 0; //发送广播计数
    /**
      * 接受消息,打印日志
      */
    public static Handler mHander = new Handler(){
        @Override
        public void handleMessage(Message message){
            switch (message.what){
                case SHOW_MSG:
                    log();
                    break;
                case RECEIVE_MSG:
                    logStringBuffer.append("已经收到了发送的广播....第"+message.arg1+"次\n");
                    log();
                    break;
                    default:
                        break;
            }
        }
    };

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

    private void initView(){
        registerBtn = findViewById(R.id.register);
        unregisterBtn = findViewById(R.id.unregister);
        sendBtn = findViewById(R.id.sendBroadcast);
        clearBtn = findViewById(R.id.clear_btn);
        logScrollView = findViewById(R.id.log_scroll);
        logTextView = findViewById(R.id.log);
        registerBtn.setOnClickListener(this);
        unregisterBtn.setOnClickListener(this);
        sendBtn.setOnClickListener(this);
        clearBtn.setOnClickListener(this);
    }
    @Override
    public void onClick(View view) {

        switch (view.getId()){
            case R.id.register:
                if(isRegistered){
                    logStringBuffer.append("广播重复,已取消该次注册....\n");
                    break;
                }
                logStringBuffer.append("广播已注册....\n");
                IntentFilter filter=new IntentFilter("com.txVideo.demo");
                receiver=new MyBroadCastReceiver();
                receiver.setReciveListener(this);
                registerReceiver(receiver,filter);
                isRegistered = true ;
                break;
            case R.id.unregister:
                if(isRegistered){
                    unregisterReceiver(receiver);
                    logStringBuffer.append("已取消该次注册....\n");
                    isRegistered = false;
                    break;
                }
                logStringBuffer.append("无广播注册,不用取消....\n");
                break;
            case  R.id.sendBroadcast:
                count++;
                logStringBuffer.append("发送广播了....计数第"+count+"次\n");
                Intent localIntent=new Intent("com.txVideo.demo");
                localIntent.putExtra("count",count);
                sendBroadcast(localIntent);  //sendOrderedBroadcast()发送有序广播
                break;
            case R.id.clear_btn:
                count = 0;
                logStringBuffer.delete(0,logStringBuffer.length());
                Toast.makeText(this,"日志已清空...",Toast.LENGTH_SHORT).show();
                break;
                default:
                    break;
        }
        mHander.sendEmptyMessage(SHOW_MSG);
    }
    /**
      * 打印操作日志
      */
    private static void log(){
        logTextView.setText(logStringBuffer.toString());
        logScrollView.post(new Runnable() {
            @Override
            public void run() {
                logScrollView.fullScroll(View.FOCUS_DOWN);
            }
        });
    }
}

MyBroadCastReceiver代码如下

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

import com.txVideo.demo.BroadcastActivity;

/**
 *
 * @date 2020/2/24
 */
public class MyBroadCastReceiver extends BroadcastReceiver{
    BroadcastActivity mActivity;
    public void setReciveListener(BroadcastActivity broadcastActivity){
        this.mActivity = broadcastActivity;
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        Message message = new Message();
        message.arg1 = intent.getIntExtra("count",0);
        message.what = BroadcastActivity.RECEIVE_MSG;
        mActivity.mHander.sendMessage(message);
    }
}

布局文件activity_broadcast.xml代码如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".BroadcastActivity">
    <Button
        android:id="@+id/register"
        style="@style/MyStyle"
        android:layout_height="wrap_content"
        android:text="动态注册"/>
    <Button
        android:id="@+id/unregister"
        style="@style/MyStyle"
        android:layout_height="wrap_content"
        android:text="取消注册"/>
    <Button
        android:id="@+id/sendBroadcast"
        style="@style/MyStyle"
        android:layout_height="wrap_content"
        android:text="发送广播"/>
    <ScrollView
        android:id="@+id/log_scroll"
        style="@style/MyStyle"
        android:layout_height="0dp"
        android:layout_weight="1">
        <TextView
            android:id="@+id/log"
            android:paddingLeft="10dp"
            android:paddingTop="10dp"
            android:paddingRight="10dp"
            android:gravity="center_vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </ScrollView>
    <Button
        android:id="@+id/clear_btn"
        style="@style/MyStyle"
        android:layout_marginBottom="10dp"
        android:layout_height="wrap_content"
        android:text="清空日志"/>
</LinearLayout>

样式文件style.xml代码

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="android:windowNoTitle">true</item>
    </style>
    <style name="MyStyle">
        <item name="android:layout_marginLeft">10dp</item>
        <item name="android:layout_marginTop">10dp</item>
        <item name="android:layout_marginRight">10dp</item>
        <item name="android:layout_width">match_parent</item>
    </style>

</resources>

在动态注册使用时需要注意的几个点

标准广播和有序广播的区别

IntentFilter filter=new IntentFilter("com.txVideo.demo");
                filter.setPriority(100);

如果是静态方式注册,receiver标签里使用

 <intent-filter android:priority="100">
                <action android:name="com.txVideo.demo"/>
            </intent-filter>

优先级越高,就越先收到广播,当第一个进程收到广播以后,如果需要截断,则在onReceive()方法调用

abortBroadcast();

进行截断,之后的进程则收不到广播,如果不截断则接下来的进程继续按顺序处理广播。

广播的初步使用就总结到这里啦,觉得对您有帮助记得点个赞~

上一篇 下一篇

猜你喜欢

热点阅读