Android自定義廣播接收者

發送者: java


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");
		
		//發送廣播
		//一、無序廣播 全部廣播接收者都會接收到
//		this.sendBroadcast(intent);
		//二、有序廣播,接收者按照優先級接收廣播事件
		//且高優先級廣播有權終止該事件
		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();
	}

}



接收者: android

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();
	}

}//還有二、3 和這個相似




<receiver android:name="com.pas.myreciver.MyRecivey1">
            <intent-filter  android:priority="1000">
                <action android:name="com.pas.xxxooo"/>
            </intent-filter>
        </receiver>
        <receiver android:name="com.pas.myreciver.MyRecivey2">
            <intent-filter  android:priority="500">
                <action android:name="com.pas.xxxooo"/>
            </intent-filter>
        </receiver>
        <receiver android:name="com.pas.myreciver.MyRecivey3">
            <intent-filter  android:priority="0">
                <action android:name="com.pas.xxxooo"/>
            </intent-filter>
        </receiver>
相關文章
相關標籤/搜索