1,系统与应用之间传递消息是以广播的方式体现的,Brodcast,比如开机信息,电量低信息,网络变化信息等等
MainActivity.java
Intent intent=new Intent(); intent.setAction("abc");//关键字的目的是为了标识此次启动的动机,让需要这个的进行接收
Bundle mybundle=new Bundle(); mybundle.putString("hello","发送广播信息");//bundle对象存储发送的广播内容,设置信息的关键字,根据信息的关键字获得内容 intent.putExtras(mybundle);//bundle信息装载 sendBroadcast(intent);//发送广播信息
2,接收信息的类被称为BroadcastRecevier,就是广播接收者
Myreciver.java
public class reciver_message extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String str=intent.getExtras().getString("hello"); MainActivity.txt_show.setText(str); } }
3,为了让特定的应用收到信息,需要设置关键字过滤,对接收的对象注册
AndroidMainifest.xml
<receiver android:name=".Myreciver"> <intent-filter > <action android:name="abc"/> </intent-filter> </receiver>
完整的代码:
MainActivity.java
package com.example.mysendmessage;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
static TextView txt_show;
Button btn_session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt_show=(TextView)findViewById(R.id.txt_message);
btn_session=(Button)findViewById(R.id.button_send);
btn_session.setOnClickListener(new mclick());
}
private class mclick implements View.OnClickListener {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setAction("abc");
Bundle mybundle=new Bundle();
mybundle.putString("hello","发送广播信息");
intent.putExtras(mybundle);
sendBroadcast(intent);
}
}
}
Myreciver.java
package com.example.mysendmessage;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class reciver_message extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String str=intent.getExtras().getString("hello");
MainActivity.txt_show.setText(str);
}
}
AndroidMainifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mysendmessage">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".Myreciver">
<intent-filter >
<action android:name="abc"/>
</intent-filter>
</receiver>
</application>
</manifest>