本地广播 localBroadcastManager Android

使用localBroadcastManager发出的广播只能在本应用程序的内部进行传递。

App应用内广播可理解为一种局部广播,广播的发送者和接收者都同属于一个App。

相比于全局广播(普通广播),App应用内广播优势体现在:安全性高 & 效率高

步骤:

1.注册广播(onResume方法内

2.发送广播

3.收到广播

4.销毁广播(onPause方法内

 

 

package com.fengbang.localbroadcasttest;

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.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

private IntentFilter intentFilter;
private LocalReceiver localReceiver;
private LocalBroadcastManager localBroadcastManager;


private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

localBroadcastManager = LocalBroadcastManager.getInstance(this);

Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent("com.fengbang.localbroadcasttest.LOCAL_BROADCAST");
localBroadcastManager.sendBroadcast(intent);//发送广播
}
});

}

@Override
protected void onResume() {
super.onResume();

intentFilter = new IntentFilter();
intentFilter.addAction("com.fengbang.localbroadcasttest.LOCAL_BROADCAST");
localReceiver = new LocalReceiver();
localBroadcastManager.registerReceiver(localReceiver,intentFilter);//注册广播
}

@Override
protected void onPause() {
super.onPause();

localBroadcastManager.unregisterReceiver(localReceiver);//销毁广播
}

class LocalReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive: 收到广播");
}
}
}
 

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyfffs.html