广播Intent的三种方式总结

来源:互联网 发布:机器人模型软件 编辑:程序博客网 时间:2024/04/29 17:21

1.android有序广播和无序广播的区别 

BroadcastReceiver所对应的广播分两类:普通广播和有序广播。 

普通广播通过Context.sendBroadcast()方法来发送。它是完全异步的。 

所有的receivers接收器的执行顺序不确定。    因此,所有的receivers接收器接收broadcast的顺序不确定。 

这种方式效率更高。但是BroadcastReceiver无法使用setResult系列,getResult系列及abort系列API 

有序广播是通过Context.sendOrderedBroadcast来发送。所有的receiver依次执行。 

BroadcastReceiver可以使用setResult系列函数来结果传给下一个BroadcastReceiver,通过getResult系列函数来取得上个BroadcastReceiver返回的结果,并可以abort系列函数来让系统丢弃该广播让,使用该广播不再传送到别的BroadcastReceiver。 

可以通过在intent-filter中设置android:priority属性来设置receiver的优先级。优先级相同的receiver其执行顺序不确定。 

如果BroadcastReceiver是代码中注册的话,且其intent-filter拥有相同android:priority属性的话,先注册的将先收到广播。 

有序广播,即从优先级别最高的广播接收器开始接收,接收完了如果没有丢弃,就下传给下一个次高优先级别的广播接收器进行处理,依次类推,直到最后。 

2.sendBroadcast和sendStickyBroadcast的区别 

sendBroadcast中发出的intent在ReceverActivity不处于onResume状态是无法接受到的,即使后面再次使其处于该状态也无法接受到。 

而sendStickyBroadcast发出的Intent当ReceverActivity重新处于onResume状态之后就能重新接受到其Intent.这就是the Intent will be held to be re-broadcast to future receivers这句话的表现。就是说sendStickyBroadcast发出的最后一个Intent会被保留,下次当Recevier处于活跃的时候,又会接受到它。 

3. FLAG的影响 
1)FLAG_RECEIVER_REPLACE_PENDING 
这个flag 将会将之前的Intent 替代掉。加了这个flag,在发送一系列的这样的Intent 之后, 中间有些Intent 有可能在你还没有来得及处理的时候,就被替代掉了。 
2)FLAG_RECEIVER_REGISTERED_ONLY: 
如果Intent 加了这个Flag, 那么在Androidmanifest.xml 里定义的Receiver 是接收不到这样的Intent 的。 
3)FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT: 
如果Intent加了这个Flag,那么在启动检查时只能接受在代码中注册的Receiver。这个标志是唯一使用的系统服务作为一种方便避免实施更复杂的机制在启动完成检测。

sendStickyBroadcast 的理解和使用

要知道区别首先需要看一下Android Developers Reference, 它可是我们最好的老师了,sendBroadcast 大家应该都会用了我就不赘述了,下面来看看sendStickyBroadcast

google官方的解释是:

Perform a sendBroadcast(Intent) that is "sticky," meaning the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value ofregisterReceiver(BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(Intent).

You must hold the BROADCAST_STICKY permission in order to use this API. If you do not hold that permission,SecurityException will be thrown.

大概的意思是说: 发出的广播会一直滞留(等待),以便有人注册这则广播消息后能尽快的收到这条广播。其他功能与sendBroadcast相同。但是使用sendStickyBroadcast 发送广播需要获得BROADCAST_STICKY permission,如果没有这个permission则会抛出异常。

 

这个解释看了后似懂非懂的,于是就写了个例子试了下,下面把代码贴出了,希望能还大家一起讨论

[java] view plaincopyprint?
  1. package com.android.test;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.os.Bundle;  
  7. import android.view.View;  
  8. import android.view.View.OnClickListener;  
  9. import android.widget.Button;  
  10.   
  11. public class StickyBroadcastTest extends Activity {  
  12.    
  13.  private Button mSendBroadcast;  
  14.  private Button mSendStickyBroadcast;  
  15.  private Button mNextActivity;  
  16.  private Context mContext;  
  17.    
  18.  private int mStickyBrcCount;  
  19.     
  20.     /** Called when the activity is first created. */  
  21.     @Override  
  22.     public void onCreate(Bundle savedInstanceState) {  
  23.         super.onCreate(savedInstanceState);  
  24.         setContentView(R.layout.main);  
  25.         mContext = getApplicationContext();  
  26.         mSendBroadcast = (Button)findViewById(R.id.broadcast);  
  27.         mSendStickyBroadcast = (Button)findViewById(R.id.stickybroadcast);  
  28.         mNextActivity = (Button)findViewById(R.id.next_activity);  
  29.           
  30.         mSendBroadcast.setOnClickListener(new OnClickListener() {  
  31.      
  32.    @Override  
  33.    public void onClick(View v) {  
  34.       
  35.     Intent intent = new Intent("com.android.action.broadcast");  
  36.     mContext.sendBroadcast(intent);  
  37.    }  
  38.   });  
  39.           
  40.         mSendStickyBroadcast.setOnClickListener(new OnClickListener() {  
  41.      
  42.    @Override  
  43.    public void onClick(View v) {  
  44.     mStickyBrcCount++;  
  45.     Intent intent = new Intent("com.android.action.sticky.broadcast");  
  46.     intent.putExtra("sent_count", mStickyBrcCount);  
  47.     mContext.sendStickyBroadcast(intent);  
  48.       
  49.    }  
  50.   });    
  51.         mNextActivity.setOnClickListener(new OnClickListener() {  
  52.      
  53.    @Override  
  54.    public void onClick(View v) {  
  55.     Intent intent = new Intent(StickyBroadcastTest.this, MyReceiverActivity.class);  
  56.     startActivity(intent);     
  57.       
  58.    }  
  59.   });  
  60.     }  
  61.   
  62.  @Override  
  63.  protected void onResume() {  
  64.   // TODO Auto-generated method stub   
  65.   super.onResume();  
  66.   mStickyBrcCount = 0;  
  67.  }  
  68.      
  69. }  
  70.   
  71.    
  72. //MyReceiverActivity    
  73. package com.android.test;  
  74.   
  75. import android.app.Activity;  
  76. import android.content.BroadcastReceiver;  
  77. import android.content.Context;  
  78. import android.content.Intent;  
  79. import android.content.IntentFilter;  
  80. import android.os.Bundle;  
  81. import android.util.Log;  
  82.   
  83. public class MyReceiverActivity extends Activity {  
  84.   
  85.  private IntentFilter mIntentFilter;  
  86.  private final static String TAG = "MyReceiverActivity";  
  87.     /** Called when the activity is first created. */  
  88.     @Override  
  89.     public void onCreate(Bundle savedInstanceState) {  
  90.         super.onCreate(savedInstanceState);  
  91.         setContentView(R.layout.broadcast_receiver);  
  92.           
  93.         mIntentFilter = new IntentFilter();     
  94.         mIntentFilter.addAction("com.android.action.broadcast");     
  95.         mIntentFilter.addAction("com.android.action.sticky.broadcast");     
  96.   
  97.     }  
  98.        
  99.  private BroadcastReceiver  mReceiver = new BroadcastReceiver () {  
  100.   @Override  
  101.   public void onReceive(Context context, Intent intent) {  
  102.    final String action = intent.getAction();  
  103.    int count = intent.getIntExtra("sent_count", -1);  
  104.    Log.d(TAG, "action = " + action + "and count = " + count);  
  105.      
  106.    //context.removeStickyBroadcast(intent);   
  107.   }  
  108.  };  
  109.   
  110.  @Override  
  111.  protected void onPause() {  
  112.   // TODO Auto-generated method stub   
  113.   super.onPause();  
  114.   unregisterReceiver(mReceiver);     
  115.   
  116.  }   
  117.   
  118.  @Override  
  119.  protected void onResume() {  
  120.   // TODO Auto-generated method stub     
  121.   super.onResume();  
  122.   registerReceiver(mReceiver, mIntentFilter);   
  123.  }  
  124.      
  125. }  

运行结果如图:

首先点击next Activity从代码中可以看到receiver已经注册,但Log无输出,这是当然的了~~~因为没有广播发出自然就不会有人响应了。

按back后退到上图

下面分别点击send broadcast 和 send stickybroadcast按钮,随便点击几次,此时对应的receiver并没有注册,所以是不会有人响应这两条广播的。然后点击next activity,当打开新的activity后对应的receiver被注册,此时从日志中就能看出已经收到了send stickybroadcast发出的广播,但没有send broadcast发出的广播。这就是sendStickyBroadcast的特别之处,它将发出的广播保存起来,一旦发现有人注册这条广播,则立即能接收到。

日志打印为: action = com.android.action.sticky.broadcastand count = 4

从上面的日志信息可以看出sendStickyBroadcast只保留最后一条广播,并且一直保留下去,这样即使已经处理了这条广播但当再一次注册这条广播后依然可以收到它。

如果你只想处理一遍,removeStickyBroadcast方法可以帮你,处理完了后就将它删除吧。

 

相似的例子:

  1. package com.android.testbroadcast;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.os.Bundle;  
  7. import android.view.View;  
  8. import android.view.View.OnClickListener;  
  9. import android.widget.Button;  
  10.   
  11. public class MainActivity extends Activity {  
  12.     Button btnSendi;  
  13.     Button btnSends;  
  14.     Button btnStart;  
  15.     Context mContext;  
  16.     /** Called when the activity is first created. */  
  17.     @Override  
  18.     public void onCreate(Bundle savedInstanceState) {  
  19.         super.onCreate(savedInstanceState);  
  20.         setContentView(R.layout.main);  
  21.         btnSendi=(Button) findViewById(R.id.sendi);  
  22.         btnSends=(Button) findViewById(R.id.sends);  
  23.         btnStart=(Button) findViewById(R.id.start);  
  24.         mContext=getApplicationContext();  
  25.         btnSendi.setOnClickListener(new OnClickListener(){  
  26.   
  27.             @Override  
  28.             public void onClick(View v) {  
  29.                 // TODO Auto-generated method stub  
  30.                 Intent intent = new Intent();  
  31.                 intent.setAction("com.android.my.action");  
  32.                 intent.setFlags(1);  
  33.                 mContext.sendBroadcast(intent);  
  34.             }  
  35.               
  36.         });  
  37.           
  38.         btnStart.setOnClickListener(new OnClickListener(){  
  39.   
  40.             @Override  
  41.             public void onClick(View v) {  
  42.                 // TODO Auto-generated method stub  
  43.                 Intent intent = new Intent(MainActivity.this,ReceiverActivity.class);  
  44.                  
  45.                 startActivity(intent);  
  46.             }  
  47.               
  48.         });  
  49.           
  50.         btnSends.setOnClickListener(new OnClickListener(){  
  51.   
  52.             @Override  
  53.             public void onClick(View v) {  
  54.                 // TODO Auto-generated method stub  
  55.                 Intent intent = new Intent();  
  56.                 intent.setAction("com.android.my.action.sticky");  
  57.                 intent.setFlags(2);  
  58.                 mContext.sendStickyBroadcast(intent);  
  59.             }  
  60.               
  61.         });  
  62.     }  
  63. }  

 

Java代码  收藏代码
  1. package com.android.testbroadcast;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.BroadcastReceiver;  
  5. import android.content.Context;  
  6. import android.content.Intent;  
  7. import android.content.IntentFilter;  
  8. import android.net.wifi.WifiManager;  
  9. import android.os.Bundle;  
  10. import android.view.View;  
  11. import android.view.View.OnClickListener;  
  12. import android.widget.Button;  
  13.   
  14. public class ReceiverActivity extends Activity {  
  15.      private IntentFilter mIntentFilter;  
  16.       
  17.     /** Called when the activity is first created. */  
  18.     @Override  
  19.     public void onCreate(Bundle savedInstanceState) {  
  20.         super.onCreate(savedInstanceState);  
  21.         setContentView(R.layout.main);  
  22.         mIntentFilter = new IntentFilter();  
  23.         mIntentFilter.addAction("com.android.my.action");  
  24.         mIntentFilter.addAction("com.android.my.action.sticky");  
  25.   
  26.               
  27.     }  
  28.     private BroadcastReceiver mReceiver = new BroadcastReceiver() {  
  29.   
  30.         @Override  
  31.         public void onReceive(Context context, Intent intent) {  
  32.             final String action = intent.getAction();  
  33.             System.out.println("action"+action);  
  34.               
  35.         }  
  36.     };  
  37.       
  38.     @Override  
  39.     protected void onResume() {  
  40.         // TODO Auto-generated method stub  
  41.         super.onResume();  
  42.         registerReceiver(mReceiver, mIntentFilter);  
  43.     }  
  44.       
  45.     @Override  
  46.     protected void onPause() {  
  47.         // TODO Auto-generated method stub  
  48.         super.onPause();  
  49.         unregisterReceiver(mReceiver);  
  50.     }  
  51.       
  52.       
  53. }  



在MainActivity里面会有sendBroadcast和sendStickyBroacat.在ReceverActivity里面通 过BroadcastReceiver来接收这两个消息,在ReceiverActivity里是通过代码来注册Recevier而不是在 Manifest里面注册的。所以通过sendBroadcast中发出的intent在ReceverActivity不处于onResume状态是无 法接受到的,即使后面再次使其处于该状态也无法接受到。而sendStickyBroadcast发出的Intent当ReceverActivity重 新处于onResume状态之后就能重新接受到其Intent.这就是the Intent will be held to be re-broadcast to future receivers这句话的表现。就是说sendStickyBroadcast发出的最后一个Intent会被保留,下次当Recevier处于活跃的 时候,又会接受到它。