学习笔记 Android LocalBroadcastManager的使用

Posted 阿蛮家

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了学习笔记 Android LocalBroadcastManager的使用相关的知识,希望对你有一定的参考价值。

LocalBroadcastManager简介

LocalBroadcastManager是Google官方androidSupport包提供的一个工具,用来管理广播的类。只能用来在同一个应用的不同组件之间发送广播,进行数据交互。和普通的全局广播相比较,LocalBroadcastManager的安全性相对较高。


布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="开始广播"
        android:id="@+id/btnSendBroadcast" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="停止广播"
        android:id="@+id/btnStopBroadcast" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="广播文字"
        android:id="@+id/txtBroadcast" />
</LinearLayout>

activity文件

package com.licheng.android.weextest;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.ServiceCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class LocalBroadcastTestActivity extends AppCompatActivity implements View.OnClickListener

    Button btnSendBroadcast, btnStopBroadcast;
    TextView txtBroadcast;

    static final String ACTION_START = "com.licheng.android.weextest.START";
    static final String ACTION_UPDATE = "com.licheng.android.weextest.UPDATE";
    static final String ACTION_STOP = "com.licheng.android.weextest.STOP";

    LocalBroadcastManager localBroadcastManager;
    BroadcastReceiver broadcastReceiver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        System.out.println("LocalBroadcastTestActivity onCreate");
        setContentView(R.layout.broadcast_layout);

        btnSendBroadcast = (Button) findViewById(R.id.btnSendBroadcast);
        btnStopBroadcast = (Button) findViewById(R.id.btnStopBroadcast);
        txtBroadcast = (TextView) findViewById(R.id.txtBroadcast);
        btnSendBroadcast.setOnClickListener(this);
        btnStopBroadcast.setOnClickListener(this);

        localBroadcastManager = LocalBroadcastManager.getInstance(this);


        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_START);
        filter.addAction(ACTION_UPDATE);
        filter.addAction(ACTION_STOP);

        broadcastReceiver = new BroadcastReceiver() 
            @Override
            public void onReceive(Context context, Intent intent) 

                System.out.println("LocalBroadcast onReceive");

                if(intent.getAction().equals(ACTION_START))
                    txtBroadcast.setText("START");
                else if(intent.getAction().equals(ACTION_UPDATE))
                    txtBroadcast.setText("UPDATE " + intent.getIntExtra("value", 0));
                 else if (intent.getAction().equals(ACTION_STOP)) 
                    txtBroadcast.setText("STOP");
                
            
        ;

        localBroadcastManager.registerReceiver(broadcastReceiver, filter);


    

    @Override
    public void onClick(View view) 
        switch (view.getId())
            case R.id.btnSendBroadcast:
                System.out.println("btnSendBroadcast click");
                startService(new Intent(LocalBroadcastTestActivity.this, LocalBroadcastService.class));
                break;
            case R.id.btnStopBroadcast:
                System.out.println("btnStopBroadcast click");
                stopService(new Intent(LocalBroadcastTestActivity.this, LocalBroadcastService.class));
                break;
            default:
                break;
        
    


    public static class LocalBroadcastService extends Service

        LocalBroadcastManager localBroadcastManager;
        int count = 0;
        static final int MSG_UPDATE = 1;

        Handler handler = new Handler()
            @Override
            public void handleMessage(Message msg) 
                switch (msg.what)
                    case MSG_UPDATE:
                        count ++;

                        Intent intent = new Intent(ACTION_UPDATE);
                        intent.putExtra("value", count);
                        localBroadcastManager.sendBroadcast(intent);
                        Message nmsg = handler.obtainMessage(MSG_UPDATE);
                        handler.sendMessageDelayed(nmsg, 1000);
                        break;
                    default:
                        super.handleMessage(msg);
                        break;
                
            
        ;

        @Override
        public void onCreate() 
            super.onCreate();
            System.out.println("LocalBroadcast onCreate");
            localBroadcastManager = LocalBroadcastManager.getInstance(this);
        

        @Override
        public void onDestroy() 
            super.onDestroy();
            System.out.println("LocalBroadcast onDestroy");
            localBroadcastManager.sendBroadcast(new Intent(ACTION_STOP));
            handler.removeMessages(MSG_UPDATE);
        

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) 
            System.out.println("LocalBroadcast onStartCommand");
            localBroadcastManager.sendBroadcast(new Intent(ACTION_START));

            handler.removeMessages(MSG_UPDATE);
            Message msg = handler.obtainMessage(MSG_UPDATE);
            handler.sendMessageDelayed(msg, 1000);
            return ServiceCompat.START_STICKY;
        

        @Nullable
        @Override
        public IBinder onBind(Intent intent) 
            System.out.println("LocalBroadcast onBind");
            return null;
        
    


    @Override
    protected void onDestroy() 
        System.out.println("LocalBroadcastTestActivity onCreate");
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(broadcastReceiver);
    


上面的例子通过service发送广播,service需要在mainfest中注册

<service android:name=".LocalBroadcastTestActivity$LocalBroadcastService"></service>

运行效果



参考: https://my.oschina.net/ososchina/blog/340339  

以上是关于学习笔记 Android LocalBroadcastManager的使用的主要内容,如果未能解决你的问题,请参考以下文章

android学习笔记

Android学习笔记(34):Android菜单

Android学习笔记

Android学习笔记之Service

Android学习笔记-----------布局

Android学习笔记:Android Service组件深入解析