为了简单解决广播的安全性问题,Android引入了一套本地广播机制,使用这个机制发出的广播只能在程序的内部进行传递,只能接受来自本应用程序发出的广播。否则当我们发送一些携带关键数据的广播可能被截获,一些恶意程序也可能向我们的广播接收器中发送各种垃圾广播。
用法如下:(主要就是使用LocalBroadcastManager来对广播进行管理,并提供注册广播和发送广播的方法)。
package com.example.xch.localbroadcast;
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.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private IntentFilter intentFilter;
private Button sendBroadcast;
private LocalReceiver localReceiver;
private LocalBroadcastManager localBroadcastManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
localBroadcastManager=LocalBroadcastManager.getInstance(this);//通过getInstance()得到LocalBroadcastManager的实例
sendBroadcast=(Button) findViewById(R.id.sendBroadcast);
sendBroadcast.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//发送本地广播
Intent intent=new Intent("com.example.LOCAL_BROADCAST");
localBroadcastManager.sendBroadcast(intent);
}
});
//注册本地广播监听器
intentFilter=new IntentFilter();
intentFilter.addAction("com.example.LOCAL_BROADCAST");
localReceiver=new LocalReceiver();
localBroadcastManager.registerReceiver(localReceiver,intentFilter);
}
class LocalReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"接受到本地广播",Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
localBroadcastManager.unregisterReceiver(localReceiver);//关闭广播
}
}