发送和接收普通消息
activity_main.mxl
<?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"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="请输入要发送的信息"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="200dp"
android:singleLine="false"
android:inputType="text"
android:id="@+id/id_et"
/>
<Button
android:id="@+id/text_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送"
/>
</LinearLayout>
修改MainActivity.java 监听按键的点击事件 并在onClick()方法中发送普通广播信息
package com.commerce.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button =findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,MainActivity2.class);
startActivity(intent);
}
});
}
}
MyReceiver.java
package com.commerce.myapplication;
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) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
// throw new UnsupportedOperationException("Not yet implemented");
Log.d("text","textsdds");
String msg =intent.getStringExtra("msg");
Toast.makeText(context,msg, Toast.LENGTH_SHORT).show();
}
}
最后一步需要在AndroidManifest.xml文件中注册该消息接收器
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.hello" />
</intent-filter>
</receiver>