Android BroadcastReceiver广播(基本使用)

五陵年少金市东,银鞍白马渡春风。这篇文章主要讲述Android BroadcastReceiver广播:基本使用相关的知识,希望能为你提供帮助。
一、什么是广播
BroadcastReceiver是android 系统的四大组件之一,本质上就是一个全局的监听器,用于监听系统全局的广播消息,可以方便的实现系统中不同组件之间的通信。
程序可以通过调用context的sendBroadcast()方法来启动指定的BroadcastReceiver.
二、广播的生命周期
BroadcastReceiver生命周期只有十秒左右,如果在onReceive()内做超过十秒的事情,就会报错。所以广播中不要执行耗时操作,可以考虑启动一个Service来完成操作。
三、注册BroadcastReceiver
广播分为两种:静态注册和动态注册
1.静态注册
【Android BroadcastReceiver广播(基本使用)】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); }}

 
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; } }

 

    推荐阅读