zoukankan      html  css  js  c++  java
  • Android中的广播机制

          有的时候,在一个Activity之外要对这个Activity的UI进行更新,例如,当外界的参数变化引起这个Activity相应的变化,这种情况下,我们可以采用广播机制:在变量发生变化的地方,向需要接收的Activity或其他Android应用组件发送一个广播消息。下面有个Demo,展示了这种消息机制:

           首先启动的是Activity中注册一个广播:

    //广播监听类
        class MyReceiver extends BroadcastReceiver{
     
            @Override
            public void onReceive(Context context, Intent intent) {
                int color = intent.getExtras().getInt("color");
                Log.v("tag", "receive color: " + color);
                drawColor(color);
            }
            
        }
        
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            receiver = new MyReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction("ChangeColor");
            registerReceiver(receiver, filter);
            btnStartB = (Button) findViewById(R.id.btnStartB);
            textView = (TextView) findViewById(R.id.textView);
            
            btnStartB.setOnClickListener(new OnClickListener() {
     
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(FirstActivity.this,
                            SecondActivity.class);
                    startActivity(intent);
                }
            });
        }
     
        
        
        @Override
        protected void onDestroy() {
            super.onDestroy();
            unregisterReceiver(receiver);   //取消注册
        }
     
     
     
        public void drawColor(int c) {
            int color = c;
            Log.v("tag", "receive: " + color);
            switch (color) {
            case 0:
                textView.setBackgroundColor(Color.RED);
                break;
            case 1:
                textView.setBackgroundColor(Color.YELLOW);
                break;
            case 2:
                textView.setBackgroundColor(Color.BLUE);
                break;
            }
            textView.invalidate();   //更新UI
        }

        在第二个Activity中,有三个按钮,代表三种不同的颜色值,每次点击一个按钮,则发出广播,通知ActivityA进行更新UI。

    发送广播的代码如下:

            Intent intent = new Intent("ChangeColor");
            intent.putExtra("color", c);
            sendBroadcast(intent);

    Demo的效果如下:

    (1)

    QQ截图20111013161820

    (2)

     QQ截图20111013162133    

    (3)

    QQ截图20111013162049

  • 相关阅读:
    Cocos2d-x 3.0截屏功能集成
    游戏嵌入Webview网页
    Cocos2dx进阶学习之屏幕适配
    Android如何实现文件下载并自动安装apk包!!!
    LINQ Select变量定义 Expression<Func<TSource, TResult>>
    StringComparison枚举
    .net core DBFirst 生成Model表结构
    .net core反向工程Model生成 配置机密
    axios下载文件.net Core
    EFCore Database-first深入研究
  • 原文地址:https://www.cnblogs.com/yangzhenyu/p/2210438.html
Copyright © 2011-2022 走看看