启动下载任务.

        将任务状态设定为Downloading, 如果没有超过最大任务数的话;
        否则将它设定为Waiting.
177906
def start_task(self, row, scan=True):
        '''
        '''
        if not row or row[STATE_COL] in RUNNING_STATES :
            return
        row[STATE_COL] = State.WAITING
        row[STATENAME_COL] = StateNames[State.WAITING]
        self.update_task_db(row)
        if scan:
            self.scan_tasks()
337977
private synchronized static void waiting(String classname, int fnr,
			int offset)
	{
		m.put(classname, StaticOperationsCounters.waiting[fnr] += offset);
		stateChanged();
	}
566750
function downloadInstaller(requester, isInitialAttempt, updateParams) {
        updateParams = updateParams || _updateParams;
        var currentRequester = requester || "";
        try {
            var ext = path.extname(updateParams.installerName);
            var localInstallerPath = path.resolve(updateDir, Date.now().toString() + ext),
                localInstallerFile = fs.createWriteStream(localInstallerPath),
                requestCompleted = true,
                readTimeOut = 180000;
            progress(request(updateParams.downloadURL, {timeout: readTimeOut}), {})
                .on('progress', function (state) {
                    var target = "retry-download";
                    if (isInitialAttempt) {
                        target = "initial-download";
                    }
                    var info = Math.floor(parseFloat(state.percent) * 100).toString() + '%';
                    var status = {
                        target: target,
                        spans: [{
                            id: "percent",
                            val: info
                        }]
                    };
                    postMessageToBrackets(MessageIds.SHOW_STATUS_INFO, currentRequester, status);
                })
                .on('error', function (err) {
                    console.log("AutoUpdate : Download failed. Error occurred : " + err.toString());
                    requestCompleted = false;
                    localInstallerFile.end();
                    var error = err.code === 'ESOCKETTIMEDOUT' || err.code === 'ENOTFOUND' ?
                                nodeErrorMessages.NETWORK_SLOW_OR_DISCONNECTED :
                                nodeErrorMessages.DOWNLOAD_ERROR;
                    postMessageToBrackets(MessageIds.NOTIFY_DOWNLOAD_FAILURE, currentRequester, error);
                })
                .pipe(localInstallerFile)
                .on('close', function () {
                    if (requestCompleted) {
                        try {
                            fs.renameSync(localInstallerPath, installerPath);
                            postMessageToBrackets(MessageIds.NOTIFY_DOWNLOAD_SUCCESS, currentRequester);
                        } catch (e) {
                            console.log("AutoUpdate : Download failed. Exception occurred : " + e.toString());
                            postMessageToBrackets(MessageIds.NOTIFY_DOWNLOAD_FAILURE,
                                                      currentRequester, nodeErrorMessages.DOWNLOAD_ERROR);
                        }
                    }
                });
        } catch (e) {
            console.log("AutoUpdate : Download failed. Exception occurred : " + e.toString());
            postMessageToBrackets(MessageIds.NOTIFY_DOWNLOAD_FAILURE,
                                  currentRequester, nodeErrorMessages.DOWNLOAD_ERROR);
        }
    }
765558
function getBrowserData(){
	//Mobile
	function mobilecheck() {
		var check = false;
		(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
		return check;
	}
	//Mobile or Tablet
	function mobileAndTabletcheck() {
		var check = false;
		(function(a){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor||window.opera);
		return check;
	}
	//Device Type
	var device = 'desktop';
	if(mobilecheck()){
		device = 'mobile';
	}
	else if(mobileAndTabletcheck()){
		device = 'tablet';
	}
	//Browser
	var ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
	if(/trident/i.test(M[1])){
		tem=/\brv[ :]+(\d+)/g.exec(ua) || []; 
		return {name:'IE',version:(tem[1]||'')};
		}
	if(M[1]==='Chrome'){
		tem=ua.match(/\bOPR\/(\d+)/)
		if(tem!=null)   {return {name:'Opera', version:tem[1]};}
		}
	M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
	if((tem=ua.match(/version\/(\d+)/i))!=null) {M.splice(1,1,tem[1]);}
	//Screen Size
	var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
	var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
	return {
		device: device,
		name: M[0],
		version: M[1],
		width: width,
		height: height
	}
}
1275857
public void download() {
        URL dataURL = null;
        String fileName = folder + "/" + url.substring(url.lastIndexOf("/") + 1);
        if (new File(fileName).exists()) {
            return;
        }
        try {
            dataURL = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        File downloadedData = new File(fileName);
        try {
            assert dataURL != null;
            FileUtils.copyURLToFile(dataURL, downloadedData);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
1374613
def start_playing(self, on_exit, args):
        
        # log.debug("%s,%s,%s" % (args['song_id'], args['song_name'], args['mp3_url']))
        if "cache" in args.keys() and os.path.isfile(args["cache"]):
            thread = threading.Thread(
                target=self.run_mpg123, args=(on_exit, args["cache"])
            )
        else:
            new_url = NetEase().songs_url([args["song_id"]])[0]["url"]  #使用新地址
            if  not new_url:    #如果没有获得新地址
                new_url = args["mp3_url"]  #使用老地址传给mpg123
            thread = threading.Thread(
                target=self.run_mpg123,
                args=(on_exit, new_url, args["expires"], args["get_time"]),
            )
            cache_thread = threading.Thread(
                target=self.download_song,
                args=(
                    args["song_id"],
                    args["song_name"],
                    args["artist"],
                    args["mp3_url"],
                ),
            )
            cache_thread.start()

        thread.start()
        lyric_download_thread = threading.Thread(target=self.download_lyric)
        lyric_download_thread.start()
        tlyric_download_thread = threading.Thread(
            target=self.download_lyric, args=(True,)
        )
        tlyric_download_thread.start()
        # returns immediately after the thread starts
        return thread
571399
function downloadRegistry() {
        if (pendingDownloadRegistry) {
            return pendingDownloadRegistry.promise();
        }

        pendingDownloadRegistry = new $.Deferred();

        $.ajax({
            url: brackets.config.extension_registry,
            dataType: "json",
            cache: false
        })
            .done(function (data) {
                exports.hasDownloadedRegistry = true;
                Object.keys(data).forEach(function (id) {
                    if (!extensions[id]) {
                        extensions[id] = {};
                    }
                    extensions[id].registryInfo = data[id];
                    synchronizeEntry(id);
                });
                exports.trigger("registryDownload");
                pendingDownloadRegistry.resolve();
            })
            .fail(function () {
                pendingDownloadRegistry.reject();
            })
            .always(function () {
                // Make sure to clean up the pending registry so that new requests can be made.
                pendingDownloadRegistry = null;
            });

        return pendingDownloadRegistry.promise();
    }
691314
public void download() throws IOException, InterruptedException {
    if (!Files.exists(destinationFile.getParent())) {
      Files.createDirectories(destinationFile.getParent());
    }

    if (Files.exists(destinationFile)) {
      throw new FileAlreadyExistsException(destinationFile.toString());
    }
    URLConnection connection = address.openConnection();
    connection.setRequestProperty("User-Agent", userAgentString);

    try (InputStream in = connection.getInputStream()) {
      // note : contentLength can potentially be -1 if it is unknown.
      long contentLength = connection.getContentLengthLong();

      logger.info("Downloading " + address + " to " + destinationFile);

      try (BufferedOutputStream out =
          new BufferedOutputStream(
              Files.newOutputStream(destinationFile, StandardOpenOption.CREATE_NEW))) {

        progressListener.start(
            getDownloadStatus(contentLength, Locale.getDefault()), contentLength);

        int bytesRead;
        byte[] buffer = new byte[BUFFER_SIZE];

        while ((bytesRead = in.read(buffer)) != -1) {
          if (Thread.currentThread().isInterrupted()) {
            logger.warning("Download was interrupted\n");
            cleanUp();
            throw new InterruptedException("Download was interrupted");
          }

          out.write(buffer, 0, bytesRead);
          progressListener.update(bytesRead);
        }
      }
    }
    progressListener.done();
  }
752103
@Override
    protected void ensureAvailableBytes(int size)
    {
        if (offset + size > bufferSize)
        {
            try
            {
                int availableBytes = (int) (fileChannel.size() - fileChannel.position());
                ByteBuffer byteBuffer = ByteBuffer.allocate(Math.min(availableBytes, offset));
                int readBytes = fileChannel.read(byteBuffer);
                if (readBytes == availableBytes)
                {
                    fileChannel.close();
                    fileChannel = null;
                }
                assert readBytes > 0 : "已到达文件尾部！";
                byteBuffer.flip();
                byte[] bytes = byteBuffer.array();
                System.arraycopy(this.bytes, offset, this.bytes, offset - readBytes, bufferSize - offset);
                System.arraycopy(bytes, 0, this.bytes, bufferSize - readBytes, readBytes);
                offset -= readBytes;
            }
            catch (IOException e)
            {
                throw new RuntimeException(e);
            }
        }
    }
833975
public void ready() {
        
        // 複数の文字の場合、重複を排除する。
        final Set<String> duplicatedWords = new HashSet<>();
        final List<MultiChar> newMulti = new ArrayList<>();
        for(MultiChar word : multi) {
            if(duplicatedWords.contains(word.word)) {
                continue;
            }
            duplicatedWords.add(word.word);
            newMulti.add(word);
        }
        
        // 複数の文字の場合、文字長が長い順に並び替える。
        Collections.sort(newMulti, new Comparator<MultiChar>() {
            
            @Override
            public int compare(final MultiChar o1, final MultiChar o2) {
                
                final int length1 = o1.word.length();
                final int length2 = o2.word.length();
                if(length1 < length2) {
                    return 1;
                    
                } else if(length1 > length2) {
                    return -1;
                    
                } else {
                    return o1.word.compareTo(o2.word);
                }
            }
        });
        
        multi.clear();
        multi.addAll(newMulti);
        
    }
18631
def _download(url):
    
    fh = StringIO()

    for line in get(url):
        fh.write(line)

    fh.seek(0)
    return fh
88952
def waiting(self, timeout=0):
        ""
        if self.linebuffer:
            return True
        (winput, woutput, wexceptions) = select.select((self.sock,), (), (), timeout)
        return winput != []
381264
def status(self):
        ''''''
        transfered = self.download - self.prev_download
        now = time.time()
        interval = now - self.last_status_time
        self.last_status_time = now
        return("DFLogger: %(state)s Rate(%(interval)ds):%(rate).3fkB/s Block:%(block_cnt)d Missing:%(missing)d Fixed:%(fixed)d Abandoned:%(abandoned)d" %
              {"interval": interval,
               "rate": transfered/(interval*1000),
               "block_cnt": self.block_cnt,
               "missing": len(self.missing_blocks),
               "fixed": self.missing_found,
               "abandoned": self.abandoned,
               "state": "Inactive" if self.stopped else "Active"
           })
502376
@SuppressWarnings("ResultOfMethodCallIgnored")
    public static boolean download(String downloadURL) {
        if (Checker.isHyperLink(downloadURL) && checkDownloadPath()) {
            logger.info("ready for download url: " + downloadURL + " storage in " + storageFolder);
        } else {
            logger.info("url or storage path are invalidated, can't download");
            return false;
        }
        int byteRead;
        String log = "download success from url '" + downloadURL + "' to local '";
        try {
            String fileName = checkPath(storageFolder + ValueConsts.SEPARATOR + Formatter.getFileName(downloadURL));
            String tmp = fileName + ".tmp";
            File file = new File(tmp);
            log += file.getAbsolutePath() + "'";
            URL url = new URL(downloadURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            InputStream inStream = NetUtils.getInputStreamOfConnection(conn);
            if (conn.getResponseCode() != ValueConsts.RESPONSE_OK || conn.getContentLength() <= 0) {
                return false;
            }
            FileOutputStream fs = new FileOutputStream(file);
            if (!file.exists()) {
                file.createNewFile();
            }
            byte[] buffer = new byte[1024];
            while ((byteRead = inStream.read(buffer)) != -1) {
                fs.write(buffer, 0, byteRead);
            }
            fs.flush();
            inStream.close();
            fs.close();
            file.renameTo(new File(fileName));
            logger.info(log);
            return true;
        } catch (IOException e) {
            log = log.replace("success", "error") + ", message: " + e.getMessage();
            logger.error(log);
            return false;
        }
    }
449255
def finish():
    """"""
    out.warn("Interrupted!")
    for t in threads:
        t.stop()
    jobs.clear()
    out.warn("Waiting for download threads to finish.")
363216
public static void download(String entranceURL, String type, String path, boolean containEntrance, boolean justOriginalName){
        int timeout = 300000;
        if(!entranceURL.endsWith("/")){
            entranceURL += "/";
        }
        Set<String> urls = new HashSet<>();
        boolean ok = false;
        int limit=0;
        while (!ok && (limit++) < 3) {
            try {
                System.out.println("【"+type+"】*** connect " + entranceURL);
                for (Element element : Jsoup.connect(entranceURL).timeout(timeout).get().select("a")) {
                    String href = element.attr("href").trim();
                    if (!href.startsWith("http")) {
                        if(href.startsWith("/")){
                            href = "http://www.bbc.co.uk" + href;
                        }else{
                            href = entranceURL + href;
                        }
                    }
                    if (href.startsWith(entranceURL) && (!href.equals(entranceURL) || containEntrance) ) {
                        urls.add(href);
                    }
                }
                ok = true;
            } catch (Exception e) {
                System.out.println(e.getMessage() + " retry...");
            }
        }
        AtomicInteger i = new AtomicInteger(1);
        Set<String> resources = new HashSet<>();
        urls.stream().sorted().forEach(url -> {
            boolean success = false;
            int times=0;
            while (!success && (times++) < 3) {
                try {
                    System.out.println(i.get() + "、connect " + url);
                    for (Element element : Jsoup.connect(url).timeout(timeout).get().select("a")) {
                        String href = element.attr("href").trim();
                        //只下载mp3、mp4、wav和pdf文件
                        if (href.endsWith(".mp3") || href.endsWith(".wav") || href.endsWith(".mp4") || href.endsWith(".pdf")) {
                            if (!href.startsWith("http")) {
                                if(href.startsWith("/")){
                                    href = "http://www.bbc.co.uk" + href;
                                }else{
                                    String[] attr = url.split("/");
                                    href = url.substring(0, url.length()-attr[attr.length-1].length()) + href;
                                }
                            }
                            resources.add(href);
                        }
                    }
                    i.incrementAndGet();
                    success = true;
                } catch (Exception e) {
                    System.out.println(e.getMessage() + " retry...");
                }
            }
        });
        AtomicInteger j = new AtomicInteger(1);
        count += resources.size();
        resources.stream().sorted().forEach(resource -> {
            boolean success = false;
            int times=0;
            while (!success && (times++) < 3) {
                try {
                    //提取文件名称
                    String[] attr = resource.split("/");
                    String fileName = attr[attr.length - 2] + "_" + attr[attr.length - 1].replace(attr[attr.length - 2], "");
                    if(attr[attr.length - 1].endsWith(attr[attr.length - 2])){
                        fileName = attr[attr.length - 1];
                    }
                    fileName = fileName.replace("_download", "");
                    if(justOriginalName){
                        fileName = attr[attr.length - 1];
                    }
                    System.out.println(resources.size() + "/" + j.get() + "、find resource: " + resource);
                    //确保本地路径存储
                    Path dir = Paths.get(path, type);
                    if (!Files.exists(dir)) {
                        //不存在则新建
                        dir.toFile().mkdirs();
                    }
                    //保存文件的完整本地路径
                    Path out = Paths.get(path, type, fileName);
                    //如果文件存在则表示之前已经下载过，本次不用下载
                    //因为BBC的访问不稳定，所以可能需要执行程序多次才能完整下载完毕，所以这里要处理已存在文件的问题
                    if (!Files.exists(out)) {
                        //下载文件
                        Connection.Response response = Jsoup.connect(resource).maxBodySize(0).ignoreContentType(true).timeout(timeout).execute();
                        //将文件保存到本地
                        Files.write(out, response.bodyAsBytes());
                        System.out.println(resources.size() + "/" + j.get() + "、save resource to: " + out);
                    } else {
                        System.out.println(resources.size() + "/" + j.get() + "、resource exist, don't need to download");
                    }
                    j.incrementAndGet();
                    success = true;
                } catch (Exception e) {
                    System.out.println(e.getMessage() + " retry...");
                }
            }
        });
    }
1177274
private void startConnect() {

        // 触发一次连接将重试次数减1
        curLeftResolveTimes--;

        HMSAgentLog.d("start thread to connect");
        ThreadUtil.INST.excute(new Runnable() {
            @Override
            public void run() {
                HuaweiApiClient client =  getApiClient();

                if (client != null) {
                    HMSAgentLog.d("connect");
                    Activity curActivity = ActivityMgr.INST.getLastActivity();

                    // 考虑到有cp后台需要调用接口，HMSSDK去掉了activity不能为空的判断。这里只是取当前activity，可能为空
                    timeoutHandler.sendEmptyMessageDelayed(APICLIENT_TIMEOUT_HANDLE_MSG, APICLIENT_CONNECT_TIMEOUT);
                    client.connect(curActivity);
                } else {
                    HMSAgentLog.d("client is generate error");
                    onConnectEnd(HMSAgent.AgentResultCode.RESULT_IS_NULL);
                }
            }
        });
    }