发送标准广播
标准广播:是一种异步的方式执行的,可以让所有的接收器收到此条广播,所以它们之间不存在顺序,示意图如下:
发送广播前我们需要先定义一个广播接收器来接受此广播,如果你用的是Android studio那么你可以在存放MainActivity的包下新建一个广播并取名为MybroadcastReceiver如图:
完成后你就可以看到它默认继承了BroadcastReceiver类并重写onReceive()方法,为了能直接看到效果我们需要加上一个显示:
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"静态广播显示",Toast.LENGTH_SHORT).show();
}
}
接下来我们找到AndroidManifest.xml文件中发现它已经替你注册好了receiver此时你需要加入以下代码,:
<receiver
android:name=".MyBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="myBroadCast"/>
</intent-filter>
</receiver>
接下来我们需要修改一下activity_main.xml文件,你需要添加一个按钮:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="162dp"
android:text="发送广播"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
所有的准备都已经就绪了,接下来我们就要发送一条广播测试一下,修改MainActivity中的代码如下:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyBroadcastReceiver mbr=new MyBroadcastReceiver();
IntentFilter intf=new IntentFilter("nanchang_1");
registerReceiver(mbr,intf);
Button button=findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//写发送广播
Intent intent=new Intent("myBroadCast");//此处的myBroadCast应该与AndroidManifest.xml文件中的保持一致
//在androi9.0以上版本需要设置包名,包名应是你存放MybroadcastReceiver的包名
intent.setPackage("com.example.myapplication21");
sendBroadcast(intent);
}
});
}
}
试所写参照《第一行代码》,若有表达上的错误请指正。