安卓廣播應用,BroadcastReceiver,詳細解說,看了就會

前言:

廣播是一個同時通知多個對象的事件通知機制。
在應用甚至手機進行某個動作後,廣播接受到是哪一個動作。
接下來我們來編寫一個簡單的廣播應用。
這個應用只需要放上去兩個按鈕,創建兩個BroadcastReceiver類。
我們判斷的三個動作分別是,開機,點擊按鈕一,點擊按鈕二,然後根據不同的動作,不同的廣播進行相應的反應。



開機的動作是系統自帶的,它有系統自己的命名,而其它兩個動作是我們自己創建的,也是我們自己所命名

過程:

我們先把佈局寫好

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:gravity="center">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="50dp"
        android:id="@+id/btn1"></Button>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn2"></Button>
</LinearLayout>

然後開始新建廣播
在這裏插入圖片描述
我們先創建一個名爲MyReceiver的類。
創建之後它會自動生成這樣的代碼:
在這裏插入圖片描述
我們需要把這一行代碼刪掉




throw new UnsupportedOperationException("Not yet implemented");

然後變成這樣:

@Override
    public void onReceive(Context context, Intent intent) {//這個方法是有對象發送廣播給它時,它調用這個方法
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        
    }

只要創建了MyReceiver之後,我們在AndroidManifest.xml中,會自動創建一個

<receiver
            android:name=".MyReceiver"
            android:enabled="true"
            android:exported="true"></receiver>

我們想要它接收廣播就要爲它創建動作,根據動作的不同在MyReceiver接受廣播時就會根據相應的動作進行相應的操作,我們這樣給它添加動作

<receiver
            android:name=".MyReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />//開機動作
                <action android:name="send" />
            </intent-filter>
        </receiver>

我們添加了兩個動作
一個是系統自帶的開機動作,一個是我們自己自定義的send動作

然後我們轉到MyReceiver類中去寫代碼,如下:

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {//接受廣播時時,參數裏面自帶一個intent,裏面有所有接受的動作
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        if(intent.getAction()== "android.intent.action.BOOT_COMPLETED")//如果爲開機動作
        {
            Log.d("開機","開機成功!!!");
        }
        else if (intent.getAction()=="send")//如果是我們自定義的send動作
        {
            Log.d("二號廣播","succeeded");
        }


    }
}

因爲開機的動作是系統自帶的,手機開機的時候,系統會自動把動作傳給MyReceiver,然後就會開始執行onReceive這個方法,但是我們的send動作如何傳給MyReceiver呢?我們在MainActivity裏面點擊按鈕2去動作給它。代碼:

btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setAction("send");//爲intent裝上動作reasureReceive
                intent.setComponent(new ComponentName("com.example.broadcast","com.example.broadcast.MyReceiver"));
                //上面這行第一個參數是我們的程序包,第二個參數是廣播,廣播在程序包下面一個目錄,所以前面就是第一個參數的值,意思是讓第一個程序包的這個類開始應用
                sendBroadcast(intent);//發送廣播
            }
        });

程序包可以在這上面看:
在這裏插入圖片描述
另一個按鈕的點擊和我們這個一模一樣,大家可以自己嘗試。

總代碼:

MainActivity.java:
package com.example.broadcast;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn1=(Button)findViewById(R.id.btn1);
        Button btn2=(Button)findViewById(R.id.btn2);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setAction("reasureReceive");//爲intent裝上動作reasureReceive
                intent.setComponent(new ComponentName("com.example.broadcast","com.example.broadcast.EnterReceiver"));
                sendBroadcast(intent);
            }
        });
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setAction("send");//爲intent裝上動作reasureReceive
                intent.setComponent(new ComponentName("com.example.broadcast","com.example.broadcast.MyReceiver"));
                sendBroadcast(intent);
            }
        });

    }
}

MyReceiver.java:

package com.example.broadcast;

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

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        if(intent.getAction()== "android.intent.action.BOOT_COMPLETED")
        {
            Log.d("開機","開機成功!!!");
        }
        else if (intent.getAction()=="send")
        {
            Log.d("二號廣播","succeeded");
        }


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