簡體   English   中英

如何在Android的其他Activity中調用其他類的AsynkTask?

[英]How to call AsynkTask of other class in other Activity in android?

我有一個名為CRegistrationScreen的類,其中包含一個名為GenerateOtp AsynkTask類,我有一個名為Login的類,我想在其中執行CGenerateOtp。

我怎樣才能做到這一點?

這是我的CREgistration類AsynkTask代碼:-

// 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();
        }
    }

}

這是我的登錄類代碼:

public class Login extends Fragment {
  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return super.onCreateView(inflater, container, savedInstanceState);

    // here I want to execute CRegistration AsynkTask  
  }
}

1 CGenerateOtp移出CRegistrationScreen類,為異步創建單獨的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();
        }
    }

}

嘗試將AsyncTask類訪問修飾符從private更改為public static然后使用類似這樣的名稱(基於您的代碼命名約定)進行調用:

new CRegistrationScreen.CGenerateOtp().execute();

從您所需的Activity

小心嘗試一下。 讓我知道是否有事情發生。 干杯!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM