HuaweiApiClient 连接结果回调

@param rst    结果码
@param client HuaweiApiClient 实例
344522
@Override
    public void onConnect(int rst, HuaweiApiClient client) {
        if (client == null || !ApiClientMgr.INST.isConnect(client)) {
            HMSAgentLog.e("client not connted");
            onSnsGetMsgIntentResult(rst, null);
            return;
        }

        PendingResult<IntentResult> sendMsgResult = HuaweiSns.HuaweiSnsApi.getMsgSendIntent(client, msg, needResult);
        sendMsgResult.setResultCallback(new ResultCallback<IntentResult>() {
            @Override
            public void onResult(IntentResult result) {
                if (result == null) {
                    HMSAgentLog.e("result is null");
                    onSnsGetMsgIntentResult(HMSAgent.AgentResultCode.RESULT_IS_NULL, null);
                    return;
                }

                Status status = result.getStatus();
                if (status == null) {
                    HMSAgentLog.e("status is null");
                    onSnsGetMsgIntentResult(HMSAgent.AgentResultCode.STATUS_IS_NULL, null);
                    return;
                }

                int rstCode = status.getStatusCode();
                HMSAgentLog.d("status=" + status);
                // 需要重试的错误码，并且可以重试
                if ((rstCode == CommonCode.ErrorCode.SESSION_INVALID
                        || rstCode == CommonCode.ErrorCode.CLIENT_API_INVALID) && retryTimes > 0) {
                    retryTimes--;
                    connect();
                } else if (rstCode == SNSCode.OK) {
                    //回调GetMsgIntent结果
                    Intent nxtIntent = result.getIntent();
                    if (nxtIntent == null) {
                        HMSAgentLog.e("nxtIntent is null");
                        onSnsGetMsgIntentResult(HMSAgent.AgentResultCode.RESULT_IS_NULL, null);
                        return;
                    } else {
                        onSnsGetMsgIntentResult(rstCode, nxtIntent);
                        return;
                    }

                }else {
                    onSnsGetMsgIntentResult(rstCode, null);
                }
            }
        });
    }
126055
@Override
    @SuppressWarnings("checkstyle:linelength")
    public Page<RatePlan> firstPage(final TwilioRestClient client) {
        Request request = new Request(
            HttpMethod.GET,
            Domains.WIRELESS.toString(),
            "/v1/RatePlans",
            client.getRegion()
        );

        addQueryParams(request);
        return pageForRequest(client, request);
    }
1137107
public ApiResponse authorizeAppClient(String clientId, String clientSecret) {
        validateNonEmptyParam(clientId, "client identifier");
        validateNonEmptyParam(clientSecret, "client secret");
        assertValidApplicationId();
        loggedInUser = null;
        accessToken = null;
        currentOrganization = null;
        Map<String, Object> formData = new HashMap<String, Object>();
        formData.put("grant_type", "client_credentials");
        formData.put("client_id", clientId);
        formData.put("client_secret", clientSecret);
        ApiResponse response = apiRequest(HttpMethod.POST, formData, null,
                organizationId, applicationId, "token");
        if (response == null) {
            return response;
        }
        if (!isEmpty(response.getAccessToken())) {
            loggedInUser = null;
            accessToken = response.getAccessToken();
            currentOrganization = null;
            log.info("Client.authorizeAppClient(): Access token: "
                    + accessToken);
        } else {
            log.info("Client.authorizeAppClient(): Response: " + response);
        }
        return response;
    }
1071119
public void addClient(String pUserName, WebSocketSession pClient) {
        if (!mClients.containsKey(pUserName)) {
            LogHelper.info("", "增加客户端；name:" + pUserName, "MyClientFactory.addClient");
            mClients.put(pUserName, pClient);
            onAddClient(pUserName, pClient);
        } else {
            if (!mClients.get(pUserName).getId().equals(pClient.getId()) && mClients.get(pUserName).isOpen()) {
                changeClient(pUserName, pClient);
            }
        }
    }
153286
@Override
    public void onActivityPause(Activity activity) {
        // 通知hmssdk，activity onPause了
        HuaweiApiClient client = getApiClient();
        if (client != null) {
            client.onPause(activity);
        }
    }
746810
@Override
    public ResourceSet<Payload> read(final TwilioRestClient client) {
        return new ResourceSet<>(this, client, firstPage(client));
    }
337247
public static void createAsync(final TemplateBasedViewBuilderClient client) {
        GWT.runAsync(new RunAsyncCallback() {
            public void onFailure(Throwable err) {
                client.onUnavailable();
                throw new IllegalStateException(err);
            }

            public void onSuccess() {
                GWTVizPlot.createAsync(new GWTVizPlot.GWTVizPlotClient() {
                    @Override
                    public void onSuccess(GWTVizPlot gwtVizPlot) {
                        if (instance == null) {
                            instance = new TemplateBasedViewBuilder(gwtVizPlot);
                        }
                        client.onSuccess(instance);
                    }

                    @Override
                    public void onUnavailable() {
                        throw new IllegalStateException("unable to load plotter");
                    }
                });


            }
        });
    }
765316
private void onConnectEnd(final int rstCode) {
        HMSAgentLog.d("connect end:" + rstCode);

        synchronized (CALLBACK_LOCK) {
            // 回调各个回调接口连接结束
            for (IClientConnectCallback callback : connCallbacks) {
                aSysnCallback(rstCode, callback);
            }
            connCallbacks.clear();

            // 恢复默认不显示
            allowResolveConnectError = false;
        }

        synchronized (STATIC_CALLBACK_LOCK) {
            // 回调各个回调接口连接结束
            for (IClientConnectCallback callback : staticCallbacks) {
                aSysnCallback(rstCode, callback);
            }
            staticCallbacks.clear();
        }
    }
1260028
function RpcTunnel(url, sslSettings) {
		var self = this;
		if (! (this instanceof RpcTunnel)) {
			return new RpcTunnel(url, sslSettings);
		}

		this.transports = {};

		if (!url) {
			throw new Error('Missing url parameter, which should be either a URL or client transport.')
		}

		var transport = null;

		if (typeof url === 'string') {
			var HttpTransport = require('./transports/http');
			transport = new HttpTransport(url, sslSettings);

			// As a special case when adding an HTTP transport, set up the WebSocket transport
			// It is lazy-loaded, so the WebSocket connection is only created if/when the transport is used
			Object.defineProperty(this.transports, 'ws', {
				enumerable: true, // JSWS-47 ensure we can discover the ws transport
				get: (function () {
					var webSocketTransport;
					var WebSocketTransport = require('./transports/ws');
					return function () {
						if (!webSocketTransport) {
							webSocketTransport = new WebSocketTransport(url, sslSettings);
							webSocketTransport.on('event', function (e) {
								self.emit('event', e);
							});
						}
						return webSocketTransport;
					};
				}())
			});
		} else {
			transport = url;
			transport.on('event', function (e) {
				self.emit('event', e);
			});
		}

		transport.on('error', function(err) {
			self.emit('error', err);
		});

		this.url = transport.url;
		this.transports[transport.name] = transport;
	}
486360
private void showFinal(boolean show, Activity activity, HuaweiApiClient client) {

        // 保存当前浮标显示状态，以便出现异常浮标消失后，能够恢复
        isCurFloatShow = show;

        Activity curActivity = activity!=null ? activity : ActivityMgr.INST.getLastActivity();

        // 取得当前 activity 用于展示浮标
        if (curActivity == null) {
            HMSAgentLog.e("activity is null");
            return;
        }

        if (show) {
            if (client == null || !client.isConnected()) {
                HMSAgentLog.e("client is invalid");
                ApiClientMgr.INST.connect(new EmptyConnectCallback("try connect end when show float:"), false);
                return;
            }

            HMSAgentLog.d("show begin");
            PendingResult<ShowFloatWindowResult> pendingRst = HuaweiGame.HuaweiGameApi.showFloatWindow(client, curActivity);
            pendingRst.setResultCallback(new ShowFloatWindowCallBack());
        } else {
            HMSAgentLog.d("hide");
            HuaweiGame.HuaweiGameApi.hideFloatWindow(client, curActivity);
        }
    }
12894
@Override
    public ResourceSet<SyncListPermission> read(final TwilioRestClient client) {
        return new ResourceSet<>(this, client, firstPage(client));
    }
782946
private HuaweiApiClient resetApiClient(){
        if (context == null) {
            HMSAgentLog.e("HMSAgent not init");
            return null;
        }

        synchronized (APICLIENT_LOCK) {
            if (apiClient != null) {
                // 对于老的apiClient，1分钟后才丢弃，防止外面正在使用过程中这边disConnect了
                disConnectClientDelay(apiClient, 60000);
            }

            HMSAgentLog.d("reset client");

            // 这种重置client，极端情况可能会出现2个client都回调结果的情况。此时可能出现rstCode=0，但是client无效。
            // 因为业务调用封装中都进行了一次重试。所以不会有问题
            HuaweiIdSignInOptions signInOptions = new
                    HuaweiIdSignInOptions.Builder(HuaweiIdSignInOptions.DEFAULT_SIGN_IN).requestAccessToken().requestOpenId().requestUnionId().build();
            apiClient = new HuaweiApiClient.Builder(context)
                    .addApi(HuaweiPay.PAY_API)
                    .addApi(HuaweiGame.GAME_API)
                    .addApi(HuaweiSns.API)
                    .addApi(HuaweiId.SIGN_IN_API, signInOptions)
                    .addApi(HuaweiPush.PUSH_API)
                    .addConnectionCallbacks(INST)
                    .addOnConnectionFailedListener(INST)
                    .build();
            return apiClient;
        }
    }
24447
private Page<AvailablePhoneNumberCountry> pageForRequest(final TwilioRestClient client, final Request request) {
        Response response = client.request(request);

        if (response == null) {
            throw new ApiConnectionException("AvailablePhoneNumberCountry read failed: Unable to connect to server");
        } else if (!TwilioRestClient.SUCCESS.apply(response.getStatusCode())) {
            RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper());
            if (restException == null) {
                throw new ApiException("Server Error, no content");
            }

            throw new ApiException(
                restException.getMessage(),
                restException.getCode(),
                restException.getMoreInfo(),
                restException.getStatus(),
                null
            );
        }

        return Page.fromJson(
            "countries",
            response.getContent(),
            AvailablePhoneNumberCountry.class,
            client.getObjectMapper()
        );
    }
261291
private void onSignInResult(int rstCode, SignInHuaweiId result) {
        HMSAgentLog.i("signIn:callback=" + StrUtils.objDesc(handler) +" retCode=" + rstCode);
        if (handler != null) {
            new Handler(Looper.getMainLooper()).post(new CallbackResultRunnable<SignInHuaweiId>(handler, rstCode, result));
            handler = null;
        }
        signInResultForDispose = null;
        retryTimes = MAX_RETRY_TIMES;
    }
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);
                }
            }
        });
    }
167405
@Override
    public void onConnect(int rst, HuaweiApiClient client) {

        HMSAgentLog.d("onConnect:" + rst);

        if (client == null || !ApiClientMgr.INST.isConnect(client)) {
            HMSAgentLog.e("client not connted");
            onProductDetailResult(rst, null);
            return;
        }

        // 调用HMS-SDK getOrderDetail 接口
        PendingResult<ProductDetailResult> checkPayResult = HuaweiPay.HuaweiPayApi.getProductDetails(client, productDetailReq);
        checkPayResult.setResultCallback(new ResultCallback<ProductDetailResult>() {
            @Override
            public void onResult(ProductDetailResult result) {

                if (result == null) {
                    HMSAgentLog.e("result is null");
                    onProductDetailResult(HMSAgent.AgentResultCode.RESULT_IS_NULL, null);
                    return;
                }

                Status status = result.getStatus();
                if (status == null) {
                    HMSAgentLog.e("status is null");
                    onProductDetailResult(HMSAgent.AgentResultCode.STATUS_IS_NULL, null);
                    return;
                }

                int rstCode = status.getStatusCode();
                HMSAgentLog.d("status=" + status);
                // 需要重试的错误码，并且可以重试
                if ((rstCode == CommonCode.ErrorCode.SESSION_INVALID
                        || rstCode == CommonCode.ErrorCode.CLIENT_API_INVALID) && retryTimes > 0) {
                    retryTimes--;
                    connect();
                } else {
                    onProductDetailResult(rstCode, result);
                }
            }
        });
    }
592820
function TransmitOralProcessWithInit(client, req) {
    return new Promise(function (resolve, reject) {
        // 通过client对象调用想要访问的接口，需要传入请求对象以及响应回调函数
        client.TransmitOralProcessWithInit(req, function (err, response) {
            if (err) {
                reject(err)
                return;
            }
            // 请求正常返回，打印response对象
            resolve(response)
        });
    })
}