Android studio 广播 Android studio 广播的简单使用代码详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Android studio 广播 Android studio 广播的简单使用代码详解

Mo.城   2021-04-09 我要评论
想了解Android studio 广播的简单使用代码详解的相关内容吗,Mo.城在本文为您仔细讲解Android studio 广播的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,studio,广播,Android,studio,广播使用,下面大家一起来学习吧。

1.在布局文件里面加入按钮,等会发送广播

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context=".MainActivity3">
    
    <Button
        android:id="@+id/send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="发送广播"></Button>
        
</LinearLayout>

2.使用广播的第一步当然是创建一个广播接受者

public class MyBrodestReciver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            //判断action是否为添加的action,如果是则toast
            String action = intent.getAction();
            if (action.equals("one_brodest")){
                Toast.makeText(context, "发送了一个广播", Toast.LENGTH_SHORT).show();
            }
        }
    }

3.创建完广播接受者以后注册广播,并且添加一个action

//新建intentFilter对象 通过addAction添加广播
     IntentFilter intentFilter = new IntentFilter();
     intentFilter.addAction("one_brodest");

4.然后注册一个广播

//注册广播
     MyBrodestReciver myBrodestReciver = new MyBrodestReciver();
     registerReceiver(myBrodestReciver,intentFilter);

5.到这里广播的注册已经完成接下来就是使用了

//做一个点击事件发送一个广播
     send.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
             Intent intent = new Intent();
             intent.setAction("one_brodest");
             sendBroadcast(intent);
         }
     });

6.这就是点击之后的效果,成功发送了一个广播!!!!!!!!!!!!!!!

点击之后的效果

7.最后一步,销毁广播

@Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁广播
        unregisterReceiver(brodestReciver);
    }

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们