Android BroadcastReceiver实例Demo(有序广播的发送)

上一篇简介了广播的发送,这篇主要介绍下,有序广播的发送。

设置完相关属性的时候,广播就会依照有序的方式进行发送:

发送顺序:

先发送第二条广播;

再发送第一条广播;

最后发送第三条广播。

代码例如以下:

Android BroadcastReceiver实例Demo(有序广播的发送)_第1张图片


布局文件:

activity_main(一个Button):



    

MainActivity:

package com.android_broadcasereceiverdemo2;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
	private Button button;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		button = (Button) findViewById(R.id.button1);
		button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setAction("myaction");
				intent.putExtra("name", "梅西");
				sendOrderedBroadcast(intent, null);
			}
		});
	}
}


FirstBroadcast:

package com.android_broadcasereceiverdemo2;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class FirstBroadcast extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		
		String name = intent.getStringExtra("name");
		Toast.makeText(context, "第一条广播已发送..."+name, Toast.LENGTH_SHORT).show();
//		abortBroadcast();//当加上这条代码的时候,广播发送到此结束,即第三条广播不会再收到。
	}

}

SecondBroadcast:

package com.android_broadcasereceiverdemo2;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class SecondBroadcast extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		
		String name = intent.getStringExtra("name");
		Toast.makeText(context, "第二条广播已发送..."+name, Toast.LENGTH_SHORT).show();
	}

}


ThirdBroadcast:

package com.android_broadcasereceiverdemo2;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class ThirdBroadcast extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		
		String name = intent.getStringExtra("name");
		Toast.makeText(context, "第三条广播已发送..."+name, Toast.LENGTH_SHORT).show();
	}

}

AndroidManifest.xml(非常关键):




    

    
        
            
                

                
            
        

        
            
            
                
            
        
        
        
            
                
            
        
        
        
            
                
            
        
    



须要源代码的读者能够到我的资源中下载。

你可能感兴趣的:(Android BroadcastReceiver实例Demo(有序广播的发送))