发送者:
package com.pas.broad;import android.os.Bundle;import android.app.Activity;import android.content.Intent;import android.view.Menu;import android.view.View;public class MainActivity extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } public void click(View v) { Intent intent=new Intent(); intent.setAction("com.pas.xxxooo"); //发送广播 //1、无序广播 所有广播接收者都会接收到// this.sendBroadcast(intent); //2、有序广播,接收者按照优先级接收广播事件 //且高优先级广播有权终止该事件 this.sendOrderedBroadcast(intent, null); //使用此方法直接指定接收者 无论如何都会接收到信息 sendOrderedBroadcast(intent, null, new FinalRecivey(), null, 0, null, null); }}
package com.pas.broad;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.util.Log;import android.widget.Toast;public class FinalRecivey extends BroadcastReceiver{ @Override public void onReceive(Context arg0, Intent arg1) { Log.i("broad", "Final检测到自定义广播"); Toast.makeText(arg0, "Final检测到自定义广播", 0).show(); }}
接收者:
package com.pas.myreciver;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.util.Log;import android.widget.Toast;public class MyRecivey1 extends BroadcastReceiver{ @Override public void onReceive(Context arg0, Intent arg1) { Log.i("broad", "1检测到自定义广播"); Toast.makeText(arg0, "1检测到自定义广播", 0).show(); abortBroadcast(); }}//还有2、3 和这个类似