Android基础------Broadcast基础

 

广播分为普通广播和有序广播,广播的注册方式分为动态注册和静态注册

动态注册广播是在代码中进行注册,这种注册方式下广播的生命周期随Activity,不一定同时创建,但是基本同时销毁。动态注册广播的步骤为:创建广播接收者,创建过滤器、添加action、注册广播,发送广播

静态注册广播生命周期不受Activity的生命周期影响,这种注册方式是在AndroidManifest.xml文件中进行配置。

普通广播的注册

package com.example.mybroadcast.registerbroadcast;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.mybroadcast.R;

/**
 * 动态注册广播,此注册广播的方式下,广播的生命周期跟随Activity,不一定同生,但一般共死
 */
public class DynamicRegisterActivity extends AppCompatActivity {

    private Button button;
    public static final String ACTION_TEST  = "com.example.mybroadcast.TEST";
    DynamicRegisterReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic_register);
        button = findViewById(R.id.btn_dynamic_register);
        receiver = new DynamicRegisterReceiver();
        /**
         * 定义过滤器,添加Action,注册广播
         */
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_TEST);
        registerReceiver(receiver,intentFilter);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //发送广播
                Intent intent = new Intent();
                intent.setAction(ACTION_TEST);
                sendBroadcast(intent);
            }
        });
    }

    /**
     * 创建广播接收者
     */
    class DynamicRegisterReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(ACTION_TEST.equals(action)){
                Toast.makeText(context,"动态注册广播成功",Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //注销广播
        if(receiver != null){
            unregisterReceiver(receiver);
        }
    }
}
<?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">

   <Button
       android:id="@+id/btn_dynamic_register"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:textSize="20sp"
       android:text="动态注册广播"
       android:layout_centerInParent="true"/>

</RelativeLayout>

 

下面是静态注册广播

package com.example.mybroadcast.registerbroadcast;

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

/**
 * 静态注册广播,监听开机
 * 监听手机的开机事件需要在AndroidManifest.xml申请权限
 */
public class StaticRegisterReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        System.out.println("Action为:"+action);
        Toast.makeText(context,"开机了!!!!!",Toast.LENGTH_SHORT).show();

    }
}

AndroidManifest.xml文件

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

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <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/AppTheme">
        <activity android:name=".orderbroadcast.SendOrderBroadcast">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".registerbroadcast.DynamicRegisterActivity">

        </activity>

        <receiver android:name=".registerbroadcast.StaticRegisterReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        
        <receiver android:name=".orderbroadcast.HighLevelReceiver">
            <!--     priority属性设置广播接收者的优先级,取值为-1000~1000,数值越大优先级越高    -->
            <intent-filter android:priority="1000">
                <action android:name="com.example.mybroadcast.SEND_ORDER"/>
            </intent-filter>
        </receiver>
        <receiver android:name=".orderbroadcast.LowLevelReceiver">
            <intent-filter android:priority="-1000">
                <action android:name="com.example.mybroadcast.SEND_ORDER"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

 

有序广播

有序广播在注册时要注意为其设置优先级,有序广播有终止广播继续传递的方法,有序广播可以携带数据传递,有更改数据的方法。

package com.example.mybroadcast.orderbroadcast;

import androidx.appcompat.app.AppCompatActivity;

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

import com.example.mybroadcast.R;

/**
 * 发送有序广播
 */
public class SendOrderBroadcast extends AppCompatActivity {

    Button button;
    public static final String ACTION_SEND_ORDER = "com.example.mybroadcast.SEND_ORDER";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_order_broadcast);
        button = findViewById(R.id.btn_send_order);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(ACTION_SEND_ORDER);
                Bundle bundle = new Bundle();
                bundle.putCharSequence("msg","这是一个有序广播");
                intent.putExtras(bundle);
                sendOrderedBroadcast(intent,null,null,null, Activity.RESULT_OK,null,bundle);
            }
        });
    }
}

 

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".orderbroadcast.SendOrderBroadcast">

    <Button
        android:id="@+id/btn_send_order"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="发送有序广播"/>

</LinearLayout>
package com.example.mybroadcast.orderbroadcast;

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

/**
 * 优先级高的广播接收者
 */
public class HighLevelReceiver extends BroadcastReceiver {
    private static final String TAG = "HighLevelReceiver:";

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = getResultExtras(true);
        String msg = bundle.getCharSequence("msg").toString();
        Log.d(TAG,msg);
        /**
         * abortBroadcast();此方法可以终止有序广播继续往下传播
         */
        abortBroadcast();
        //设置信息并将信息再放入广播中
        bundle.putCharSequence("msg","信息已经改变");
        setResultExtras(bundle);
    }
}
package com.example.mybroadcast.orderbroadcast;

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

/**
 * 优先级低的广播接收者
 */
public class LowLevelReceiver extends BroadcastReceiver {
    private static final String TAG = "LowLevelReceiver:";

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = getResultExtras(true);
        String msg = bundle.getCharSequence("msg").toString();
        Log.d(TAG,msg);
    }
}

 

-----仅为自己的学习笔记

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章