• Bundle传递数据,Handler更新UI


    Bundle主要用于传递数据;它保存的数据,是以key-value(键值对)的形式存在的。

    Bundle经常使用在Activity之间或者线程间传递数据,传递的数据可以是boolean、byte、int、long、float、double、string等基本类型或它们对应的数组,也可以是对象或对象数组。

    当Bundle传递的是对象或对象数组时,必须实现Serializable 或Parcelable接口。

    Bundle提供了各种常用类型的putXxx()/getXxx()方法,用于读写基本类型的数据。(各种方法可以查看API)

    在activity间传递信息

    Intent intent  = new Intent(mContext,DetailActivity.class);
    Bundle bundle = new Bundle();
    
    bundle.putCharSequence("newsId",newsId);           
    bundle.putString("sff", "value值");  //key-"sff",通过key得到value-"value值"(String型)  
    bundle.putInt("iff", 175);  //key-"iff",value-175  
    
    intent.putExtras(bundle); //通过intent将bundle传到另个Activity   
    startActivity(intent);

    接收数据

     //接收Intent发过来的数据
     Intent intent  = getIntent();
     Bundle bundle = intent.getExtras();
     String newsId = bundle.getString("newsId");

    线程间传递

    通过Handler将带有dundle数据的message放入消息队列,其他线程就可以从队列中得到数据

    Message message=new Message();//new一个Message对象 
    message.what = MESSAGE_WHAT_2;//给消息做标记 
    Bundle bundle = new Bundle(); //得到Bundle对象 
    bundle.putString("text1","消息传递参数的例子!"); //往Bundle中存放数据 
    bundle.putInt("text2",44); //往Bundle中put数据 
    message.setData(bundle);//mes利用Bundle传递数据 
    mHandler.sendMessage(message);//Handler将消息放入消息队列 

    读取数据
    这里用的是Handler的handleMessage(Message msg)方法处理数据

    String str1=msg.getData().getString("text1"); 
    int int1=msg.getData().getString("text2");

    转自:https://blog.csdn.net/yiranruyuan/article/details/78049219

  • 相关阅读:
    SpringBoot入门系列
    日志收集系统-多线程消息队列
    阿里云ecs 服务器配置
    MySQL 表分区详解MyiSam引擎和InnoDb 区别(实测)
    Redis 3.2 Linux 环境集群搭建与java操作
    Java
    多线程编程-工具篇-BlockingQueue
    java常见面试题及答案 11-20(JVM篇)
    28.function_score自定义相关度分数算法
    27.四种常见的相关度分数优化方法
  • 原文地址:https://www.cnblogs.com/xuqp/p/9817580.html
Copyright © 2020-2023  润新知