(1)定义即将要发送的内容
Intent intent = new Intent();
intent.putExtra("key", "我是一个广播");
(2)创建静态注册的receiver,继承BroadcastReceiver,并重写onReceive(Context context, Intent intent)接收消息
package com.afang.day22_exec01.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class StaticReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 接收消息
String info = intent.getStringExtra("info");
Log.i("---","onReceive");
// 处理消息
Toast.makeText(context, info, Toast.LENGTH_LONG).show();
}
}
(3)AndroidManifest.xml中进行静态注册,并添加意图过滤器的Action标签
静态注册 --清单文件中 <Application>标签下 <receiver>标签
添加意图过滤器 IntentFilter 定义接收者的Action
exported = true 支持接收外部应用发送的广播
<receiver
android:name="com.afang.day22_exec01.receiver.StaticReceiver"
android:exported="true">
<intent-filter >
<action android:name="com.afang.day22_exec01.receiver.StaticReceiver"/>
</intent-filter>
</receiver>
(4)定义广播发送的action
//4、定义广播发送的action
intent.setAction("com.afang.day22_exec01.receiver.StaticReceiver");
(5)发送广播,使用sendBroadcast(Intent intent)方法
sendBroadcast(intent);
完整代码如下
activity_main.xml文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="静态注册"
android:id="@+id/button"
android:onClick="show"/>
</RelativeLayout>
MainActivity.java代码
package com.afang.day22_exec01;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void show(View v)
{
//1、定义要发送的内容
Intent intent = new Intent();
intent.putExtra("info","静态注册");
//4、定义广播发送的action
intent.setAction("com.afang.day22_exec01.receiver.StaticReceiver");
//5、发送广播
sendBroadcast(intent);
Log.i("---", "发送完了");
}
}
StaticReceiver.java代码