使用本地广播
Posted ccffhh
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用本地广播相关的知识,希望对你有一定的参考价值。
MainActivity中的代码,要先导入架包
package com.example.broadcasttest; import androidx.appcompat.app.AppCompatActivity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import androidx.localbroadcastmanager.content.LocalBroadcastManager; public class MainActivity extends AppCompatActivity { private IntentFilter intentFilter; private LocalReceiver localReceiver; private LocalBroadcastManager localBroadcastManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); localBroadcastManager=LocalBroadcastManager.getInstance(this); Button button=(Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent("com.example.broadcasttest.LOCAL_BROADCAST"); localBroadcastManager.sendBroadcast(intent); //sendBroadcast(intent); //sendOrderedBroadcast(intent,null); } }); intentFilter=new IntentFilter(); intentFilter.addAction("com.example.broadcasttest.LOCAL_BROADCAST"); localReceiver=new LocalReceiver(); localBroadcastManager.registerReceiver(localReceiver,intentFilter); } @Override protected void onDestroy(){ super.onDestroy(); localBroadcastManager.unregisterReceiver(localReceiver); //unregisterReceiver(networkChangeReceiver); } class LocalReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context,Intent intent){ Toast.makeText(context,"received local broadcast",Toast.LENGTH_SHORT).show(); } } /*class NetworkChangeReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent){ ConnectivityManager connectionManager=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo=connectionManager.getActiveNetworkInfo(); if (networkInfo!=null&&networkInfo.isAvailable()){ Toast.makeText(context,"network is available",Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(context,"network is unavailable",Toast.LENGTH_SHORT).show(); } } }*/ }
首先通过LocalBroadcastManager的getInstance()方法得到了它的一个实例,如何在注册广播接收器的时候调用LocalBroadcastManager的registerReceiver()方法,在发送广播的时候调用LocalBroadcastManager的sendBroadcast()方法。我们在按钮的点击事件里面发出了一条com.example.broadcasttest.LOCAL_BROADCAST广播,然后在LocalReceiver里去接收这条广播。
运行结果如下图
以上是关于使用本地广播的主要内容,如果未能解决你的问题,请参考以下文章