LocalBroadcastManager基本用法
LocalBroadcastManager发送的广播只作用于本应用,如果不涉及到其他应用,但用到了广播的话那么用LocalBroadcastManager取代BroadcastReceiver将是明智之选,LocalBroadcastManager google官方给的解释为
Helper to register for and send broadcasts of Intents to local objects within your process. This has a number of advantages over sending global broadcasts with sendBroadcast(Intent):
- You know that the data you are broadcasting won’t leave your app, so don’t need to worry about leaking private data.
- It is not possible for other applications to send these broadcasts to your app, so you don’t need to worry about having security holes they can exploit.
- It is more efficient than sending a global broadcast through the system.
注册并发送只能在本应用中接受的广播,相比全局广播有很大优势
- 你发送的数据只能在本应用中接收,所以不用担心数据泄露问题
- 其他应用的广播不可能接收,不用担心恶意广播
- 比全局广播更加高效
简单Demo运行效果
代码
MainActivity
package com.example.localbroadcastmanager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private BroadcastReceiver localReceiver;
private final String ACTION = "com.qfxl.receiver";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
localReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String toast = intent.getStringExtra("message");
if(null != toast){
Toast.makeText(MainActivity.this, toast, Toast.LENGTH_SHORT).show();
}
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(localReceiver, new IntentFilter(ACTION));
}
public void toSubPage(View view) {
startActivity(new Intent(this,SubActivity.class));
}
@Override
protected void onDestroy() {
super.onDestroy();
if (localReceiver != null) {
LocalBroadcastManager.getInstance(this).unregisterReceiver(localReceiver);
}
}
}
SubActivity
package com.example.localbroadcastmanager;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class SubActivity extends AppCompatActivity {
private final String ACTION = "com.qfxl.receiver";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
}
public void sendBroadcast(View view){
Intent mIntent = new Intent(ACTION);
mIntent.putExtra("message","this message is from subActivity");
LocalBroadcastManager.getInstance(this).sendBroadcast(mIntent);
}
}