广播发送者:
1.创建广播地址字符串
2.创建一个Intent来发送广播
3.调用sendBroadcast方法,发送广播
public class MainActivity extends AppCompatActivity {
private Button sendButton;
// 1. 创建广播地址字符串
private static final String MyBroadcast = "com.user.mybroadcast";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 2.创建一个Intent来发送广播
final Intent intent= new Intent(MyBroadcast);
Bundle mBundle = new Bundle();
mBundle.putString("Data", "夜深人静,小心火烛");
intent.putExtras(mBundle);
sendButton = (Button) findViewById(R.id.sendbutton);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 在这里进行广播的发送
// 3.调用方法,发送广播
sendBroadcast(intent);
// 传递数据给广播接收者一句话:夜深人静,小心火烛
}
});
}
}
广播接收者
接受步骤1.创建一个类继承BroadcastReceiver
步骤2.重写onReceive方法
步骤3.在manifest注册一个接收者,指定类文件和过滤器
public class MyBroadCast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("打印","收到广播");
Bundle bundle = intent.getExtras();
String data = bundle.getString("Data");
Log.e("da印",""+data);
Toast.makeText(context, ""+data, Toast.LENGTH_SHORT).show();
}
}
<receiver android:name=".MyBroadCast">
<intent-filter>
<action android:name="com.user.mybroadcast"/>
</intent-filter>
</receiver>
根据系统开机广播,开机启动
创建一个类继承BroadcastReceiver,重写onReceive方法
在manifest注册一个接收者
声明权限
public class Mybroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("提示开机启动","成功");
Toast.makeText(context, "sdfdfdsfdf", Toast.LENGTH_SHORT).show();
}
}
<receiver android:name=".Mybroadcast">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>