zoukankan      html  css  js  c++  java
  • 使用本地广播

    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();
            }
        }
    }
    

    运行界面如图所示
    这里写图片描述

  • 相关阅读:
    poj 3616 Milking Time
    poj 3176 Cow Bowling
    poj 2229 Sumsets
    poj 2385 Apple Catching
    poj 3280 Cheapest Palindrome
    hdu 1530 Maximum Clique
    hdu 1102 Constructing Roads
    codeforces 592B The Monster and the Squirrel
    CDOJ 1221 Ancient Go
    hdu 1151 Air Raid(二分图最小路径覆盖)
  • 原文地址:https://www.cnblogs.com/CCCrunner/p/11782007.html
Copyright © 2011-2022 走看看