MainActivity中的代码,要先导入架包
package com.example.broadcasttest;@R_419_5565@ androIDx.appcompat.app.AppCompatActivity;@R_419_5565@ androID.content.broadcastReceiver;@R_419_5565@ androID.content.Context;@R_419_5565@ androID.content.Intent;@R_419_5565@ androID.content.IntentFilter;@R_419_5565@ androID.net.ConnectivityManager;@R_419_5565@ androID.net.NetworkInfo;@R_419_5565@ androID.os.Bundle;@R_419_5565@ androID.vIEw.VIEw;@R_419_5565@ androID.Widget.button;@R_419_5565@ androID.Widget.Toast;@R_419_5565@ 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里去接收这条广播。
运行结果如下图
总结
以上是内存溢出为你收集整理的使用本地广播全部内容,希望文章能够帮你解决使用本地广播所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)