调用异步任务并等待回答

时间:2016-05-18 02:13:59

标签: android

您好我正在尝试检查用户名是否可用但必须通过异步任务进行检查。尝试了一些方法,但无法做到这一点。所以,我带来了这个:

异步任务在普通类中,因此将调用新实例,调用异步任务(checkusername),然后等待异步任务完成(在postexecute上,它将更新公共变量,' resultOut&# 39)。在活动时,为了防止锁定,在退出之前循环到1000或resultOut。

我一直在' resultOut'假的。这是代码:

urlConnection url = new urlConnection();

    if(url.isConnected(view.getContext())) {
        Toast.makeText(getApplicationContext(), "connected ", Toast.LENGTH_LONG).show();
        boolean result=false;
        url.checkUserName(user_name);
        int i = 0;

        while (!result && i!=1000){
            i++;
            result=url.resultOut;
        } 

这是urlconnection类(已编辑)

private void connectUrl(String action, String user_name, String pwd) {
    String urlParam = null;
    strAction=action;

    switch (action){
        case "update":
            urlParam = "/test.php?action=update&user_id=7&lat="+latitude+"&lon="+longitude;
            break;
        case "locate":
            urlParam = "/test.php?action=locate&user_id=7";
            break;
        case "insert":
            urlParam = "/test.php?action=insert&user_name="+user_name+"&pwd="+pwd;
            break;
        case "check":
            urlParam = "/test.php?action=check&user_name="+user_name;

    }
    //Toast.makeText(, "Connecting to site: " + WB_URL + urlParam, Toast.LENGTH_LONG).show();
    new DownloadWebpageTask().execute(WB_URL + urlParam);

}
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {

        // params comes from the execute() call: params[0] is the url.
        try {
            return downloadUrl(urls[0]);
        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {

        result=result.trim();

        switch (strAction){
            case "update":
                int i = Integer.parseInt(result);
                if (i > 0) {
                    //Toast.makeText(getApplicationContext(), "Update successful", Toast.LENGTH_LONG).show();
                }else{
                    //Toast.makeText(getApplicationContext(), "Update failed", Toast.LENGTH_LONG).show();
                }
                break;
            case "locate":
                String[] s = result.split(",");


            case "insert":

                break;
            case "check":
                int x = Integer.parseInt(result);
                resultOut=true;
                //Toast.makeText(getApplicationContext(), "Check Result: "+x, Toast.LENGTH_LONG).show();
                if (x==0){
                    //cannot locate name so, name usable
                    isUserNameUsed=false;
                }else{
                    isUserNameUsed=true;
                }

        }

        //showLocation(null);
    }
}
private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;
    // Only display the first 500 characters of the retrieved
    // web page content.
    int len = 500;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        Log.d(DEBUG_TAG, "The response is: " + response);
        is = conn.getInputStream();

        // Convert the InputStream into a string
        String contentAsString = readIt(is, len);
        return contentAsString;


        // Makes sure that the InputStream is closed after the app is
        // finished using it.
    } finally {
        if (is != null) {
            is.close();
        }
    }
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
    Reader reader = null;
    reader = new InputStreamReader(stream, "UTF-8");
    char[] buffer = new char[len];
    reader.read(buffer);
    return new String(buffer);
}

}

帮助表示感谢,提前谢谢。理查德

1 个答案:

答案 0 :(得分:0)

你的实用程序asyncTask类,你必须在你的片段或活动中实现它。 apiKey用于检查你呼叫的api的响应。

public class UtilityAsyncRequest extends AsyncTask<String, Integer, String> {

    private final OnAsyncRequestComplete caller;
    private String requestType = "";
    private String strJsonData = "";
    private int apiKey = 0;

    /**
     * @param caller      callback interface for request
     * @param requestType GET POST
     * @param jsonStringData     payload with request type POST
     * @param apiKey      apiKey
     */

    public UtilityAsyncRequest(OnAsyncRequestComplete caller, String requestType,
                               String jsonStringData, int apiKey) {
        this.caller = caller;
        this.apiKey = apiKey;

        if (requestType.equalsIgnoreCase("Get")) {
            this.requestType = "Get";
        } else if (jsonStringData != null && requestType.equalsIgnoreCase("Post")) {
            this.requestType = "Post";
            this.strJsonData = jsonStringData;
        }
    }

    public String doInBackground(String... urls) {
        // callApi url pointing to entry point of API

        String address = urls[0];
        String response = "";
        if (requestType.equalsIgnoreCase("Post")) {
            response = Connection.postAPIResponse(address, strJsonData);
        } else if (requestType.equalsIgnoreCase("Get")) {
            response = Connection.getAPIResponse(address);
        }

        return response;
    }

    public void onPreExecute() {
        if(caller!=null)
            caller.onPreExecute(apiKey);

    }

    public void onPostExecute(String response) {
        if (caller != null)
                caller.onPostExecute(response, apiKey);

    }

    protected void onCancelled(String response) {
        if(caller!=null)
        caller.onCancelled(apiKey);
    }
    // Interface to be implemented by calling activity
    public interface OnAsyncRequestComplete {
        void onPreExecute(int api);
        void onPostExecute(String response, int api);
        void onCancelled(int api);
    }
}

现在要进行异步请求,您可以在活动中执行此操作。通过实现接口。

public class MainActivity extends Activity implements UtilityAsyncRequest.OnAsyncRequestComplete{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //first Api Call
        UtilityAsyncRequest utilityAsyncRequest=new UtilityAsyncRequest(this,"GET",null,1);
        utilityAsyncRequest.execute("https://www.google.co.in/?gws_rd=ssl");
        //Second Api Call
        utilityAsyncRequest=new UtilityAsyncRequest(this,"GET",null,2);
        utilityAsyncRequest.execute("https://www.google.co.in/?gws_rd=ssl");
    }

    @Override
    public void onPreExecute(int api) {
        switch (api){
            case 1:
                //first api call pre show Loading dialog else whatever you want
                break;
            case 2:
                //second api call pre
                break;
        }
    }

    @Override
    public void onPostExecute(String response, int api) {
        switch (api){
            case 1:
                //first api call response
                break;
            case 2:
                //second api call response
                break;
        }

    }

    @Override
    public void onCancelled(int api) {

    }
}

用于处理接收和发布数据。

public class Connection {
    // Private constructor prevents instantiation from other classes
    private Connection() {

    }

    public static String postAPIResponse(String url, String data) {

        HttpURLConnection con = null;
        InputStream inputStream;
        StringBuffer responses = null;
        try {
            URL urlObject = new URL(url);
            con = (HttpURLConnection) (urlObject.openConnection());

            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            con.setRequestProperty("Content-Length", Integer.toString(data.getBytes().length));
            con.setRequestProperty("Content-Language", "en-US");
            if (Cookie.getCookie() != null)
                con.addRequestProperty("Cookie", Cookie.getCookie());

            con.setUseCaches(false);
            con.setDoInput(true);
            con.setDoOutput(true);

            //Send request
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(data);
            wr.flush();
            wr.close();

            //Get Response
            if (con.getResponseCode() == 200) {
                if (Cookie.getCookie() == null)
                    Cookie.setCookie(con.getHeaderField("Set-Cookie"));


                InputStream is = con.getInputStream();
                BufferedReader rd = new BufferedReader(new InputStreamReader(is));
                String line;
                responses = new StringBuffer();
                while ((line = rd.readLine()) != null) {
                    responses.append(line);
                }
                rd.close();

            } else {

                inputStream = new BufferedInputStream(con.getErrorStream());
                return convertInputStreamToString(inputStream);
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            assert con != null;
            con.disconnect();
        }
        return responses != null ? responses.toString() : "";
    }

    public static String getAPIResponse(String urlName) {
        String response = null;
        HttpURLConnection con = null;
        InputStream inputStream;

        try {

            URL url = new URL(urlName);
            con = (HttpURLConnection) (url.openConnection());

            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            if (Cookie.getCookie() != null)
                con.addRequestProperty("Cookie", Cookie.getCookie());

            int statusCode = con.getResponseCode();
            if (statusCode == 200) {
                inputStream = new BufferedInputStream(con.getInputStream());
                response = convertInputStreamToString(inputStream);
                if (Cookie.getCookie() == null)
                    Cookie.setCookie(con.getHeaderField("Set-Cookie"));
            } else {
                inputStream = new BufferedInputStream(con.getErrorStream());
                response = convertInputStreamToString(inputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            assert con != null;
            con.disconnect();
        }
        return response != null ? response : "";
    }

    static public String convertInputStreamToString(InputStream inputStream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        String result = "";
        while ((line = bufferedReader.readLine()) != null) {
            result += line;
        }
            /* Close Stream */
        inputStream.close();
        return result;
    }

}

并处理cookie模型类。

public class Cookie {
    private static String Cookie;
    //private static final com.core.Cookie singleton = new Cookie( );

    /* A private Constructor prevents any other
     * class from instantiating.
     */
    private Cookie() {
    }

    /* Other methods protected by singleton */
    public static String getCookie() {
        return Cookie;
    }

    public static void setCookie(String cookie) {
        Cookie = cookie;
    }
}