Android四大組件:BroadcastReceiver的使用


BroadcastReceiver

 

作用:

監聽 / 接收 應用 App 發出的廣播消息,並 做出響應

 

應用場景:

  • Android不同組件間的通信(含 :應用內 / 不同應用之間)
  • 多線程通信
  • 與 Android 系統在特定情況下的通信

如:電話呼入時、網絡可用時、耳機插入時

 

 

 

初步使用BroadcastReceiver:實現向BroadcastRecever發送消息,在控制台輸出BroadcastReceiver接收到的消息

 

步驟一:

activity_main.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="com.contentprovide.liuliu.brodcast_demo1.MainActivity">

<Button
    android:id="@+id/btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="傳送消息"
    />

</LinearLayout>

 

 

步驟二:

創建一個BroadcastReceiver(自定義類繼承BroadcastReceiver,重寫onReceive方法),

package com.contentprovide.liuliu.brodcast_demo1;

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

public class MyReceiver extends BroadcastReceiver {


    @Override
    public void onReceive(Context context, Intent intent) {

        String s = intent.getStringExtra("date");

        System.out.println("===================接收到的消息是:"+s);

    }
}

 這一步系統會在AndroidManifest.xml文件中自動靜態注冊BroadcastReceiver

 

步驟三: Java代碼向廣播接收器傳遞信息

package com.contentprovide.liuliu.brodcast_demo1;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button btn;

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

        btn = (Button) findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(MainActivity.this, MyReceiver.class);
                intent.putExtra("date", "11111");
//                傳送消息
                sendBroadcast(intent);

            }
        });


    }


}

實現效果: 

 

 

 

 動態注冊和注銷BroadcastReceiver


在Android Studio中一鍵創建BroadcastReceiver時系統會自動的靜態注冊,但是很多時候為了優化程序,在需要的時候動態注冊,不需要時及時注銷

 

步驟一:activity_main.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="com.contentprovide.liuliu.brodcast_demo2.MainActivity">


    <Button
        android:id="@+id/btn_send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="傳送消息" />

    <Button
        android:id="@+id/btn_reg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="注冊接收器" />

    <Button
        android:id="@+id/btn_unreg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="注銷接收器" />


</LinearLayout>

 

 步驟二:創建BroadcastRecever,聲明一個對象用作廣播接收器的類型

MyReceiver.java

package com.contentprovide.liuliu.brodcast_demo2;

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

public class MyReceiver extends BroadcastReceiver {

//聲明一個字符串變量儲存當前廣播接收器的路徑,用作接收廣播的類型
    public static final String Path = "com.contentprovide.liuliu.brodcast_demo2";

    @Override
    public void onReceive(Context context, Intent intent) {

        String s = intent.getStringExtra("date");

        System.out.println("===================接收到的消息是:"+s);

    }
}

 

 步驟三:使用Java代碼動態注冊和注銷廣播接收器

 

package com.contentprovide.liuliu.brodcast_demo2;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {


    Button btn_send, btn_reg, btn_unreg;

    Intent intent;

    MyReceiver myReceiver = null;

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

        btn_send = (Button) findViewById(R.id.btn_send);
        btn_reg = (Button) findViewById(R.id.btn_reg);
        btn_unreg = (Button) findViewById(R.id.btn_unreg);

        btn_send.setOnClickListener(this);
        btn_reg.setOnClickListener(this);
        btn_unreg.setOnClickListener(this);

        intent = new Intent(MyReceiver.Path);


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_send:
                intent.putExtra("date", "11111");
                sendBroadcast(intent);
                break;
            case R.id.btn_reg:
//添加判斷語句是為了防止重復注冊和重復注銷
                if (myReceiver == null) {
                    myReceiver = new MyReceiver();
//                     設置接收廣播的類型,在實例化后面的括號中調用在MyReceiver.java中聲明的字符串變量
                    IntentFilter intentFilter = new IntentFilter(myReceiver.Path);
//                    注冊廣播接收器
                    registerReceiver(myReceiver, intentFilter);
                }

                break;
            case R.id.btn_unreg:

                if (myReceiver != null) {
//                    注銷廣播接收器
                    unregisterReceiver(myReceiver);
                    myReceiver = null;
                }
                break;
        }
    }


}

 實現效果:在點擊注冊播放器前點擊傳送消息,控制台沒有消息輸出。先點擊注冊播放器再點擊發送消息,控制台有消息輸出。點擊注銷播放器后再點擊發送消息,控制台也沒有消息輸出

 

 

 

 

  • Android中內置了多個系統廣播:只要涉及到手機的基本操作(如開機、網絡狀態變化、拍照等等),都會發出相應的廣播
  • 每個廣播都有特定的Intent - Filter(包括具體的action),Android系統廣播action如下:
系統操作 action
監聽網絡變化 android.net.conn.CONNECTIVITY_CHANGE
關閉或打開飛行模式 Intent.ACTION_AIRPLANE_MODE_CHANGED
充電時或電量發生變化 Intent.ACTION_BATTERY_CHANGED
電池電量低 Intent.ACTION_BATTERY_LOW
電池電量充足(即從電量低變化到飽滿時會發出廣播 Intent.ACTION_BATTERY_OKAY
系統啟動完成后(僅廣播一次) Intent.ACTION_BOOT_COMPLETED
按下照相時的拍照按鍵(硬件按鍵)時 Intent.ACTION_CAMERA_BUTTON
屏幕鎖屏 Intent.ACTION_CLOSE_SYSTEM_DIALOGS
設備當前設置被改變時(界面語言、設備方向等) Intent.ACTION_CONFIGURATION_CHANGED
插入耳機時 Intent.ACTION_HEADSET_PLUG
未正確移除SD卡但已取出來時(正確移除方法:設置--SD卡和設備內存--卸載SD卡) Intent.ACTION_MEDIA_BAD_REMOVAL
插入外部儲存裝置(如SD卡) Intent.ACTION_MEDIA_CHECKING
成功安裝APK Intent.ACTION_PACKAGE_ADDED
成功刪除APK Intent.ACTION_PACKAGE_REMOVED
重啟設備 Intent.ACTION_REBOOT
屏幕被關閉 Intent.ACTION_SCREEN_OFF
屏幕被打開 Intent.ACTION_SCREEN_ON
關閉系統時 Intent.ACTION_SHUTDOWN
重啟設備 Intent.ACTION_REBOOT

注:當使用系統廣播時,只需要在注冊廣播接收者時定義相關的action即可,並不需要手動發送廣播,當系統有相關操作時會自動進行系統廣播

 

 

 

推薦相關博客:https://www.jianshu.com/p/ca3d87a4cdf3

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM