Android应用开发之(小技巧之LocalBroadcastManager)

Android v4 兼容包提供android.support.v4.content.LocalBroadcastManager工具类,帮助大家在自己的进程内进行局部广播发送与注册,使用它比直接通过sendBroadcast(Intent)发送系统全局广播有以下几点好处。

1    因广播数据在本应用范围内传播,你不用担心隐私数据泄露的问题。

2    不用担心别的应用伪造广播,造成安全隐患。

3    相比在系统内发送全局广播,它更高效。

使用方法 通过getInstance(Contextcontext)获取实例,demo如下:

/**

* Demonstrates the use of a LocalBroadcastManager to easily communicate

* data from a service to any other interested code.

*/

public class LocalServiceBroadcaster extends Activity {

static final String ACTION_STARTED = "com.example.android.supportv4.STARTED";

static final String ACTION_UPDATE = "com.example.android.supportv4.UPDATE";

static final String ACTION_STOPPED = "com.example.android.supportv4.STOPPED";

LocalBroadcastManager mLocalBroadcastManager;

BroadcastReceiver mReceiver;

@Override

protected void onCreate(Bundle savedInstanceState) {

   super.onCreate(savedInstanceState);

   setContentView(R.layout.local_service_broadcaster);

   // This is where we print the data we get back.

   final TextView callbackData = (TextView)findViewById(R.id.callback);

   // Put in some initial text.

   callbackData.setText("No broadcast received yet");

   // We use this to send broadcasts within our local process.

   mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);

   // We are going to watch for interesting local broadcasts.

   IntentFilter filter = new IntentFilter();

   filter.addAction(ACTION_STARTED);

   filter.addAction(ACTION_UPDATE);

   filter.addAction(ACTION_STOPPED);

   mReceiver = new BroadcastReceiver() {

       @Override

       public void onReceive(Context context, Intent intent) {

           if (intent.getAction().equals(ACTION_STARTED)) {

               callbackData.setText("STARTED");

           } else if (intent.getAction().equals(ACTION_UPDATE)) {

               callbackData.setText("Got update: " + intent.getIntExtra("value", 0));

           } else if (intent.getAction().equals(ACTION_STOPPED)) {

               callbackData.setText("STOPPED");

           }

       }

   };

   mLocalBroadcastManager.registerReceiver(mReceiver, filter);

   // Watch for button clicks.

   Button button = (Button)findViewById(R.id.start);

   button.setOnClickListener(mStartListener);

   button = (Button)findViewById(R.id.stop);

   button.setOnClickListener(mStopListener);

}

@Override

protected void onDestroy() {

   super.onDestroy();

   mLocalBroadcastManager.unregisterReceiver(mReceiver);

}

private OnClickListener mStartListener = new OnClickListener() {

   public void onClick(View v) {

       startService(new Intent(LocalServiceBroadcaster.this, LocalService.class));

   }

};

private OnClickListener mStopListener = new OnClickListener() {

   public void onClick(View v) {

       stopService(new Intent(LocalServiceBroadcaster.this, LocalService.class));

   }

};

public static class LocalService extends Service {

   LocalBroadcastManager mLocalBroadcastManager;

   int mCurUpdate;

   static final int MSG_UPDATE = 1;

   Handler mHandler = new Handler() {

       @Override

       public void handleMessage(Message msg) {

           switch (msg.what) {

               case MSG_UPDATE: {

                   mCurUpdate++;

                   Intent intent = new Intent(ACTION_UPDATE);

                   intent.putExtra("value", mCurUpdate);

                   mLocalBroadcastManager.sendBroadcast(intent);

                   Message nmsg = mHandler.obtainMessage(MSG_UPDATE);

                   mHandler.sendMessageDelayed(nmsg, 1000);

               } break;

               default:

                   super.handleMessage(msg);

           }

       }

   };

   @Override

   public void onCreate() {

       super.onCreate();

       mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);

   }

   public int onStartCommand(Intent intent, int flags, int startId) {

       // Tell any local interested parties about the start.

       mLocalBroadcastManager.sendBroadcast(new Intent(ACTION_STARTED));

       // Prepare to do update reports.

       mHandler.removeMessages(MSG_UPDATE);

       Message msg = mHandler.obtainMessage(MSG_UPDATE);

       mHandler.sendMessageDelayed(msg, 1000);

       return ServiceCompat.START_STICKY;

   }

   @Override

   public void onDestroy() {

       super.onDestroy();

       // Tell any local interested parties about the stop.

       mLocalBroadcastManager.sendBroadcast(new Intent(ACTION_STOPPED));

       // Stop doing updates.

       mHandler.removeMessages(MSG_UPDATE);

   }

   @Override

   public IBinder onBind(Intent intent) {

       return null;

   }

}

}