如何将BroadcastReceiver中的信息传到Activity中

Posted liuleliu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将BroadcastReceiver中的信息传到Activity中相关的知识,希望对你有一定的参考价值。

方法:在BroadcastReceiver中定义一个接口,在Activity中定义一个BroadcastReceiver的对象,采用动态注册,在Activity中定义接口中的方法并通过BroadcastReceiver对象调用该方法,具体代码如下:

自定义BroadcastReceiver:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyBroadcastReceiver extends BroadcastReceiver {
private Handle handle;
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        String msg=intent.getStringExtra("msg");
        handle.handle(msg);//调用接口中的方法

    }
    public interface Handle{        //接口定义
        public void handle(String s);
    };

public void setHandle(Handle handle)
{
    this.handle=handle;
}
}    

  Activity:

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements MyBroadcastReceiver.Handle {

private Button broad=null;
private MyBroadcastReceiver receiver;//定义广播接收器对象
private ServiceConnection serviceConnection =new ServiceConnection() {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        broad=(Button)super.findViewById(R.id.broad);


        receiver=new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.EDIT");
        registerReceiver(receiver,intentFilter);//动态注册

        receiver.setHandle(this);
}

  
    broad.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent it=new Intent();
            it.setAction("android.intent.action.EDIT");

            it.putExtra("msg","广播已接收");
            MainActivity.this.sendBroadcast(it);
        }
    });
    }

    @Override
//实现接口中的方法
    public void handle(String s) {
   
        Toast.makeText(this,s,Toast.LENGTH_SHORT).show();
    }
    protected void onDestroy() {
                super.onDestroy();
                unregisterReceiver(receiver);     //注销广播接收器
            }
 }

注意一点就是这里要使用动态注册,不能用静态注册,因此不需要去配置AndroidMainifest.xml文件

以上是关于如何将BroadcastReceiver中的信息传到Activity中的主要内容,如果未能解决你的问题,请参考以下文章

Android的BroadcastReceiver组件

BroadcastReceiver机制-Android12

BroadcastReceiver机制-Android12

如何将参数传递给 Python 模块中的主函数?

如何将多个参数传递给 ASP.NET CORE MVC 中的 HttpGet 方法?

如何将权限传递给 Broadcastreceiver?