Android BroadcastReceiver廣播(一):基本使用


一、什么是廣播

BroadcastReceiver是android 系統的四大組件之一,本質上就是一個全局的監聽器,用於監聽系統全局的廣播消息,可以方便的實現系統中不同組件之間的通信。

程序可以通過調用context的sendBroadcast()方法來啟動指定的BroadcastReceiver.

二、廣播的生命周期

BroadcastReceiver生命周期只有十秒左右,如果在onReceive()內做超過十秒的事情,就會報錯。所以廣播中不要執行耗時操作,可以考慮啟動一個Service來完成操作。

三、注冊BroadcastReceiver

廣播分為兩種:靜態注冊和動態注冊

1.靜態注冊

AndroidManifest.xml文件中配置

特點:常駐形廣播,程序推出后,廣播依然存在。

在AndroidManifest中進行注冊后,不管該應用程序是否處於活動狀態,都會進行監聽,比如某個程序是監聽 內存 的使用情況的,當在手機上安裝好后,
不管該應用程序是處於什么狀態,都會執行改監聽方法中的內容。

goal:創建廣播,新建一個類,繼承自BroadcastReceiver,並重寫onReceive()方法,在manifest文件中注冊該廣播,再發送廣播

2.動態注冊

代碼中動態指定廣播地址並注冊

在代碼中進行注冊后,當應用程序關閉后,就不再進行監聽。如果是在Activity中進行的注冊和解注冊,則生命周期是跟隨該Activity的。

特點:非常駐型,廣播會跟隨程序的生命周期的結束而結束

goal:新建內部類,繼承BroadcastReceiver,並重寫onReceive()方法,在onStart()中注冊廣播,在onStop()中解除注冊廣播,在發送廣播

 

A、Send  

1.1 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="btn1"
        android:textSize="32sp" />

    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="btn2"
        android:textSize="32sp" />

</LinearLayout>

1.2 MainActivity.java

package com.gatsby.intentfiltersend;

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

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button btn1, btn2;
    CrushReceiver crushReceiver;

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

        initView();
    }

    public void initView() {

        btn1 = (Button) findViewById(R.id.btn1);
        btn2 = (Button) findViewById(R.id.btn2);

        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btn1:
                CrushRegister();
                //發送動態廣播
                Intent intent1 = new Intent();
                intent1.setAction("com.android.crushGril");
                intent1.putExtra("key", "CrsuhGril");
                sendBroadcast(intent1);
                break;
            case R.id.btn2:
                //發送靜態廣播
                Intent intent2 = new Intent();
                intent2.setAction("com.android.gatsby");
                sendBroadcast(intent2);
                break;
        }
    }

    //動態注冊廣播
    public void CrushRegister() {
        //實例化IntentFilter對象
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.android.crushGril");
        crushReceiver = new CrushReceiver();
        //注冊廣播接收
        registerReceiver(crushReceiver, filter);
    }

    class CrushReceiver extends BroadcastReceiver {

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

            //通過繼承 BroadcastReceiver建立動態廣播接收器
            String action = intent.getAction();
            if (action.equals("com.android.crushGril")) {
                //通過吐司驗證接收到廣播
                Toast toast = Toast.makeText(context, "動態廣播:" + action + " value-->" + intent.getStringExtra("key"), Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.TOP, 0, 0);//將吐司設置在屏幕頂端
                toast.show();
            }
        }
    }

    /*動態注冊需在Acticity生命周期onPause通過
     *unregisterReceiver()方法移除廣播接收器,
     * 優化內存空間,避免內存溢出
     */
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(crushReceiver);
    }

    //在銷毀時要與廣播解綁
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(crushReceiver);
    }

}

1.3.XHService 動態注冊廣播

	  public void SerialPortWrite(String strcmd)
		{
		   try
		   {		       
           byte[] bytes = strcmd.getBytes();
           mOutputBuffer.clear();
           mOutputBuffer.put(bytes);
           mSerialPort.write(mOutputBuffer, bytes.length);
           Thread.sleep(200);
		   }
		   catch (Exception e)
			 {
		 	   e.printStackTrace();
		   }
		}
		
		XHService(Context context)
		{
			   	Log.d(TAG, "enter XHService");
			   	
			   	mContext=context;
			   	
			   	XHService_SerialInit();
			   	 
			   	IntentFilter filter = new IntentFilter(); 
			   	     
				  filter.addAction(Intent.ACTION_TIME_CHANGED);
				  filter.addAction(Intent.ACTION_SCREEN_ON);
				  filter.addAction(Intent.ACTION_SCREEN_OFF);
				  filter.addAction(Intent.ACTION_BOOT_COMPLETED);
			  	filter.addAction("com.xinhua.scheduled");
			  	filter.addAction("com.xinhua.ethernet_static");
			  	filter.addAction("com.xinhua.ethernet_enable");
			  	filter.addAction("com.xinhua.ethernet_dhcp");	
			  	filter.addAction("xy.update.third.apk.start");  
			  	filter.addAction("com.xinhua.scheduledSysOrApi");	
				  context.registerReceiver(mIntentReceiver, filter);
				  

					mEthManager = (EthernetManager) mContext.getSystemService(Context.ETHERNET_SERVICE);
					mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
					
					if(SystemProperties.get("persist.rild.libpath","/system/lib/libreference-ril-ls-u8300.so")
						.equals("/system/lib/libreference-ril-huawei-me909s.so")){
								Thread thread = new Thread(NetChceck);
			    			thread.start();
					}	
					mHandler = new xhHandler(FgThread.get().getLooper());	
		}
		

 mIntentReceiver 廣播接收

		BroadcastReceiver mIntentReceiver = new BroadcastReceiver()
		{
	        public void onReceive(Context context, Intent intent) 
	        {
	        			Log.d(TAG, "receiver intent :"+intent.getAction());
	        			
	        			if (intent.getAction().equals(Intent.ACTION_TIME_CHANGED))
					      {
					      	  SetMcuTime(); 
					      }

 

B、Receiver  靜態注冊廣播、傳遞信息到活動頁面Activity

2.1 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="btn1"
        android:textSize="32sp" />

    <TextView
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="繪梨衣"
        android:textSize="64sp" />
    
</LinearLayout>

2.2 AndroidManifest.xml

        <receiver android:name=".MyCrushBroadcastReceiver">
            <intent-filter>
                <action android:name="com.android.crushGril" />
                <action android:name="com.android.gatsby"/>
            </intent-filter>
        </receiver>

2.3 MainActivity.java

package com.gatsby.broadcastreceiver;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button btn1;
    TextView tv1;

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

        initView();
    }

    public void initView() {
        tv1 = (TextView) findViewById(R.id.tv1);

        btn1 = (Button) findViewById(R.id.btn1);
        btn1.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn1:
                MyCrushBroadcastReceiver myCrushBroadcastReceiver = new MyCrushBroadcastReceiver();
                Log.d("gatsby","receive value!"+myCrushBroadcastReceiver.getGatsbySting());
                tv1.setText(myCrushBroadcastReceiver.getGatsbySting());
                break;
        }
    }
}

2.3 MyCrushBroadcastReceiver.java

package com.gatsby.broadcastreceiver;

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

public class MyCrushBroadcastReceiver extends BroadcastReceiver {

    static String gatsbyString;

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals("com.android.crushGril")) {
            Toast toast = Toast.makeText(context, "靜態廣播CrushGril:" + action + " value->" + intent.getStringExtra("key"), Toast.LENGTH_SHORT);
            toast.show();
        } else if (action.equals("com.android.gatsby")) {
            gatsbyString = "Gatsby receive CrushGril";
            Toast toast = Toast.makeText(context, "靜態廣Gatsby:->" + action + " value->", Toast.LENGTH_SHORT);
            toast.show();
        }
    }

    //處理返回信息
    public static String getGatsbySting() {
        return gatsbyString;
    }
}

 


免責聲明!

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



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