为什么我的活动上有NetworkOnMainThreadException?

时间:2014-08-01 15:46:55

标签: android networkonmainthread

我有一个下载文件的活动,并且在执行活动一段时间后我在onPostExecute()上获得了NetworkOnMainThreadException。该文件也未完全下载。我无法找到我错的地方。这是我的代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_activity1);

    RetrieveFeedTask download = new RetrieveFeedTask();
    download.execute();
}

class RetrieveFeedTask extends AsyncTask<String, Void, InputStream> {

    private Exception exception;

    protected InputStream doInBackground(String... urls) {
        try {
             OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                  .url(URL)
                  .build();

              Response response = client.newCall(request).execute();
              InputStream asd = response.body().byteStream();
              System.out.println(asd + " vaslisiss");
                          return asd;
        } catch (Exception e) {
            System.out.println("helloooo");
            this.exception = e;;
            return null;
        }
    }

    protected void onPostExecute(InputStream feed) {
        Log.e("mactibiti", "exception", exception); 
        // TODO: do something with the feed
        if(exception == null)
            System.out.println("asdasdasdasdasdasdads");
        try{
        File file = new File(Environment.getExternalStorageDirectory() + "/downloaded_file.xml");
        FileOutputStream fileOutput = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int bufferLength = 0;

        while ( (bufferLength = feed.read(buffer)) > 0 ) {
            fileOutput.write(buffer, 0, bufferLength);
        }
        //close the output stream when complete //
        fileOutput.close();
        feed.close();
        }
        catch(Exception e){
            Log.e("filex", "ioexc", e);
        }

    }
}}

1 个答案:

答案 0 :(得分:3)

protected void onPostExecute(InputStream feed) {

feed是您正在通过Http调用

读取的InputStream