发送自定义广播-标准广播
广播主要分为两种类型: 标准广播和有序广播
在发送广播之前, 我们还是需要先定义一个广播接收器来准备接收此广播才行, 不然发出去也是白发。 因此新建一个MyBroadcastReceiver
package com.example.administrator.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "received in MyBroadcastReceiver", Toast.LENGTH_SHORT).show();
}
}Code language: JavaScript (javascript)
这里当MyBroadcastReceiver收到自定义的广播时, 就会弹出“received in MyBroadcastReceiver”的提示。 然后在AndroidManifest.xml中对这个广播接收器进行修改:
<receiver
android:name=".MyBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.example.broadcasttest.MY_BROADCAST"/>
</intent-filter>
</receiver>Code language: HTML, XML (xml)
可以看到, 这里让MyBroadcastReceiver接收一条值为com.example.broadcasttest.MY_BROADCAST 的广播, 因此待会儿在发送广播的时候, 我们就需要发出这样的一条广播。
修改activity_main.xml中的代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Broadcast"
/>
</LinearLayout>Code language: HTML, XML (xml)
后台代码:
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new
Intent("com.example.broadcasttest.MY_BROADCAST");
sendBroadcast(intent);
}
});Code language: JavaScript (javascript)
Previous: 静态注册实现开机启动
Next: 权限机制