zoukankan      html  css  js  c++  java
  • Android自动化预备 (上)

    一.学习Android自动化需要哪些能力,否则后续学习起来会吃力

    1. 在测试行业带过一年以上(才有测试思想,测试思维的方向,一些学习中专业的词语才可以理解)

    2. 独立编写Java或者C++等项目一年以上(对脚本,对源码的理解,对KPI的理解)

    3. 熟练掌握具备业界开源自动化的工具并用在工作中(对开源的了解,如monkey,monkeyrunner(google自家做的),robotium(开源的,基于控件的自动化框架),UiAutomator(2013年,4.1以上的自动化框架))(才能直接进入代码学习,理解)UiAutomator支持4.1

    4. 用python的脚本语言的了解

    5. 会简单的Linux命令(底层包装在Linux中,进程方面的命令,adb shell中的指令),会android简单的开发,会Eclipse的开发

    二.面试中通常会被问道自动化相关方面的经验与基础

    BAT是:百度,阿里,腾讯的简称,经常的面试题:进程处理,app自动化,批处理调用脚本,监控进程的方法,线程阻塞的处理

    如:腾讯笔试题目:

    1.如何测试分布式ATM机?这个是针对一些大系统的题目,集群部署

    2.使用一个数组实现三个堆栈,要求有效得使用数组的存储空间,可以使用其他数据结构.涉及到一个测试人员对整个系统的了

        解,包括前端的负载均衡到主备应用等

    3.编写一个脚本,统计log文件中首个单词出现的次数,如:error:xxx/warning:xxx

    阿里巴巴2面的部分面试题:

    1.robotium源码架构实现

    2.robotium的工具怎么根据id找到脚本id(脚本id和架构映射原理)?

    3.mongkeyrunner和Uiautomator原理

    4.怎么做电量测试(如何做到app进程级别)

    5.影响手机电量因素列举一下

    6.稳定性和压力怎么做?

    7.robotium webview怎么实现

    8.怎么让系统不休眠:1.通过powermanager来精细控制,具体函数请指出2.在view中设置PLAG_KEEP_SCREEN_ON

    百度1面题目:

    1.我测试他们客户端,日文输入法我们不认识日文,怎么用自动化解决

    2.不用变量交换两个数

    3.调脚本怎么并行和串行调bat批处理

    4.怎么解决控件和点触实现屏自动化

    5.用户装了百度客户端,你怎么实现自动化?

    6.我们自动化要验证功能准确性还有性能,UI界面.一个自动化脚本验证多个,难道一个自动化只验证一条用例?

    7.怎么实现监控内存,在esliose显示pss是什么意思?

    8.ANS出现怎么解决?

    9.进程和线程,handler 和runnable 还有广播和服务

    10.robotium和mongkeyrunner的区别

    11.Radiobox 和checkbox自动化脚本怎能么复用(考的是正交法)

    12.GC原理

    13.android性能自动化怎么做

    14.电量对比测试

    15.android安全自动化怎么做

    16.有个客户装了百度客户端,怎么规划测试版本自动化

    17.UI线程阻塞,怎么复现查log

    三.业界自动化框架:

    1.基于坐标:mongkeyrunner,北京播思自研工具

    2.基于随机流的单元测试:CTS,monkey(压力测试)

    3.基于元素查找图形对比:seetest(收费),I-test     seetest:http://experitest.com

    4.腾讯:bita.qq.com平台(登录后可以进行一些定制或者压力,试用测试等),GT.tencent.com(测试游戏,帧率,解码率,需要手机root权限)

    5.百度云,itestin:itestin.cn(手游测试),阿里巴巴TMTS

    6.基于控件信息:Robutium+Junit4框架(基于控件,app),东舟Smart-Robot,美国风河公司的:wind test management

    7.NativeDriver和Selenium(被UiAutomator取代),比较新的技术

    ADB  (Android Debug Bridge调试桥接)

    adb devices:查看连接的设备

    1.是一个客户端,是一个服务器(运行后台,端口:TCP port:5037[如果adb不能启用时可以检查一下端口是否被占用]),还是一个守护进程,能够使的运行的实例运行在后台

      能在SDK中的platform-tools中找到:adb.exe(用该路径配置环境变量:path下添加到最后即可,用;号隔开)

    如:D:\SDK\sdk\platform-tools

    环境配置:

    http://hi.baidu.com/szy123618/item/48be8134cdfcd5c3382ffaa1

    2.基本命令:

      adb install <apkpath>:安装程序

    adb push <PC path> < /data/local/tmp>:从PC拷贝文件到手机 adb push 文件路径 /data/local/tmp

    adb pull:从手机拷贝文件到PC

    kill -server:要进入adb shell (显示$为未root,显示#为有root权限)

    在android 4.4以上支持adb shell screenrecord <save path>

    如:adb shell screenrecord /sdcard/demo.mp4

    2.AndroidDebugBridge 源码:

    debug内部类:

    Path:SDK/tools/lib/ddmslib.jar      Android DebugBridge 源码位置

    问:如何判定device设备是否连接

    问题参考:http://stackoverflow.com/questions/17381324/how-to-tell-if-android-device-detected-by-adb

    解答中涉及AndroidDebugBridge的类,在google中搜索AndroidDebugBridge如下:

    http://code.google.com/p/android-screen-monitor/source/browse/trunk/java/AndroidScreenMonitor/src/com/android/ddmlib/AndroidDebugBridge.java?r=16

    起源码如下:

    其中:

    publicstaticAndroidDebugBridge createBridge(String osLocation,boolean forceNewBridge){
            synchronized(sLock)

    不论是否促在ADB连接,都会重新再启动一个adb连接

    publicstaticAndroidDebugBridge createBridge(){
            synchronized(sLock)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    727
    728
    729
    730
    731
    732
    733
    734
    735
    736
    737
    738
    739
    740
    741
    742
    743
    744
    745
    746
    747
    748
    749
    750
    751
    752
    753
    754
    755
    756
    757
    758
    759
    760
    761
    762
    763
    764
    765
    766
    767
    768
    769
    770
    771
    772
    773
    774
    775
    776
    777
    778
    779
    780
    781
    782
    783
    784
    785
    786
    787
    788
    789
    790
    791
    792
    793
    794
    795
    796
    797
    798
    799
    800
    801
    802
    803
    804
    805
    806
    807
    808
    809
    810
    811
    812
    813
    814
    815
    816
    817
    818
    819
    820
    821
    822
    823
    824
    825
    826
    827
    828
    829
    830
    831
    832
    833
    834
    835
    836
    837
    838
    839
    840
    841
    842
    843
    844
    845
    846
    847
    848
    849
    850
    851
    852
    853
    854
    855
    856
    857
    858
    859
    860
    861
    862
    863
    864
    865
    866
    867
    868
    869
    870
    871
    872
    873
    874
    875
    876
    877
    878
    879
    880
    881
    882
    883
    884
    885
    886
    887
    888
    889
    890
    891
    892
    893
    894
    895
    896
    897
    898
    899
    900
    901
    902
    903
    904
    905
    906
    907
    908
    909
    910
    911
    912
    913
    914
    915
    916
    917
    918
    919
    920
    921
    922
    923
    924
    925
    926
    927
    928
    929
    930
    931
    932
    933
    934
    935
    936
    937
    938
    939
    940
    941
    942
    943
    944
    945
    946
    947
    948
    949
    950
    951
    952
    953
    954
    955
    956
    957
    958
    959
    960
    961
    962
    963
    964
    965
    966
    967
    968
    969
    970
    971
    972
    973
    974
    975
    976
    977
    978
    979
    980
    981
    982
    983
    984
    985
    986
    987
    988
    989
    990
    991
    992
    993
    994
    995
    996
    997
    998
    999
    1000
    1001
    1002
    1003
    1004
    1005
    1006
    1007
    1008
    1009
    1010
    1011
    1012
    1013
    1014
    1015
    1016
    1017
    1018
    1019
    1020
    1021
    1022
    1023
    1024
    1025
    1026
    1027
    1028
    1029
    1030
    1031
    1032
    1033
    1034
    1035
    1036
    1037
    1038
    1039
    1040
    1041
    1042
    1043
    1044
    1045
    1046
    1047
    1048
    1049
    1050
    1051
    1052
     
     
    /*
     * Copyright (C) 2007 The Android Open Source Project
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *      http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
     
    package com.android.ddmlib;
     
    import com.android.ddmlib.Log.LogLevel;
     
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.lang.Thread.State;
    import java.net.InetAddress;
    import java.net.InetSocketAddress;
    import java.net.UnknownHostException;
    import java.security.InvalidParameterException;
    import java.util.ArrayList;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
     
    /**
     * A connection to the host-side android debug bridge (adb)
     * <p/>This is the central point to communicate with any devices, emulators, or the applications
     * running on them.
     * <p/><b>{@link #init(boolean)} must be called before anything is done.</b>
     */
    publicfinalclassAndroidDebugBridge{
     
        /*
         * Minimum and maximum version of adb supported. This correspond to
         * ADB_SERVER_VERSION found in //device/tools/adb/adb.h
         */
     
      privatefinalstaticint ADB_VERSION_MICRO_MIN =20;
        privatefinalstaticint ADB_VERSION_MICRO_MAX =-1;
     
        privatefinalstaticPattern sAdbVersion =Pattern.compile(
                "^.*(\\d+)\\.(\\d+)\\.(\\d+)$");//$NON-NLS-1$
     
        privatefinalstaticString ADB ="adb";//$NON-NLS-1$
        privatefinalstaticString DDMS ="ddms";//$NON-NLS-1$
     
        // Where to find the ADB bridge.
        finalstaticString ADB_HOST ="127.0.0.1";//$NON-NLS-1$
        finalstaticint ADB_PORT =5037;
     
        staticInetAddress sHostAddr;
        staticInetSocketAddress sSocketAddr;
     
        static{
            // built-in local address/port for ADB.
            try{
                sHostAddr =InetAddress.getByName(ADB_HOST);
                sSocketAddr =newInetSocketAddress(sHostAddr, ADB_PORT);
            }catch(UnknownHostException e){
     
            }
        }
     
        privatestaticAndroidDebugBridge sThis;
        privatestaticboolean sClientSupport;
     
        /** Full path to adb. */
        privateString mAdbOsLocation =null;
     
        privateboolean mVersionCheck;
     
        privateboolean mStarted =false;
     
        privateDeviceMonitor mDeviceMonitor;
     
        privatefinalstaticArrayList<IDebugBridgeChangeListener> sBridgeListeners =
            newArrayList<IDebugBridgeChangeListener>();
        privatefinalstaticArrayList<IDeviceChangeListener> sDeviceListeners =
            newArrayList<IDeviceChangeListener>();
        privatefinalstaticArrayList<IClientChangeListener> sClientListeners =
            newArrayList<IClientChangeListener>();
     
        // lock object for synchronization
        privatestaticfinalObject sLock = sBridgeListeners;
     
        /**
         * Classes which implement this interface provide a method that deals
         * with {@link AndroidDebugBridge} changes.
         */
        public interface IDebugBridgeChangeListener{
            /**
             * Sent when a new {@link AndroidDebugBridge} is connected.
             * <p/>
             * This is sent from a non UI thread.
             * @param bridge the new {@link AndroidDebugBridge} object.
             */
            publicvoid bridgeChanged(AndroidDebugBridge bridge);
        }
     
        /**
         * Classes which implement this interface provide methods that deal
         * with {@link IDevice} addition, deletion, and changes.
         */
        public interface IDeviceChangeListener{
            /**
             * Sent when the a device is connected to the {@link AndroidDebugBridge}.
             * <p/>
             * This is sent from a non UI thread.
             * @param device the new device.
             */
            publicvoid deviceConnected(IDevice device);
     
            /**
             * Sent when the a device is connected to the {@link AndroidDebugBridge}.
             * <p/>
             * This is sent from a non UI thread.
             * @param device the new device.
             */
            publicvoid deviceDisconnected(IDevice device);
     
            /**
             * Sent when a device data changed, or when clients are started/terminated on the device.
             * <p/>
             * This is sent from a non UI thread.
             * @param device the device that was updated.
             * @param changeMask the mask describing what changed. It can contain any of the following
             * values: {@link IDevice#CHANGE_BUILD_INFO}, {@link IDevice#CHANGE_STATE},
             * {@link IDevice#CHANGE_CLIENT_LIST}
             */
            publicvoid deviceChanged(IDevice device,int changeMask);
        }
     
        /**
         * Classes which implement this interface provide methods that deal
         * with {@link Client}  changes.
         */
        public interface IClientChangeListener{
            /**
             * Sent when an existing client information changed.
             * <p/>
             * This is sent from a non UI thread.
             * @param client the updated client.
             * @param changeMask the bit mask describing the changed properties. It can contain
             * any of the following values: {@link Client#CHANGE_INFO},
             * {@link Client#CHANGE_DEBUGGER_STATUS}, {@link Client#CHANGE_THREAD_MODE},
             * {@link Client#CHANGE_THREAD_DATA}, {@link Client#CHANGE_HEAP_MODE},
             * {@link Client#CHANGE_HEAP_DATA}, {@link Client#CHANGE_NATIVE_HEAP_DATA}
             */
            publicvoid clientChanged(Client client,int changeMask);
        }
     
        /**
         * Initializes the <code>ddm</code> library.
         * <p/>This must be called once <b>before</b> any call to
         * {@link #createBridge(String, boolean)}.
         * <p>The library can be initialized in 2 ways:
         * <ul>
         * <li>Mode 1: <var>clientSupport</var> == <code>true</code>.<br>The library monitors the
         * devices and the applications running on them. It will connect to each application, as a
        * debugger of sort, to be able to interact with them through JDWP packets.</li>
       * <li>Mode 2: <var>clientSupport</var> == <code>false</code>.<br>The library only monitors
       * devices. The applications are left untouched, letting other tools built on
       * <code>ddmlib</code> to connect a debugger to them.</li>
         * </ul>
         * <p/><b>Only one tool can run in mode 1 at the same time.</b>
         * <p/>Note that mode 1 does not prevent debugging of applications running on devices. Mode 1
         * lets debuggers connect to <code>ddmlib</code> which acts as a proxy between the debuggers and
         * the applications to debug. See {@link Client#getDebuggerListenPort()}.
         * <p/>The preferences of <code>ddmlib</code> should also be initialized with whatever default
         * values were changed from the default values.
         * <p/>When the application quits, {@link #terminate()} should be called.
         * @param clientSupport Indicates whether the library should enable the monitoring and
         * interaction with applications running on the devices.
         * @see AndroidDebugBridge#createBridge(String, boolean)
         * @see DdmPreferences
         */
        publicstaticvoid init(boolean clientSupport){
            sClientSupport = clientSupport;
     
            MonitorThread monitorThread =MonitorThread.createInstance();
            monitorThread.start();
     
            HandleHello.register(monitorThread);
            HandleAppName.register(monitorThread);
            HandleTest.register(monitorThread);
            HandleThread.register(monitorThread);
            HandleHeap.register(monitorThread);
            HandleWait.register(monitorThread);
            HandleProfiling.register(monitorThread);
        }
     
        /**
         * Terminates the ddm library. This must be called upon application termination.
         */
        publicstaticvoid terminate(){
            // kill the monitoring services
            if(sThis !=null&& sThis.mDeviceMonitor !=null){
                sThis.mDeviceMonitor.stop();
                sThis.mDeviceMonitor =null;
            }
     
            MonitorThread monitorThread =MonitorThread.getInstance();
            if(monitorThread !=null){
                monitorThread.quit();
            }
        }
     
        /**
         * Returns whether the ddmlib is setup to support monitoring and interacting with
         * {@link Client}s running on the {@link IDevice}s.
         */
        staticboolean getClientSupport(){
            return sClientSupport;
        }
     
        /**
         * Creates a {@link AndroidDebugBridge} that is not linked to any particular executable.
         * <p/>This bridge will expect adb to be running. It will not be able to start/stop/restart
         * adb.
         * <p/>If a bridge has already been started, it is directly returned with no changes (similar
         * to calling {@link #getBridge()}).
         * @return a connected bridge.
         */
        publicstaticAndroidDebugBridge createBridge(){
            synchronized(sLock){
                if(sThis !=null){
                    return sThis;
                }
     
                try{
                    sThis =newAndroidDebugBridge();
                    sThis.start();
                }catch(InvalidParameterException e){
                    sThis =null;
                }
     
                // because the listeners could remove themselves from the list while processing
                // their event callback, we make a copy of the list and iterate on it instead of
                // the main list.
                // This mostly happens when the application quits.
                IDebugBridgeChangeListener[] listenersCopy = sBridgeListeners.toArray(
                        newIDebugBridgeChangeListener[sBridgeListeners.size()]);
     
                // notify the listeners of the change
                for(IDebugBridgeChangeListener listener : listenersCopy){
                    // we attempt to catch any exception so that a bad listener doesn't kill our
                    // thread
                    try{
                        listener.bridgeChanged(sThis);
                    }catch(Exception e){
                        Log.e(DDMS, e);
                    }
                }
     
                return sThis;
            }
        }
     
     
        /**
         * Creates a new debug bridge from the location of the command line tool.
         * <p/>
         * Any existing server will be disconnected, unless the location is the same and
         * <code>forceNewBridge</code> is set to false.
         * @param osLocation the location of the command line tool 'adb'
         * @param forceNewBridge force creation of a new bridge even if one with the same location
         * already exists.
         * @return a connected bridge.
         */
        publicstaticAndroidDebugBridge createBridge(String osLocation,boolean forceNewBridge){
            synchronized(sLock){
                if(sThis !=null){
                    if(sThis.mAdbOsLocation !=null&& sThis.mAdbOsLocation.equals(osLocation)&&
                            forceNewBridge ==false){
                        return sThis;
                    }else{
                        // stop the current server
                        sThis.stop();
                    }
                }
     
                try{
                    sThis =newAndroidDebugBridge(osLocation);
                    sThis.start();
                }catch(InvalidParameterException e){
                    sThis =null;
                }
     
                // because the listeners could remove themselves from the list while processing
                // their event callback, we make a copy of the list and iterate on it instead of
                // the main list.
                // This mostly happens when the application quits.
                IDebugBridgeChangeListener[] listenersCopy = sBridgeListeners.toArray(
                        newIDebugBridgeChangeListener[sBridgeListeners.size()]);
     
                // notify the listeners of the change
                for(IDebugBridgeChangeListener listener : listenersCopy){
                    // we attempt to catch any exception so that a bad listener doesn't kill our
                    // thread
                    try{
                        listener.bridgeChanged(sThis);
                    }catch(Exception e){
                        Log.e(DDMS, e);
                    }
                }
     
                return sThis;
            }
        }
     
        /**
         * Returns the current debug bridge. Can be <code>null</code> if none were created.
         */
        publicstaticAndroidDebugBridge getBridge(){
            return sThis;
        }
     
        /**
         * Disconnects the current debug bridge, and destroy the object.
         * <p/>This also stops the current adb host server.
         * <p/>
         * A new object will have to be created with {@link #createBridge(String, boolean)}.
         */
        publicstaticvoid disconnectBridge(){
            synchronized(sLock){
                if(sThis !=null){
                    sThis.stop();
                    sThis =null;
     
                    // because the listeners could remove themselves from the list while processing
                    // their event callback, we make a copy of the list and iterate on it instead of
                  // the main list.
                    // This mostly happens when the application quits.
                    IDebugBridgeChangeListener[] listenersCopy = sBridgeListeners.toArray(
                            newIDebugBridgeChangeListener[sBridgeListeners.size()]);
     
                    // notify the listeners.
                    for(IDebugBridgeChangeListener listener : listenersCopy){
                        // we attempt to catch any exception so that a bad listener doesn't kill our
                        // thread
                        try{
                          listener.bridgeChanged(sThis);
                        }catch(Exception e){
                            Log.e(DDMS, e);
                        }
                    }
                }
            }
        }
     
        /**
         * Adds the listener to the collection of listeners who will be notified when a new
         * {@link AndroidDebugBridge} is connected, by sending it one of the messages defined
         * in the {@link IDebugBridgeChangeListener} interface.
         * @param listener The listener which should be notified.
         */
        publicstaticvoid addDebugBridgeChangeListener(IDebugBridgeChangeListener listener){
            synchronized(sLock){
                if(sBridgeListeners.contains(listener)==false){
                  sBridgeListeners.add(listener);
                    if(sThis !=null){
                        // we attempt to catch any exception so that a bad listener doesn't kill our
                        // thread
                        try{
                            listener.bridgeChanged(sThis);
                        }catch(Exception e){
                            Log.e(DDMS, e);
                        }
                    }
                }
            }
        }
     
        /**
         * Removes the listener from the collection of listeners who will be notified when a new
         * {@link AndroidDebugBridge} is started.
         * @param listener The listener which should no longer be notified.
         */
        publicstaticvoid removeDebugBridgeChangeListener(IDebugBridgeChangeListener listener){
            synchronized(sLock){
                sBridgeListeners.remove(listener);
            }
        }
     
        /**
         * Adds the listener to the collection of listeners who will be notified when a {@link IDevice}
         * is connected, disconnected, or when its properties or its {@link Client} list changed,
         * by sending it one of the messages defined in the {@link IDeviceChangeListener} interface.
         * @param listener The listener which should be notified.
         */
        publicstaticvoid addDeviceChangeListener(IDeviceChangeListener listener){
            synchronized(sLock){
                if(sDeviceListeners.contains(listener)==false){
                    sDeviceListeners.add(listener);
                }
            }
        }
     
        /**
         * Removes the listener from the collection of listeners who will be notified when a
         * {@link IDevice} is connected, disconnected, or when its properties or its {@link Client}
         * list changed.
         * @param listener The listener which should no longer be notified.
         */
        publicstaticvoid removeDeviceChangeListener(IDeviceChangeListener listener){
            synchronized(sLock){
                sDeviceListeners.remove(listener);
            }
        }
     
        /**
         * Adds the listener to the collection of listeners who will be notified when a {@link Client}
         * property changed, by sending it one of the messages defined in the
         * {@link IClientChangeListener} interface.
         * @param listener The listener which should be notified.
         */
        publicstaticvoid addClientChangeListener(IClientChangeListener listener){
            synchronized(sLock){
                if(sClientListeners.contains(listener)==false){
                    sClientListeners.add(listener);
                }
            }
        }
     
        /**
         * Removes the listener from the collection of listeners who will be notified when a
         * {@link Client} property changed.
         * @param listener The listener which should no longer be notified.
         */
        publicstaticvoid removeClientChangeListener(IClientChangeListener listener){
            synchronized(sLock){
                sClientListeners.remove(listener);
            }
        }
     
     
        /**
         * Returns the devices.
         * @see #hasInitialDeviceList()
         */
        publicIDevice[] getDevices(){
            synchronized(sLock){
                if(mDeviceMonitor !=null){
                    return mDeviceMonitor.getDevices();
                }
            }
     
            returnnewIDevice[0];
        }
     
        /**
         * Returns whether the bridge has acquired the initial list from adb after being created.
         * <p/>Calling {@link #getDevices()} right after {@link #createBridge(String, boolean)} will
         * generally result in an empty list. This is due to the internal asynchronous communication
         * mechanism with <code>adb</code> that does not guarantee that the {@link IDevice} list has been
         * built before the call to {@link #getDevices()}.
         * <p/>The recommended way to get the list of {@link IDevice} objects is to create a
         * {@link IDeviceChangeListener} object.
         */
        publicboolean hasInitialDeviceList(){
            if(mDeviceMonitor !=null){
                return mDeviceMonitor.hasInitialDeviceList();
            }
     
            returnfalse;
        }
     
        /**
         * Sets the client to accept debugger connection on the custom "Selected debug port".
         * @param selectedClient the client. Can be null.
         */
        publicvoid setSelectedClient(Client selectedClient){
            MonitorThread monitorThread =MonitorThread.getInstance();
            if(monitorThread !=null){
                monitorThread.setSelectedClient(selectedClient);
            }
        }
     
        /**
         * Returns whether the {@link AndroidDebugBridge} object is still connected to the adb daemon.
         */
        publicboolean isConnected(){
            MonitorThread monitorThread =MonitorThread.getInstance();
            if(mDeviceMonitor !=null&& monitorThread !=null){
                return mDeviceMonitor.isMonitoring()&& monitorThread.getState()!=State.TERMINATED;
            }
            returnfalse;
        }
     
        /**
         * Returns the number of times the {@link AndroidDebugBridge} object attempted to connect
         * to the adb daemon.
         */
        publicint getConnectionAttemptCount(){
            if(mDeviceMonitor !=null){
                return mDeviceMonitor.getConnectionAttemptCount();
            }
            return-1;
        }
     
        /**
         * Returns the number of times the {@link AndroidDebugBridge} object attempted to restart
         * the adb daemon.
         */
        publicint getRestartAttemptCount(){
            if(mDeviceMonitor !=null){
                return mDeviceMonitor.getRestartAttemptCount();
            }
            return-1;
        }
     
        /**
         * Creates a new bridge.
         * @param osLocation the location of the command line tool
         * @throws InvalidParameterException
         */
        privateAndroidDebugBridge(String osLocation)throwsInvalidParameterException{
            if(osLocation ==null|| osLocation.length()==0){
                thrownewInvalidParameterException();
            }
            mAdbOsLocation = osLocation;
     
            checkAdbVersion();
        }
     
        /**
         * Creates a new bridge not linked to any particular adb executable.
         */
        privateAndroidDebugBridge(){
        }
     
        /**
         * Queries adb for its version number and checks it against {@link #MIN_VERSION_NUMBER} and
         * {@link #MAX_VERSION_NUMBER}
         */
        privatevoid checkAdbVersion(){
            // default is bad check
            mVersionCheck =false;
     
            if(mAdbOsLocation ==null){
                return;
            }
     
            try{
                String[] command =newString[2];
                command[0]= mAdbOsLocation;
                command[1]="version";//$NON-NLS-1$
                Log.d(DDMS,String.format("Checking '%1$s version'", mAdbOsLocation));//$NON-NLS-1$
                Process process =Runtime.getRuntime().exec(command);
     
                ArrayList<String> errorOutput =newArrayList<String>();
                ArrayList<String> stdOutput =newArrayList<String>();
                int status = grabProcessOutput(process, errorOutput, stdOutput,
                        true/* waitForReaders */);
     
                if(status !=0){
                    StringBuilder builder =newStringBuilder("'adb version' failed!");//$NON-NLS-1$
                    for(String error : errorOutput){
                        builder.append('\n');
                        builder.append(error);
                    }
                    Log.logAndDisplay(LogLevel.ERROR,"adb", builder.toString());
                }
     
                // check both stdout and stderr
                boolean versionFound =false;
                for(String line : stdOutput){
                    versionFound = scanVersionLine(line);
                    if(versionFound){
                        break;
                    }
                }
                if(!versionFound){
                    for(String line : errorOutput){
                        versionFound = scanVersionLine(line);
                        if(versionFound){
                            break;
                        }
                    }
                }
     
                if(!versionFound){
                    // if we get here, we failed to parse the output.
                    Log.logAndDisplay(LogLevel.ERROR, ADB,
                            "Failed to parse the output of 'adb version'");//$NON-NLS-1$
                }
     
            }catch(IOException e){
                Log.logAndDisplay(LogLevel.ERROR, ADB,
                        "Failed to get the adb version: "+ e.getMessage());//$NON-NLS-1$
            }catch(InterruptedException e){
            }finally{
     
            }
        }
     
        /**
         * Scans a line resulting from 'adb version' for a potential version number.
         * <p/>
         * If a version number is found, it checks the version number against what is expected
         * by this version of ddms.
         * <p/>
         * Returns true when a version number has been found so that we can stop scanning,
         * whether the version number is in the acceptable range or not.
         *
         * @param line The line to scan.
         * @return True if a version number was found (whether it is acceptable or not).
         */
        privateboolean scanVersionLine(String line){
            if(line !=null){
                Matcher matcher = sAdbVersion.matcher(line);
                if(matcher.matches()){
                    int majorVersion =Integer.parseInt(matcher.group(1));
                    int minorVersion =Integer.parseInt(matcher.group(2));
                    int microVersion =Integer.parseInt(matcher.group(3));
     
                    // check only the micro version for now.
                    if(microVersion < ADB_VERSION_MICRO_MIN){
                        String message =String.format(
                                "Required minimum version of adb: %1$d.%2$d.%3$d."//$NON-NLS-1$
                                +"Current version is %1$d.%2$d.%4$d",//$NON-NLS-1$
                                majorVersion, minorVersion, ADB_VERSION_MICRO_MIN,
                                microVersion);
                        Log.logAndDisplay(LogLevel.ERROR, ADB, message);
                    }elseif(ADB_VERSION_MICRO_MAX !=-1&&
                            microVersion > ADB_VERSION_MICRO_MAX){
                        String message =String.format(
                                "Required maximum version of adb: %1$d.%2$d.%3$d."//$NON-NLS-1$
                                +"Current version is %1$d.%2$d.%4$d",//$NON-NLS-1$
                                majorVersion, minorVersion, ADB_VERSION_MICRO_MAX,
                                microVersion);
                        Log.logAndDisplay(LogLevel.ERROR, ADB, message);
                    }else{
                        mVersionCheck =true;
                    }
     
                    returntrue;
                }
            }
            returnfalse;
        }
     
        /**
         * Starts the debug bridge.
         * @return true if success.
         */
        boolean start(){
            if(mAdbOsLocation !=null&&(mVersionCheck ==false|| startAdb()==false)){
                returnfalse;
            }
     
            mStarted =true;
     
            // now that the bridge is connected, we start the underlying services.
            mDeviceMonitor =newDeviceMonitor(this);
            mDeviceMonitor.start();
     
            returntrue;
        }
     
       /**
         * Kills the debug bridge, and the adb host server.
         * @return true if success
         */
        boolean stop(){
            // if we haven't started we return false;
            if(mStarted ==false){
                returnfalse;
            }
     
            // kill the monitoring services
            mDeviceMonitor.stop();
            mDeviceMonitor =null;
     
            if(stopAdb()==false){
                returnfalse;
            }
     
            mStarted =false;
            returntrue;
        }
     
        /**
         * Restarts adb, but not the services around it.
         * @return true if success.
         */
        publicboolean restart(){
            if(mAdbOsLocation ==null){
                Log.e(ADB,
                        "Cannot restart adb when AndroidDebugBridge is created without the location of adb.");//$NON-NLS-1$
                returnfalse;
            }
     
            if(mVersionCheck ==false){
                Log.logAndDisplay(LogLevel.ERROR, ADB,
                        "Attempting to restart adb, but version check failed!");//$NON-NLS-1$
                returnfalse;
            }
            synchronized(this){
                stopAdb();
     
                boolean restart = startAdb();
     
                if(restart && mDeviceMonitor ==null){
                    mDeviceMonitor =newDeviceMonitor(this);
                    mDeviceMonitor.start();
                }
     
                return restart;
            }
        }
     
        /**
         * Notify the listener of a new {@link IDevice}.
         * <p/>
         * The notification of the listeners is done in a synchronized block. It is important to
         * expect the listeners to potentially access various methods of {@link IDevice} as well as
         * {@link #getDevices()} which use internal locks.
         * <p/>
         * For this reason, any call to this method from a method of {@link DeviceMonitor},
         * {@link IDevice} which is also inside a synchronized block, should first synchronize on
         * the {@link AndroidDebugBridge} lock. Access to this lock is done through {@link #getLock()}.
         * @param device the new <code>IDevice</code>.
         * @see #getLock()
         */
        void deviceConnected(IDevice device){
            // because the listeners could remove themselves from the list while processing
            // their event callback, we make a copy of the list and iterate on it instead of
            // the main list.
            // This mostly happens when the application quits.
            IDeviceChangeListener[] listenersCopy =null;
            synchronized(sLock){
                listenersCopy = sDeviceListeners.toArray(
                        newIDeviceChangeListener[sDeviceListeners.size()]);
            }
     
            // Notify the listeners
            for(IDeviceChangeListener listener : listenersCopy){
                // we attempt to catch any exception so that a bad listener doesn't kill our
                // thread
                try{
                    listener.deviceConnected(device);
                }catch(Exception e){
                    Log.e(DDMS, e);
                }
            }
        }
     
        /**
         * Notify the listener of a disconnected {@link IDevice}.
         * <p/>
         * The notification of the listeners is done in a synchronized block. It is important to
         * expect the listeners to potentially access various methods of {@link IDevice} as well as
         * {@link #getDevices()} which use internal locks.
         * <p/>
         * For this reason, any call to this method from a method of {@link DeviceMonitor},
         * {@link IDevice} which is also inside a synchronized block, should first synchronize on
         * the {@link AndroidDebugBridge} lock. Access to this lock is done through {@link #getLock()}.
         * @param device the disconnected <code>IDevice</code>.
         * @see #getLock()
         */
        void deviceDisconnected(IDevice device){
            // because the listeners could remove themselves from the list while processing
            // their event callback, we make a copy of the list and iterate on it instead of
            // the main list.
            // This mostly happens when the application quits.
            IDeviceChangeListener[] listenersCopy =null;
            synchronized(sLock){
                listenersCopy = sDeviceListeners.toArray(
                        newIDeviceChangeListener[sDeviceListeners.size()]);
            }
     
            // Notify the listeners
            for(IDeviceChangeListener listener : listenersCopy){
                // we attempt to catch any exception so that a bad listener doesn't kill our
                // thread
                try{
                    listener.deviceDisconnected(device);
                }catch(Exception e){
                    Log.e(DDMS, e);
                }
            }
        }
     
        /**
         * Notify the listener of a modified {@link IDevice}.
         * <p/>
         * The notification of the listeners is done in a synchronized block. It is important to
         * expect the listeners to potentially access various methods of {@link IDevice} as well as
         * {@link #getDevices()} which use internal locks.
         * <p/>
         * For this reason, any call to this method from a method of {@link DeviceMonitor},
         * {@link IDevice} which is also inside a synchronized block, should first synchronize on
         * the {@link AndroidDebugBridge} lock. Access to this lock is done through {@link #getLock()}.
         * @param device the modified <code>IDevice</code>.
         * @see #getLock()
         */
        void deviceChanged(IDevice device,int changeMask){
            // because the listeners could remove themselves from the list while processing
            // their event callback, we make a copy of the list and iterate on it instead of
            // the main list.
            // This mostly happens when the application quits.
            IDeviceChangeListener[] listenersCopy =null;
            synchronized(sLock){
                listenersCopy = sDeviceListeners.toArray(
                        newIDeviceChangeListener[sDeviceListeners.size()]);
            }
     
            // Notify the listeners
            for(IDeviceChangeListener listener : listenersCopy){
                // we attempt to catch any exception so that a bad listener doesn't kill our
                // thread
                try{
                    listener.deviceChanged(device, changeMask);
                }catch(Exception e){
                    Log.e(DDMS, e);
                }
            }
        }
     
        /**
         * Notify the listener of a modified {@link Client}.
         * <p/>
         * The notification of the listeners is done in a synchronized block. It is important to
         * expect the listeners to potentially access various methods of {@link IDevice} as well as
         * {@link #getDevices()} which use internal locks.
         * <p/>
         * For this reason, any call to this method from a method of {@link DeviceMonitor},
         * {@link IDevice} which is also inside a synchronized block, should first synchronize on
         * the {@link AndroidDebugBridge} lock. Access to this lock is done through {@link #getLock()}.
         * @param device the modified <code>Client</code>.
         * @param changeMask the mask indicating what changed in the <code>Client</code>
         * @see #getLock()
         */
        void clientChanged(Client client,int changeMask){
            // because the listeners could remove themselves from the list while processing
            // their event callback, we make a copy of the list and iterate on it instead of
            // the main list.
            // This mostly happens when the application quits.
            IClientChangeListener[] listenersCopy =null;
            synchronized(sLock){
                listenersCopy = sClientListeners.toArray(
                        newIClientChangeListener[sClientListeners.size()]);
     
            }
     
            // Notify the listeners
            for(IClientChangeListener listener : listenersCopy){
                // we attempt to catch any exception so that a bad listener doesn't kill our
                // thread
                try{
                    listener.clientChanged(client, changeMask);
                }catch(Exception e){
                    Log.e(DDMS, e);
                }
            }
        }
     
        /**
         * Returns the {@link DeviceMonitor} object.
         */
        DeviceMonitor getDeviceMonitor(){
            return mDeviceMonitor;
        }
     
        /**
         * Starts the adb host side server.
         * @return true if success
         */
        synchronizedboolean startAdb(){
            if(mAdbOsLocation ==null){
                Log.e(ADB,
                    "Cannot start adb when AndroidDebugBridge is created without the location of adb.");//$NON-NLS-1$
                returnfalse;
            }
     
            Process proc;
            int status =-1;
     
            try{
                String[] command =newString[2];
                command[0]= mAdbOsLocation;
                command[1]="start-server";//$NON-NLS-1$
                Log.d(DDMS,
                        String.format("Launching '%1$s %2$s' to ensure ADB is running.",//$NON-NLS-1$
                        mAdbOsLocation, command[1]));
                proc =Runtime.getRuntime().exec(command);
     
                ArrayList<String> errorOutput =newArrayList<String>();
                ArrayList<String> stdOutput =newArrayList<String>();
                status = grabProcessOutput(proc, errorOutput, stdOutput,
                        false/* waitForReaders */);
     
            }catch(IOException ioe){
                Log.d(DDMS,"Unable to run 'adb': "+ ioe.getMessage());//$NON-NLS-1$
                // we'll return false;
            }catch(InterruptedException ie){
                Log.d(DDMS,"Unable to run 'adb': "+ ie.getMessage());//$NON-NLS-1$
                // we'll return false;
            }
     
            if(status !=0){
                Log.w(DDMS,
                        "'adb start-server' failed -- run manually if necessary");//$NON-NLS-1$
                returnfalse;
            }
     
            Log.d(DDMS,"'adb start-server' succeeded");//$NON-NLS-1$
     
            returntrue;
        }
     
        /**
         * Stops the adb host side server.
         * @return true if success
         */
        privatesynchronizedboolean stopAdb(){
            if(mAdbOsLocation ==null){
                Log.e(ADB,
                    "Cannot stop adb when AndroidDebugBridge is created without the location of adb.");//$NON-NLS-1$
                returnfalse;
            }
     
            Process proc;
            int status =-1;
     
            try{
                String[] command =newString[2];
                command[0]= mAdbOsLocation;
                command[1]="kill-server";//$NON-NLS-1$
                proc =Runtime.getRuntime().exec(command);
                status = proc.waitFor();
            }
            catch(IOException ioe){
                // we'll return false;
            }
            catch(InterruptedException ie){
                // we'll return false;
            }
     
            if(status !=0){
                Log.w(DDMS,
                        "'adb kill-server' failed -- run manually if necessary");//$NON-NLS-1$
                returnfalse;
            }
     
            Log.d(DDMS,"'adb kill-server' succeeded");//$NON-NLS-1$
            returntrue;
        }
     
        /**
         * Get the stderr/stdout outputs of a process and return when the process is done.
         * Both <b>must</b> be read or the process will block on windows.
         * @param process The process to get the ouput from
         * @param errorOutput The array to store the stderr output. cannot be null.
         * @param stdOutput The array to store the stdout output. cannot be null.
         * @param displayStdOut If true this will display stdout as well
         * @param waitforReaders if true, this will wait for the reader threads.
         * @return the process return code.
         * @throws InterruptedException
         */
        privateint grabProcessOutput(finalProcess process,finalArrayList<String> errorOutput,
                finalArrayList<String> stdOutput,boolean waitforReaders)
                throwsInterruptedException{
            assert errorOutput !=null;
            assert stdOutput !=null;
            // read the lines as they come. if null is returned, it's
            // because the process finished
            Thread t1 =newThread(""){//$NON-NLS-1$
                @Override
                publicvoid run(){
                    // create a buffer to read the stderr output
                    InputStreamReader is =newInputStreamReader(process.getErrorStream());
                    BufferedReader errReader =newBufferedReader(is);
     
                    try{
                        while(true){
                            String line = errReader.readLine();
                            if(line !=null){
                                Log.e(ADB, line);
                                errorOutput.add(line);
                            }else{
                                break;
                            }
                        }
                    }catch(IOException e){
                        // do nothing.
                    }
                }
            };
     
            Thread t2 =newThread(""){//$NON-NLS-1$
                @Override
                publicvoid run(){
                    InputStreamReader is =newInputStreamReader(process.getInputStream());
                    BufferedReader outReader =newBufferedReader(is);
     
                    try{
                        while(true){
                            String line = outReader.readLine();
                            if(line !=null){
                                Log.d(ADB, line);
                                stdOutput.add(line);
                            }else{
                                break;
                            }
                        }
                    }catch(IOException e){
                        // do nothing.
                    }
                }
            };
     
            t1.start();
            t2.start();
     
            // it looks like on windows process#waitFor() can return
            // before the thread have filled the arrays, so we wait for both threads and the
            // process itself.
            if(waitforReaders){
                try{
                    t1.join();
                }catch(InterruptedException e){
                }
                try{
                    t2.join();
                }catch(InterruptedException e){
                }
            }
     
            // get the return code from the process
            return process.waitFor();
        }
     
        /**
         * Returns the singleton lock used by this class to protect any access to the listener.
         * <p/>
         * This includes adding/removing listeners, but also notifying listeners of new bridges,
         * devices, and clients.
         */
        staticObject getLock(){
            return sLock;
        }
    }

     

  • 相关阅读:
    Java随学随记
    jquery的bind()和trigger()
    js跨域访问
    好文推荐系列-------(5)js模块化编程
    好文推荐系列---------(4)使用Yeoman自动构建Ember项目
    好文推荐系列--------(3)GruntJS 在线重载 提升生产率至新境界
    好文推荐系列--------(2)GruntJS——重复乏味的工作总会有人做(反正我不做)
    好文推荐系列--------(1)bower---管理你的客户端依赖
    英文邮件写作
    原型
  • 原文地址:https://www.cnblogs.com/szy123618/p/4044489.html
Copyright © 2011-2022 走看看