Android:将URL代码放在AsyncTask中

时间:2014-04-22 12:04:38

标签: android url android-asynctask

如何将文字放在AsyncTask下面?我的问题是通过直接放置代码我得到一个错误NetworkOnMainThreadException。我需要任何帮助。感谢

try {
    URL myFileUrl = new URL ("http://.../cercanias.png");
    HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
    conn.setDoInput(true);
    conn.connect();

    InputStream is = conn.getInputStream();
    Bitmap bm = BitmapFactory.decodeStream(is);

    FileOutputStream out = new FileOutputStream(getCacheDir() + "cercanias.png");
    bm.compress(Bitmap.CompressFormat.PNG, 90, out);

    SubsamplingScaleImageView imageView = (SubsamplingScaleImageView)findViewById(R.id.imagenNitida);

    imageView.setImageFile(getCacheDir() + "cercanias.png");

    out.close();

    if (savedInstanceState != null &&
            savedInstanceState.containsKey(STATE_SCALE) &&
            savedInstanceState.containsKey(STATE_CENTER_X) &&
            savedInstanceState.containsKey(STATE_CENTER_Y)) {

        imageView.setScaleAndCenter(savedInstanceState.getFloat(STATE_SCALE), 
                new PointF(savedInstanceState.getFloat(STATE_CENTER_X), 
                        savedInstanceState.getFloat(STATE_CENTER_Y)));
    }
} catch (IOException e) {
}

4 个答案:

答案 0 :(得分:2)

 class TestAsyncTask extends AsyncTask<String, Integer, Integer> {

     protected Integer doInBackground(String... strings) {
    // Long running task - say processing of each passed string

     URL myFileUrl = new URL ("http://.../cercanias.png");
     HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
     conn.setDoInput(true);
     conn.connect();

     InputStream is = conn.getInputStream();
     Bitmap bm = BitmapFactory.decodeStream(is);

      FileOutputStream out = new FileOutputStream(getCacheDir() + "cercanias.png");
     bm.compress(Bitmap.CompressFormat.PNG, 90, out);
     out.close();
    return 0;
}


protected void onPostExecute(Integer result){
    Log.d("TestP", "AsyncTask returned : " + result);
 SubsamplingScaleImageView imageView = (SubsamplingScaleImageView)findViewById(R.id.imagenNitida);

imageView.setImageFile(getCacheDir() + "cercanias.png");


if (savedInstanceState != null &&
        savedInstanceState.containsKey(STATE_SCALE) &&
        savedInstanceState.containsKey(STATE_CENTER_X) &&
        savedInstanceState.containsKey(STATE_CENTER_Y)) {

    imageView.setScaleAndCenter(savedInstanceState.getFloat(STATE_SCALE), 
            new PointF(savedInstanceState.getFloat(STATE_CENTER_X), 
                    savedInstanceState.getFloat(STATE_CENTER_Y)));
}
}

答案 1 :(得分:0)

在这里:AsyncTask,preExecute(),postExecute()和doInBackground分为三个步骤。这些名字是不言自明的。 preExecute()表示在执行之前必须完成的所有操作,postExecute执行后的所有操作,doInBackground用于进程,这非常耗时。

简单示例:

public class HeavyProcess extends AsyncTask<Void, Void, Void> {
        ProgressDialog Asycdialog = new ProgressDialog(getActivity());

        protected void onPostExecute(String result) {

            //After execution execute this
            super.onPostExecute(result);
        }

        @Override
        protected void onPreExecute() {
            //Before execution do this, like init a progress dialog
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(Void... params) {
            //Do the time consuming work here
            return "";
        }
    }

现在就是你的情况:创建一个包含所有代码的函数:

public void timeTask(){

try {
    URL myFileUrl = new URL ("put your URL here");
    HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
    conn.setDoInput(true);
    conn.connect();

    InputStream is = conn.getInputStream();
    Bitmap bm = BitmapFactory.decodeStream(is);

    FileOutputStream out = new FileOutputStream(getCacheDir() + "cercanias.png");
    bm.compress(Bitmap.CompressFormat.PNG, 90, out);

    SubsamplingScaleImageView imageView = (SubsamplingScaleImageView)findViewById(R.id.imagenNitida);

    imageView.setImageFile(getCacheDir() + "cercanias.png");

    out.close();


    }
} catch (IOException e) {
}

}

然后从doInBackground()调用timeTask()函数;

答案 2 :(得分:0)

这样做

new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground(Void... arg0) {

                try {
                    URL myFileUrl = new URL("http://.../cercanias.png");
                    HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();

                    InputStream is = conn.getInputStream();
                    Bitmap bm = BitmapFactory.decodeStream(is);

                    FileOutputStream out = new FileOutputStream(getCacheDir() +File.separator+ "cercanias.png");
                    bm.compress(Bitmap.CompressFormat.PNG, 90, out);
                    out.close();
                    conn.disconnect();
                    bm.recycle();

                    return "cercanias.png";

                } catch (IOException e) {
                }
                return null;
            }

            protected void onPostExecute(String result) {
                if (result != null) {
                    SubsamplingScaleImageView imageView = (SubsamplingScaleImageView) findViewById(R.id.imagenNitida);

                    imageView.setImageFile(getCacheDir() +File.separator+ result);

                    if (savedInstanceState != null && savedInstanceState.containsKey(STATE_SCALE) && savedInstanceState.containsKey(STATE_CENTER_X)
                            && savedInstanceState.containsKey(STATE_CENTER_Y)) {

                        imageView.setScaleAndCenter(savedInstanceState.getFloat(STATE_SCALE),
                                new PointF(savedInstanceState.getFloat(STATE_CENTER_X), savedInstanceState.getFloat(STATE_CENTER_Y)));
                    }
                }
            };
        }.execute();

答案 3 :(得分:0)

你只需要将这些代码分成若干部分并将它们装入AsyncTask:

public class checkGB_status_Async extends AsyncTask<Void, Void, Bitmap> {

@Override
protected Bitmap doInBackground(Void... params) {
try {
    URL myFileUrl = new URL ("http://.../cercanias.png");
    HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
    conn.setDoInput(true);
    conn.connect();

    InputStream is = conn.getInputStream();
    Bitmap bm = BitmapFactory.decodeStream(is);

    return bm;
} catch (IOException e) {
}
}

protected void onPostExecute(Bitmap result) {

    FileOutputStream out = new FileOutputStream(getCacheDir() + "cercanias.png");
    result.compress(Bitmap.CompressFormat.PNG, 90, out);

    SubsamplingScaleImageView imageView =       (SubsamplingScaleImageView)findViewById(R.id.imagenNitida);

    imageView.setImageFile(getCacheDir() + "cercanias.png");

    out.close();

    if (savedInstanceState != null &&
            savedInstanceState.containsKey(STATE_SCALE) &&
            savedInstanceState.containsKey(STATE_CENTER_X) &&
            savedInstanceState.containsKey(STATE_CENTER_Y)) {

    imageView.setScaleAndCenter(savedInstanceState.getFloat(STATE_SCALE), 
            new PointF(savedInstanceState.getFloat(STATE_CENTER_X), 
                    savedInstanceState.getFloat(STATE_CENTER_Y)));
}
}