• ddmlib问题总结——同步获取设备信息


    通过IDevice.getProperty(String name)得到响应的设备属性。
    在实际的使用过程中发现,我的manufacturer总是获取不到,为null(获取代码如下),而剩下的属性都可以获取到,经过测试,如果将manufacturer放在下面,第一个属性总是获取不到,于是到方法定义处查看注释

    // 得到指定的设备属性        
    manufacturer = device.getProperty(IDevice.PROP_DEVICE_MANUFACTURER); // 这个属性总是无法获取,如果将它和model换一下位置,那么变成model为null model = device.getProperty(IDevice.PROP_DEVICE_MODEL); version = device.getProperty(IDevice.PROP_BUILD_VERSION); apiLevel = device.getProperty(IDevice.PROP_BUILD_API_LEVEL);

    观察IDevice.getProperty()的定义:

    /**
    * Convenience method that attempts to retrieve a property via
    * {@link #getSystemProperty(String)} with minimal wait time, and swallows exceptions.
    *
    * @param name the name of the value to return.
    * @return the value or <code>null</code> if the property value was not immediately available
    */
    @Nullable
    String getProperty(@NonNull String name);

    注释大意:利用getSystemProperty()方法在最短的等待时间内获得一个设备属性,如果在这个瞬间该属性是不可用的,则返回null。

    应该大致可以定位原因了:1.本方法为异步方法,2.默认等待时间过短

    再观察一下IDevice的子类Device的重写方法:

    Future<String> future = mPropFetcher.getProperty(name);return future.get(GET_PROP_TIMEOUT_MS, TimeUnit.MILLISECONDS);

    其中future.get(long timeout, TimeUtil unit)方法比较特殊:

    /**
    * Waits if necessary for at most the given time for the computation
    * to complete, and then retrieves its result, if available.
    *
    * @param timeout the maximum time to wait
    * @param unit the time unit of the timeout argument
    * @return the computed result
    * @throws CancellationException if the computation was cancelled
    * @throws ExecutionException if the computation threw an
    * exception
    * @throws InterruptedException if the current thread was interrupted
    * while waiting
    * @throws TimeoutException if the wait timed out
    */
    V get(long timeout, TimeUnit unit)
       throws InterruptedException, ExecutionException, TimeoutException;

    该方法将会等待timeout长度的时间,直到你需要的属性可用未知。

    根据我们上边定位出来的两个原因:

    1.本方法为异步方法,2.默认等待时间过短

    可以有两种解决方法:

    1.改为同步获取

    使用IDevice的getPropertySync(String name)方法来强制同步获取,不过在代码注释中该方法已经被放弃使用了,我没有试过这种方式。

    2.增加默认等待时间

    适用于可以修改代码的同学:

    private static final long GET_PROP_TIMEOUT_MS = 100;  // 从100改为1000
  • 相关阅读:
    【转】ubuntu 13.04 普通用户丢失sudo权限后的恢复办法
    #流水账# Mac上用Virtualbox安装//配置虚拟机Ubuntu
    #小知识# 网页内容居中的办法
    无法正常访问FTP服务(Windows 7 + VirtualBox + Ubuntu + vsftpd)
    【转】WordPress上传主题出错:无法创建目录
    判断是PC端还是移动端
    公告滚动
    vs code 汉化 自动保存 插件
    手机端的适配
    css 常见属性
  • 原文地址:https://www.cnblogs.com/shiyu404/p/7029153.html
Copyright © 2020-2023  润新知