1、首先自定义一个广播接收器:MyBroadcastReceiver
package example.com.mybroadcastreceiver; 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(); } }
2、修改AndroidManifest中的代码:
<receiver android:name=".MyBroadcastReceiver" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="example.com.mybroadcastreceiver.MY_BROADCAST"/> </intent-filter> </receiver>
3、为主活动添加一个按钮:
<Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Send Broadcast"/>
4、为按钮绑定点击事件:
package example.com.mybroadcastreceiver; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //构建一个Intent对象,并把要发送的广播值传进去。 Intent intent = new Intent("example.com.mybroadcastreceiver.MY_BROADCAST"); //调用Context的sendBroadcast()方法,将广播发送出去。所有监听这条广播的接收器就都会接收到这条广播。 sendBroadcast(intent); } }); } }
5、发送有序广播:新建一个项目,自定义一个广播接收器,用于接收上面的广播。
package example.com.broadcasttest02; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class AnotherBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context,"received in AnotherBroadcastReceiver",Toast.LENGTH_SHORT).show(); } }
6、不要忘记在AndroidManifest中注册:
<receiver android:name=".AnotherBroadcastReceiver" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="example.com.broadcasttest02.MY_BROADCAST"/> </intent-filter> </receiver>
7、