首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > 其他数据库 >

sendBroadcast跟sendStickyBroadcast的区别

2012-08-13 
sendBroadcast和sendStickyBroadcast的区别You must hold the BROADCAST_STICKY permission in order to u

sendBroadcast和sendStickyBroadcast的区别

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

intent The Intent to broadcast; all receivers matching this Intent will receive the broadcast, and the Intent will be held to be re-broadcast to future receivers.?

光从字面的意思是很难理解的。只有你写例子才会明白的。
Java代码
  1. package com.android.testbroadcast;

  2. import android.app.Activity;
  3. import android.content.BroadcastReceiver;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.content.IntentFilter;
  7. import android.net.wifi.WifiManager;
  8. import android.os.Bundle;
  9. import android.view.View;
  10. import android.view.View.OnClickListener;
  11. import android.widget.Button;

  12. public class ReceiverActivity extends Activity {
  13. ? ? ? ???private IntentFilter mIntentFilter;
  14. ? ? ? ??
  15. ? ? /** Called when the activity is first created. */
  16. ? ? @Override
  17. ? ? public void onCreate(Bundle savedInstanceState) {
  18. ? ?? ???super.onCreate(savedInstanceState);
  19. ? ?? ???setContentView(R.layout.main);
  20. ? ?? ???mIntentFilter = new IntentFilter();
  21. ? ?? ???mIntentFilter.addAction("com.android.my.action");
  22. ? ?? ???mIntentFilter.addAction("com.android.my.action.sticky");

  23. ? ? ? ? ? ? ? ? ? ? ? ??
  24. ? ? }
  25. ? ? private BroadcastReceiver mReceiver = new BroadcastReceiver() {

  26. ? ?? ???@Override
  27. ? ?? ???public void onReceive(Context context, Intent intent) {
  28. ? ?? ?? ?? ?final String action = intent.getAction();
  29. ? ?? ?? ?? ?System.out.println("action"+action);
  30. ? ?? ?? ?? ?
  31. ? ?? ???}
  32. ? ? };
  33. ? ??
  34. ? ? @Override
  35. ? ? protected void onResume() {
  36. ? ? ? ? ? ? // TODO Auto-generated method stub
  37. ? ? ? ? ? ? super.onResume();
  38. ? ? ? ? ? ? registerReceiver(mReceiver, mIntentFilter);
  39. ? ? }
  40. ? ??
  41. ? ? @Override
  42. ? ? protected void onPause() {
  43. ? ? ? ? ? ? // TODO Auto-generated method stub
  44. ? ? ? ? ? ? super.onPause();
  45. ? ? ? ? ? ? unregisterReceiver(mReceiver);
  46. ? ? }
  47. ? ??
  48. ? ??
  49. }
复制代码在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处于活跃的时候,又会接受到它。