日期:2014-05-16  浏览次数:20571 次

sendBroadcast和sendStickyBroadcast的区别

我们平时最经常使用的是sendBroadcast,就是把一个Intent广播出去。今天我在看wifi的时候,还发现了sendStickyBroadcast。官方文档是这样写的:?


public abstract void sendStickyBroadcast (Intent intent)?

Since: API Level 1?
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 of registerReceiver(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.?
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.Context;
  4. import android.content.Intent;
  5. import android.os.Bundle;
  6. import android.view.View;
  7. import android.view.View.OnClickListener;
  8. import android.widget.Button;

  9. public class MainActivity extends Activity {
  10. ? ? ? ? Button btnSendi;
  11. ? ? ? ? Button btnSends;
  12. ? ? ? ? Button btnStart;
  13. ? ? ? ? Context mContext;
  14. ? ? /** Called when the activity is first created. */
  15. ? ? @Override
  16. ? ? public void onCreate(Bundle savedInstanceState) {
  17. ? ?? ???super.onCreate(savedInstanceState);
  18. ? ?? ???setContentView(R.layout.main);
  19. ? ?? ???btnSendi=(Button) findViewById(R.id.sendi);
  20. ? ?? ???btnSends=(Button) findViewById(R.id.sends);
  21. ? ?? ???btnStart=(Button) findViewById(R.id.start);
  22. ? ?? ???mContext=getApplicationContext();
  23. ? ?? ???btnSendi.setOnClickListener(new OnClickListener(){

  24. ? ? ? ? ? ? ? ? ? ? ? ? @Override
  25. ? ? ? ? ? ? ? ? ? ? ? ? public void onClick(View v) {
  26. ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? // TODO Auto-generated method stub
  27. ? ? ? ? ? ? ? ? ? ? ? ? ? ?