Android中如何使用本地广播
这篇文章主要介绍了Android中如何使用本地广播的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Android中如何使用本地广播文章都会有所收获,下面我们一起来看看吧。
创新互联建站是一家企业级云计算解决方案提供商,超15年IDC数据中心运营经验。主营GPU显卡服务器,站群服务器,南充服务器托管,海外高防服务器,机柜大带宽租用·托管,动态拨号VPS,海外云手机,海外云服务器,海外服务器租用托管等。
MainActivity代码
package com.example.luobo.mybroadcastreceiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private Button button; private IntentFilter intentFilter; private LocalBroadcastManager localBroadcastManager ; private LocalReceiver localReciiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button)findViewById(R.id.send_button); button.setOnClickListener(this); localBroadcastManager = LocalBroadcastManager.getInstance(this);//使用 intentFilter = new IntentFilter(); intentFilter.addAction("com.example.luobo.mybroadcastreceiver.LOCAL_BROADCAST"); localReciiver = new LocalReceiver(); localBroadcastManager.registerReceiver(localReciiver,intentFilter); } @Override protected void onDestroy() { super.onDestroy(); localBroadcastManager.unregisterReceiver(localReciiver); } @Override public void onClick(View view) { Intent intent = new Intent("com.example.luobo.mybroadcastreceiver.LOCAL_BROADCAST"); localBroadcastManager.sendBroadcast(intent); } class LocalReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context,"received local broadcast",Toast.LENGTH_SHORT).show(); } } }
首先通过LocalBroadcastManager(本地广播管理类)的getInstance(this)方法获取实例,注册广播消息时是调用localBroadcastManager实例的registerReceiver(参数1,参数2)方法注册(参数1是本地广播接受者,参数2是过滤器只选择接收特定的广播消息),调用localBroadcastManager实例的sendBroadcast(Initent initent)方法发送广播消息。
MyRecevity
package com.example.luobo.mybroadcastreceiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context,"Received in MyBroadCastReceiver",Toast.LENGTH_SHORT).show(); abortBroadcast(); } }
activity_main.xml
AndroidMainfest.aml
关于“Android中如何使用本地广播”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“Android中如何使用本地广播”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注创新互联行业资讯频道。
网站题目:Android中如何使用本地广播
网站URL:http://myzitong.com/article/piijjp.html