如何使用 LocalBroadcastManager?
此示例演示了如何使用 LocalBroadcastManager
步骤 1 − 在 Android Studio 中创建一个新项目,转至文件 ⇒ 新建项目并填写所有必需的详细信息以创建新项目。
步骤 2 − 将以下代码添加到 res/layout/activity_main.xml 中。
<?xml version = "1.0" encoding = "utf-8"?> <LinearLayout 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:gravity = "center" android:layout_height = "match_parent" tools:context = ".MainActivity" android:orientation = "vertical"> <TextView android:id = "@+id/actionEvent" android:textSize = "40sp" android:layout_marginTop = "30dp" android:layout_width = "wrap_content" android:layout_height = "match_parent" /> </LinearLayout>
在上面的代码中,我们采取文本视图来显示广播值。
步骤 3 − 将以下代码添加到 src/MainActivity.java 中
<?xml version = "1.0" encoding = "utf-8"?> import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView actionEvent; @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("custom-action-local-broadcast")); actionEvent = findViewById(R.id.actionEvent); actionEvent.setText("Click"); actionEvent.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent("custom-action-local-broadcast"); intent.putExtra("name","Tutorialspoint.com"); LocalBroadcastManager.getInstance(MainActivity.this).sendBroadcast(intent); } }); } private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Get extra data included in the Intent String message = intent.getStringExtra("name"); actionEvent.setText(message); } }; }
让我们尝试运行你的应用程序。我假设你已将你的实际 Android 移动设备连接到计算机。要从 Android Studio 运行应用程序,请打开项目的某个活动文件,然后单击工具栏中的运行 图标。选择你的移动设备作为选项,然后检查将显示你的默认屏幕的移动设备 -
现在单击文本视图,它将显示如下所示的结果 -
单击 此处 下载项目代码
广告