繁体   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