• 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);
  • 相关阅读:
    CLR 对比 JVM
    unity drawcall测试
    UGUI 分页渐变居中效果
    几个ADB常用命令
    jQuery分步步骤
    jquery toast插件
    jQuery数字滚动(模拟网站人气、访问量递增)原创
    jQuery实用工具集
    scrollReveal.js – 页面滚动显示动画JS
    jquery轻量级数字动画插件jquery.countup.js
  • 原文地址:https://www.cnblogs.com/itfenqing/p/6752105.html
Copyright © 2020-2023  润新知