如何将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文件