Skip to content

Commit

Permalink
本地广播使用
Browse files Browse the repository at this point in the history
  • Loading branch information
ningbaoqi committed Jul 19, 2018
1 parent 2fab4a1 commit 70c04ff
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
4 changes: 3 additions & 1 deletion README-local.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
### 本地广播使用简介
+ `LocalBroadcastReceiver`高效的原因主要是`它内部是通过Handler实现的`,它的`sendBroadcast()`方法含义并非和我们平时所用的一样,它的`sendBroadcast()`方法实际上是`通过Handler发送一个Message实现的`,既然是它内部是通过Handler来实现广播的发送的,那么相比于系统广播通过`Binder`实现那肯定是更高效的,别的应用内发送的广播也不会离开我们的应用:`LocalBroadcastReceiver`内部协作主要靠这两个`Map`集合,`mReceivers``mActions`当然还有一个`List`集合`mPendingBroadcasts`,这个主要是`存放待接收的广播对象`
+ `LocalBroadcastReceiver`高效的原因主要是`它内部是通过Handler实现的`,它的`sendBroadcast()`方法含义并非和我们平时所用的一样,它的`sendBroadcast()`方法实际上是`通过Handler发送一个Message实现的`,既然是它内部是通过Handler来实现广播的发送的,那么相比于系统广播通过`Binder`实现那肯定是更高效的,别的应用内发送的广播也不会离开我们的应用:`LocalBroadcastReceiver`内部协作主要靠这两个`Map`集合,`mReceivers``mActions`当然还有一个`List`集合`mPendingBroadcasts`,这个主要是`存放待接收的广播对象`
### 本地广播使用
[本地广播使用](https://github.com/ningbaoqi/BroadcastReceiver/blob/master/README-local.md)
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.shop.ningbaoqi.broadcastreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

public class LocalBroadcastReceiver extends AppCompatActivity {
private LocalBroadcastManager manager;
private LocalReceiver receiver;

/**
* 本地广播,只能在本应用内部进行传递,并且广播接收器只能接收来自本应用程序发出的广播,本地广播接收器不能进行静态注册,发送本地广播更加有效
*/
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = LocalBroadcastManager.getInstance(this);
IntentFilter filter = new IntentFilter();
filter.addAction("ningbaoqi");
receiver = new LocalReceiver();
manager.registerReceiver(receiver, filter);
Intent intent = new Intent();
intent.setAction("ningbaoqi");
manager.sendBroadcast(intent);
}

@Override
protected void onDestroy() {
super.onDestroy();
manager.unregisterReceiver(receiver);
}

class LocalReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("nbq", intent.getAction());
}
}
}

0 comments on commit 70c04ff

Please sign in to comment.