import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.wangdeqiang.www.chatwithrobot.R;
/**
* 本地广播的优势
* 1.明确的知道正在发送的广播不会离开我们的程序,因此不必担心机密数据泄露.
* 2.其他的程序无法将广播发送到我们程序的内部,因此不需要担心会有安全漏洞的隐患.
* 3.
*/
public class Main2Activity extends AppCompatActivity {
private IntentFilter intentFilter;
**private LocalReceiver localReceiver;
private LocalBroadcastManager localBroadcastManager;**
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
localBroadcastManager = LocalBroadcastManager.getInstance(this); //获取实例
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.com.wangdeqiang.www.chatwithrobot.Broadcast.LOCAL_BROADCAST");
localBroadcastManager.sendBroadcast(intent);//发送本地广播
}
});
intentFilter = new IntentFilter();
intentFilter.addAction("com.com.wangdeqiang.www.chatwithrobot.Broadcast.LOCAL_BROADCAST");
localReceiver = new LocalReceiver();
//注册本地广播接收器localBroadcastManager.registerReceiver(localReceiver,intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
localBroadcastManager.unregisterReceiver(localReceiver);
}
private class LocalReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Receive the local boradcast",Toast.LENGTH_SHORT).show();
}
}
}
运行界面如图所示