使用本地广播 LocalBroadcastReceiver

使用全局广播可以被其他任何应用程序接收到,并且我们也可以接受来自于任何应用程序的广播,这样就很容易引起安全性问题。

发出本地广播,只能够在应用程序内部进行传递,并且广播接收器也只能接受来自本应用程序发出的广播。

本地广播比起发送全局广播会更加高效。


MainActivity.java:

package eason.example.com.localbroadcastdemo;

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;

public class MainActivity extends AppCompatActivity {

    private IntentFilter intentFilter=null;
    private LocalBroadcastReceiver receiver = null;
    private LocalBroadcastManager manager = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
	//获得LocalBroadcastManager实例
        manager = LocalBroadcastManager.getInstance(this);

        intentFilter = new IntentFilter();
        receiver = new LocalBroadcastReceiver();
        intentFilter.addAction("eason.example.com.localbroadcast.LOCAL_BROADCAST");
        manager.registerReceiver(receiver,intentFilter);//注册本地广播监听


        Button button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("eason.example.com.localbroadcast.LOCAL_BROADCAST");
                manager.sendBroadcast(intent);//发送本地广播
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        manager.unregisterReceiver(receiver);
    }
}
 
  
LocalBroadcastReceiver.java:
 
  
 
  
package eason.example.com.localbroadcastdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class LocalBroadcastReceiver extends BroadcastReceiver {
    public LocalBroadcastReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"LocalBroadcast received",Toast.LENGTH_SHORT).show();
    }
}

 
  


你可能感兴趣的:(ANDROID)