0

AsyncTaskをサポートするクラスを作成しようとしましたが、惨めに失敗しました。後で、このクラスのスーパークラスを作成し、メインクラスに次のように追加しました。

//subclass of the superclass CustomHttpClient
CustomHttpClient2 cl= new CustomHttpClient2();
cl.execute();
response = cl.executeHttpPost("http://ironis.dyndns.org/aeglea/android/log.php", postParameters);

エラーメッセージはandroid.os.NetworkOnMainThreadExceptionです

変換したいクラスはこれです(sdk 7で使用しましたが、14に移動しましたが、失敗します)

public class CustomHttpClient2 (extends CustomHttpClient)<<I used it without this {

 public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
    private static HttpClient mHttpClient;


    /**
     * Get our single instance of our HttpClient object.
     *
     * @return an HttpClient object with connection parameters set
     */
    private static HttpClient getHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
        }
        return mHttpClient;
    }

    /**
     * Performs an HTTP Post request to the specified url with the
     * specified parameters.
     *
     * @param url The web address to post the request to
     * @param postParameters The parameters to send via the request
     * @return The result of the request
     * @throws Exception
     */
    public JSONObject executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
        BufferedReader in = null;
        HttpEntity he=null;
        JSONObject jo=null;

        try {
            HttpClient client = getHttpClient();
            HttpPost request = new HttpPost(url);
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            //mine
            he=response.getEntity();
            jo=new JSONObject(EntityUtils.toString(he));
            //end mine

            return jo;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url The web address to post the request to
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpGet(String url) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

CustomHttpClientを使用する他のクラスは以下のとおりです

public class CustomHttpClient extends AsyncTask<HttpClient,String,String> {
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
private static HttpClient mHttpClient;



protected HttpClient doInBackground(String... params) {
    if (mHttpClient == null) {
        mHttpClient = new DefaultHttpClient();
        final HttpParams params1 = mHttpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params1, HTTP_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params1, HTTP_TIMEOUT);
        ConnManagerParams.setTimeout(params1, HTTP_TIMEOUT);
    }
    return mHttpClient;
}



@Override
protected String doInBackground(HttpClient... params) {
    // TODO Auto-generated method stub
    return null;
}




}

私への愛はありますか?

4

3 に答える 3

2

おそらく、非同期タスクは次のようになります。

public class CustomHttpTask extends AsyncTask<CustomHttpClient2,String,String> {
   public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds


   @Override
   protected String doInBackground(HttpClient... params) {
       //subclass of the superclass CustomHttpClient
       CustomHttpClient2 cl= params[0];
       response = cl.executeHttpPost("http://ironis.dyndns.org/aeglea/android/log.php", postParameters);

        // say, you need response string back

        return response.toString();
}

    @Override
    protected void onPostExecute(String result) {
        showDialog("Downloaded " + result + " response");
    }
}

そしてそれを次のように呼びます:

CustomHttpTask task = new CustomHttpTask();
task.execute(new CustomHttpClient2());

そして、AndroidはNetworkOnMainThreadExceptionをスローする正しい方法を実行しています。次に、UIスレッドでネットワーク要求を実行して、接続が遅いANRを回避しようとします。

于 2012-08-24T02:28:35.753 に答える
0

doInBackground正しい方法を上書きしないことと関係があるのではないかと思います。代わりに、さまざまなパラメータタイプでオーバーロードしています。クラス定義(例)のHttpClientとStringを切り替えて...extends AsyncTask<String,String,HTTPClient>、正しいパラメータを渡し、適切な結果を返すことができるようにします。

[編集]あなたの質問の本質を理解したかどうかはわかりませんが、私のポイントは、別のスレッドで実行される唯一のもの(IOを挿入する必要があります)は正しいdoInBackgroundメソッドのものです。

于 2012-08-24T02:22:07.333 に答える
0

同様の問題を抱えている人は誰でも、私の解決策を投稿します。

@sandrstarのソリューションを変更し、それを実行しました

public class CustomHttpTask extends AsyncTask<Object,String,JSONObject> {
   public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
   private JSONObject response = null;

   @Override
   protected JSONObject doInBackground(Object... params) {
       //subclass of the superclass CustomHttpClient
       //CustomHttpClient cl= (CustomHttpClient) params[0];
       String url = (String) params[0];
       ArrayList<NameValuePair> postParameters = (ArrayList<NameValuePair>) params[1];
    try {
        response = CustomHttpClient.executeHttpPost(url, postParameters);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

        // say, you need response string back

        return response;
}

    @Override
    protected void onPostExecute(JSONObject result) {

    }
    public JSONObject getval(){
        return response;
    }

}

これで、異なるURLで複数の投稿を行うことができます。問題は、jsonオブジェクトが必要なことです。2つの方法があります。私が行ったように関数を作成します。または、AsyncTaskのget()関数を使用します

CustomHttpTask asdf = new CustomHttpTask();
response = asdf.execute("http://192.168.1.4/aeglea/android/log.php", postParameters).get();

これが最初に実行され、終了するとget部分が実行されます。;)

于 2012-08-24T22:38:50.670 に答える