栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Android receiver 动态注册广播

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android receiver 动态注册广播

静态注册广播:在清单文件里注册(不好用,接收方没有打印出LOG → 清单文件中的代码不好用)
*动态注册广播:在java里注册

一 步骤

step1 工具类,定义flag 
step2 创建一个接收者
    CustomReceiver 继承 BroadcastReceiver,重写onReceive方法
step3 xml 定义点击事件
step4 MainActivity里
    1 动态注册
        //java代码来注册动态接收者
        //new一个自定义的接收者
        CustomReceiver customReceiver = new CustomReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ActionUtils.DONG_ACTION_FLAG);
        registerReceiver(customReceiver,filter);
    2 点击事件:        
        Intent intent = new Intent();
        // 参数是静态的flag (注册清单文件里的 action的name)
        intent.setAction(ActionUtils.JING_ACTION_FLAG);
        //发送广播
        sendBroadcast(intent);

二 代码


 step1 工具类,定义flag

//动态接收者flag
    String DONG_ACTION_FLAG ="com.cs.dong";

  step2 创建一个接收者

CustomReceiver.java
package com.example.myactivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

//接收者
public class CustomReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        Log.e("cs","动态接收到了");
    }
}

step3 xml 定义点击事件

android:onClick="sendDongAction"

step4 MainActivity里

package com.example.myactivity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;

public class MainActivity4 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main4);

        //java代码来注册动态接收者
        //new一个自定义的接收者
        CustomReceiver customReceiver = new CustomReceiver();
        IntentFilter filter = new IntentFilter();
        //参数是动态的flag
        filter.addAction(ActionUtils.DONG_ACTION_FLAG);
        registerReceiver(customReceiver,filter);

    }

    //点击事件,动态发送广播 给接收者
    public void sendDongAction(View view) {
        Intent intent = new Intent();
        // 参数是动态的flag
        intent.setAction(ActionUtils.DONG_ACTION_FLAG);
        //发送广播
        sendBroadcast(intent);
    }
}

效果

 注意log打不出来的时候改下这里

 静态注册步骤:(虽然不好用也记录一下)

1 工具类,定义flag 
1 创建一个接收者
CustomReceiver 继承 BroadcastReceiver,重写onReceive方法
2 在清单文件中注册静态接收者(action的name 是 静态接收者的flag)
       
       
           
               
           

       

3 xml
4 MainActivity里点击事件:
        
        Intent intent = new Intent();
        // 参数是静态的flag (注册清单文件里的 action的name)
        intent.setAction(ActionUtils.JING_ACTION_FLAG);
        //发送广播
        sendBroadcast(intent);

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/940644.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号