zoukankan      html  css  js  c++  java
  • Service和Activity交互之广播方式

    一.使用场景
    如果要通知多个Activity,广播较为适合.但广播较为耗费性能.

    二.Broadcast更新Activity中的UI

    1.新建一个接口OnUpdateUI,用于回调更新UI

    public interface OnUpdateUI {
        void updateUI(String i);
    }

    2.BroadcastReceiver代码

    public class MyBroadcast extends BroadcastReceiver {
    
        OnUpdateUI onUpdateUI;
        @Override
        public void onReceive(Context context, Intent intent) {
            String progress = intent.getStringExtra("progress");
            onUpdateUI.updateUI(progress);
        }
    
        public void SetOnUpdateUI(OnUpdateUI onUpdateUI){
            this.onUpdateUI = onUpdateUI;
        }
    
    }

    3.Activity中代码:

    public class MainActivity extends Activity {
    
        public static final String FLAG = "UPDATE";
        MyBroadcast myBroadcast;
        TextView tip;
        Intent intent;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            tip = (TextView)findViewById(R.id.tip);
    
            myBroadcast = new MyBroadcast();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(FLAG);
            registerReceiver(myBroadcast, intentFilter);
    
            intent = new Intent(this, MyService.class);
            
        // 更新UI
            myBroadcast.SetOnUpdateUI(new OnUpdateUI() {
                @Override
                public void updateUI(String i) {
                    tip.setText(i);
                }
            });
        }
    
        protected void myClick(View v){
        // 发送广播
            if( v.getId() == R.id.btn ){
                Intent intent = new Intent();
                intent.setAction(FLAG);
                intent.putExtra("progress", System.currentTimeMillis()+"");
                sendBroadcast(intent);
            }
    
        // 启动服务
            if (v.getId() == R.id.btn2){
                startService(intent);
            }
        }
    
        @Override
        protected void onDestroy() {
            unregisterReceiver(myBroadcast);
            stopService(intent);
            super.onDestroy();
        }
    }

    三.Service发送广播,广播更新Activity中UI

    Service发送广播

    Intent it = new Intent();
    it.setAction(MainActivity.FLAG);
    it.putExtra("progress", i+"");
    sendBroadcast(it);
  • 相关阅读:
    query and join operation after sharding
    Windows Phone中的几种集合控件
    什么是SOPA SOPA的危害
    自动刷新人人网API session_key方法
    Windows Phone XNA创建简单局域网游戏
    static 修饰MySqlConnection引发的异常
    $Dsu$ $on$ $Tree$ 复习
    $Noip$前的小总结哦
    $NOIP2018$ 暴踩全场计划实施方案
    $NOIP2018$ 爆踩全场记
  • 原文地址:https://www.cnblogs.com/itfenqing/p/6752105.html
Copyright © 2011-2022 走看看