码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-02-06 19:43:34      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:create   put   hand   使用   tco   end   one   content   interface   

方法:在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中

标签:create   put   hand   使用   tco   end   one   content   interface   

原文地址:https://www.cnblogs.com/liuleliu/p/12269730.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!