Как добавить AsyncTask в соединение HttpURLC?

java android android-asynctask

19560 просмотра

3 ответа

Я устанавливаю соединение с сервером, моя проблема в том, что мне нужно поставить AsyncTaskкод в моем коде, потому что он не работает в версии SDK 10. Я не хочу использовать StrictMode.ThreadPolicy.

public class TestConnection extends Activity {

@Override
public void onCreate(Bundle cbundle) {
    super.onCreate(cbundle);

    ConnectivityManager aConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo aNetworkInfo = aConnectivityManager.getActiveNetworkInfo();
    if (aNetworkInfo != null && aNetworkInfo.isConnected()){
        Toast.makeText(this, "Internet Connected", Toast.LENGTH_LONG).show();
    }else{
        Toast.makeText(this, "Internet Connection Timeout", Toast.LENGTH_LONG).show();
    }


    URL aURL;
    /* Will be filled and displayed later. */
    String aString = null;

    /* We will show the data we read in a TextView. */
    TextView aTextView = new TextView(this);
    try {

        /* Define the URL we want to load data from. */
        aURL = new URL(
                "http://url");

        /* Open a connection to that URL. */
        final HttpURLConnection aHttpURLConnection = (HttpURLConnection) aURL.openConnection();

        /* Define InputStreams to read from the URLConnection. */
        InputStream aInputStream = aHttpURLConnection.getInputStream();
        BufferedInputStream aBufferedInputStream = new BufferedInputStream(
                aInputStream);

        /* Read bytes to the Buffer until there is nothing more to read(-1) */
        ByteArrayBuffer aByteArrayBuffer = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = aBufferedInputStream.read()) != -1) {
            aByteArrayBuffer.append((byte) current);
        }


        /* Convert the Bytes read to a String. */
        aString = new String(aByteArrayBuffer.toByteArray());
    } catch (Exception aException) {

        /* On any Error we want to display it. */
        aString = aException.getMessage();
    }

    /* Show the String on the GUI. */
    aTextView.setText(aString);
    this.setContentView(aTextView);

}

}
Автор: Con Nectify Источник Размещён: 12.11.2019 09:31

Ответы (3)


3 плюса

private class ConnectionTask extends AsyncTask<String, Void, String>{
    @Override
    protected byte[] doInBackground(String... urls) {
            try {
    aURL = new URL(
            urls[0]);

    /* Open a connection to that URL. */
    final HttpURLConnection aHttpURLConnection = (HttpURLConnection) aURL.openConnection();

    /* Define InputStreams to read from the URLConnection. */
    InputStream aInputStream = aHttpURLConnection.getInputStream();
    BufferedInputStream aBufferedInputStream = new BufferedInputStream(
            aInputStream);

    /* Read bytes to the Buffer until there is nothing more to read(-1) */
    ByteArrayBuffer aByteArrayBuffer = new ByteArrayBuffer(50);
    int current = 0;
    while ((current = aBufferedInputStream.read()) != -1) {
        aByteArrayBuffer.append((byte) current);
    }


    /* Convert the Bytes read to a String. */
    aString = new String(aByteArrayBuffer.toByteArray());               } catch (IOException e) {
                Log.d(TAG, e.toString());
            }
        return aString;
    }

    @Override
    protected void onPostExecute(String result) {
               // result is what you got from your connection
aTextView.setText(result);

    }

}

Как это назвать:

                        ConnectionTask task = new ConnectionTask();
                        String[] params = new String[2];
                        params[0] = url;
                        params[1] = somethingelseifneeded;
                        task.execute(params);
Автор: Lazy Ninja Размещён: 03.08.2012 06:31

1 плюс

В oncreate () вы можете использовать так:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        StrictMode.ThreadPolicy policy = new       
                      StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
              new MyAsynTask().execute(null, null, null);
      }

Затем в AsynTask сделайте также:

class MyAsynTask extends AsyncTask<Long, Integer, Integer> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected <Type> doInBackground(Long... params) {
            URL ur_url = newURL(http://....) 
                   // do the works on url.....
            return <tuped>result;
        }

        @Override
        protected void onPostExecute(Integer result) {
            // set the results in Ui

        }
    }
Автор: mainu Размещён: 03.08.2012 06:31

0 плюса

См. Ниже код

new FetchRSSFeeds().execute();


private class FetchRSSFeeds extends AsyncTask<String, Void, Boolean> {

    private ProgressDialog dialog = new ProgressDialog(HomeActivity.this);

    /** progress dialog to show user that the backup is processing. */
    /** application context. */

    protected void onPreExecute() {
        this.dialog.setMessage(getResources().getString(
                R.string.Loading_String));
        this.dialog.show();
    }

    protected Boolean doInBackground(final String... args) {
        try {

            /**
             * Write your URL connection code and fetch data here
             */

            return true;
        } catch (Exception e) {
            Log.e("tag", "error", e);
            return false;
        }
    }

    @Override
    protected void onPostExecute(final Boolean success) {

        if (dialog.isShowing()) {
            dialog.dismiss();
        }

             /* Show the String on the GUI. */
                    aTextView.setText(aString);
                    this.setContentView(aTextView);

    }
}
Автор: Nirali Размещён: 03.08.2012 06:31
Вопросы из категории :
32x32