如何在android中的其他Activity中调用其他类的AsynkTask?

时间:2016-05-06 03:37:17

标签: android

我有一个名为 CRegistrationScreen 的类,其中包含名为 GenerateOtp 的AsynkTask类,我有一个名为 {的类{1}} 我想要执行CGenerateOtp。

我该怎么做?

这是我的CREgistration类AsynkTask代码: -

Login

这是我的登录类代码:

// request to server for otp generation....................
private class CGenerateOtp extends AsyncTask<String, Void, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        m_ProgressView.setVisibility(View.VISIBLE);// make progress view Visible to user while doing background process

    }

    @SuppressWarnings("deprecation")
    @Override
    protected String doInBackground(String... params) {
        InputStream inputStream;
        try {
            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();
            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(s_szRequestOtpUrl);
            String json;// storing json object
            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();// json object creation
            jsonObject.put("agentCode", s_szResponseMobileNum);// put mobile number
            jsonObject.put("pin", s_szResponseEncryPassword);// put password
            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();
            if (BuildConfig.klogInfo)// print json request to server
                Log.d(TAG, "Server Request:-" + json);
            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);
            // 6. set httpPost Entity
            httpPost.setEntity(se);
            // 7. Set some headers to inform server about the type of the content
            httpPost.setHeader("Content-type", "application/json");
            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            // 9. receive response as inputStream
            inputStream = entity.getContent();// get content in response
            if (BuildConfig.klogInfo)
                Log.d(TAG, "Input stream ...." + inputStream.toString());
            Log.d(TAG, "Response...." + httpResponse.toString());

            StatusLine statusLine = httpResponse.getStatusLine();// get status code
            if (BuildConfig.klogInfo)
                Log.d(TAG, "status line :-" + statusLine);

            ////Log.d("resp_body", resp_body.toString());
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {// check if code == 200
                // 10. convert response  to string and save in result varibale
                s_szResult = CJsonsResponse.convertInputStreamToString(inputStream);
                if (BuildConfig.klogInfo)
                    Log.d(TAG, "Server Response.." + s_szResult);
            } else
                s_szResult = "Did not work!";
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 11. return s_szResult
        return s_szResult;
    }

    @Override
    protected void onPostExecute(final String response) { // Update UI
        super.onPostExecute(response);
        m_ProgressView.setVisibility(View.GONE);// hiding progressview.....
        try {
            s_m_oResponseobject = new JSONObject(response);// get response from server in json
            getResponse();// server based condition
        } catch (JSONException e) {// handling exception occured by server
            e.printStackTrace();
        }

    }

    private void getResponse() throws JSONException {/// getting response from server .............
        //if response from server is success
        if (s_m_oResponseobject.getString("resultDesc").equalsIgnoreCase("Transaction Successful")) {

            m_oOpenDialog.dismiss();// dismiss dialog
            // and got to OTP verification
            getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new COtpAutoVerificationScreen()).commit();
        }
    }

}

2 个答案:

答案 0 :(得分:1)

<强> 1 即可。将 CGenerateOtp 移出 CRegistrationScreen 类,为asynck创建单独的java文件CGenerateOtp.java并执行任何类

<强> 2 即可。在CGenerateOtp的构造函数中传递活动和m_ProgressView等变量,如: public CGenerateOtp(Activity activity,m_ProgressView,....){}

<强> CGenerateOtp.java

private class CGenerateOtp extends AsyncTask<String, Void, String> {

    Activity activity;
    View m_ProgressView;
    public CGenerateOtp(Activity activity, View m_ProgressView) {
        this.activity = activity;
        this.m_ProgressView = m_ProgressView;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        m_ProgressView.setVisibility(View.VISIBLE);// make progress view Visible to user while doing background process

    }

    @SuppressWarnings("deprecation")
    @Override
    protected String doInBackground(String... params) {
        InputStream inputStream;
        try {
            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();
            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(s_szRequestOtpUrl);
            String json;// storing json object
            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();// json object creation
            jsonObject.put("agentCode", s_szResponseMobileNum);// put mobile number
            jsonObject.put("pin", s_szResponseEncryPassword);// put password
            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();
            if (BuildConfig.klogInfo)// print json request to server
                Log.d(TAG, "Server Request:-" + json);
            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);
            // 6. set httpPost Entity
            httpPost.setEntity(se);
            // 7. Set some headers to inform server about the type of the content
            httpPost.setHeader("Content-type", "application/json");
            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            // 9. receive response as inputStream
            inputStream = entity.getContent();// get content in response
            if (BuildConfig.klogInfo)
                Log.d(TAG, "Input stream ...." + inputStream.toString());
            Log.d(TAG, "Response...." + httpResponse.toString());

            StatusLine statusLine = httpResponse.getStatusLine();// get status code
            if (BuildConfig.klogInfo)
                Log.d(TAG, "status line :-" + statusLine);

            ////Log.d("resp_body", resp_body.toString());
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {// check if code == 200
                // 10. convert response  to string and save in result varibale
                s_szResult = CJsonsResponse.convertInputStreamToString(inputStream);
                if (BuildConfig.klogInfo)
                    Log.d(TAG, "Server Response.." + s_szResult);
            } else
                s_szResult = "Did not work!";
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 11. return s_szResult
        return s_szResult;
    }

    @Override
    protected void onPostExecute(final String response) { // Update UI
        super.onPostExecute(response);
        m_ProgressView.setVisibility(View.GONE);// hiding progressview.....
        try {
            s_m_oResponseobject = new JSONObject(response);// get response from server in json
            getResponse();// server based condition
        } catch (JSONException e) {// handling exception occured by server
            e.printStackTrace();
        }

    }

    private void getResponse() throws JSONException {/// getting response from server .............
        //if response from server is success
        if (s_m_oResponseobject.getString("resultDesc").equalsIgnoreCase("Transaction Successful")) {

            m_oOpenDialog.dismiss();// dismiss dialog
            // and got to OTP verification
            activity.getSupportFragmentManager().beginTransaction().replace(R.id.container, new COtpAutoVerificationScreen()).commit();
        }
    }

}

答案 1 :(得分:0)

尝试将AsyncTask的类访问修饰符从private更改为public static,然后使用类似的方式调用它(基于代码命名约定):

new CRegistrationScreen.CGenerateOtp().execute();

来自您想要的Activity

小心尝试。如果有事情出现,请告诉我。干杯!