01-使用 BroadcastReceiver:
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:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/btnSendMsg" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="发送消息" /> </LinearLayout>
MainActivity.java:
package com.example.learnbroadcastreceiver; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //1.2================================================= findViewById(R.id.btnSendMsg).setOnClickListener(this); //==================================================== } @Override public void onClick(View view) { switch (view.getId()){ case R.id.btnSendMsg: //1.4================================================= Intent i = new Intent(this,MyReceiver.class); i.putExtra("data","jiekexueyuan"); sendBroadcast(i); //==================================================== //1.3=================================================== // sendBroadcast(new Intent(this,MyReceiver.class)); } //====================================================== } }
MyService.java:
package com.example.learnbroadcastreceiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //1.1====================================== System.out.println("接收到了消息,消息的内容是:" + intent.getStringExtra("data")); //========================================= } }
02-动态注册和注销 BroadcastReceiver: