赞
踩
Android系统提供了一个BroadcastReceiver组件,此组件可以监听来自系统或其他组件的广播。
广播接收者可以监听系统中的广播消息,实现不同组件之间的通信。
每个组件都可以当接收者和广播者。大部分是android系统当广播者。
如图:
1.创建广播接收者:
得到以下初始代码:
package com.example.broadcastreceiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class MyReceiver extends BroadcastReceiver { //onReceive方法用于实现广播接收者相关操作 @Override public void onReceive(Context context, Intent intent) { // TODO: This method is called when the BroadcastReceiver is receiving // an Intent broadcast. // throw new UnsupportedOperationException("Not yet implemented");//这个删除即可 } }
例子:
发送广播:
xml:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="发送有序广播" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" android:onClick="send" /> </androidx.constraintlayout.widget.ConstraintLayout>
2.MainActivity文件:
package com.example.broadcastreceiver; import androidx.appcompat.app.AppCompatActivity; import android.content.ComponentName; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void send(View view) { Intent intent = new Intent(); intent.setComponent(new ComponentName("com.example.broadcastreceiver", "com.example.broadcastreceiver.MyReceiver")); sendBroadcast(intent); } }
3.广播接收者java文件:
package com.example.broadcastreceiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "我收到了广播!", Toast.LENGTH_SHORT).show(); } }
结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。