android利用广播(BroadcastReceiver)传递数据

利用广播传递数据,肯定需要用Intent或者bundle,那首先第一步:

一、注册广播接收器

  public class MainActivity extends AppCompatActivity {
     MyReceiver myReceiver;
 
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
 
     //注册广播接收器
     myReceiver = new MyReceiver();
     IntentFilter intentFilter = new IntentFilter();
     intentFilter.addAction("com.fengchi.broadcastreceiver.MYRECEIVER");
     registerReceiver(myReceiver, intentFilter);

      }

  } 

二、发送广播(在这个步骤进行传递数据)

    // "com.fengchi.broadcastreceiver.MYRECEIVER"与注册广播时的action保持一致
    Intent intent = new Intent("com.fengchi.broadcastreceiver.MYRECEIVER");
    intent.putExtra("ID", ID);         //向广播接收器传递数据
    sendBroadcast(intent);

三、广播接收器的实现类(可以是内部类也可以是外部类)

public BroadcastReceiver MyReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, "action  = " + action);
            if (action.equals("com.fengchi.broadcastreceiver.MYRECEIVER")) {
                // 接收到广播传来的数据
                int ID =intent.getIntExtra("ID");
                ToastUtils.showToast_Now(mContext,ID + "");
            }else{
                ToastUtils.showToast_Now(mContext,"");
            }
         }
    };

 

    原文作者:fengchi95
    原文地址: https://blog.csdn.net/qq_28670711/article/details/83379509
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞