通过asynctask“下载”的文件保存为0

时间:2013-11-07 16:17:14

标签: android android-asynctask download

这是我用来下载文件的代码:

package com.mynavy;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import java.net.*;
import android.os.*;
import java.io.*;


public class YNrank extends Activity {
    Button E4;
    String url1 = "http://www.mambazham.com/uploaded_files/downloads/download.pdf";
    Button prtbtn;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rank_select);
        addListenerOnButton();      
    }
    public void addListenerOnButton() 

      { 
              E4 = (Button) findViewById(R.id.E4);
              E4.setOnClickListener(new OnClickListener() 

              {
//BIBS BUTTON!
                public void onClick(View v){
                    new download().execute(url1);
                    DialogFragment newFragment = new open();
                    newFragment.show(getFragmentManager(), "YN3");
                    }

                class download extends AsyncTask<String, Integer, String>{
                protected String doInBackground(String... url1) {                       
                         try {

                         String fileName="E4";
                         String fileExtension=".pdf";

//                     download pdf file.

                            URL url = new URL("http://www.education.gov.yk.ca/pdf/pdf-test.pdf");
                            HttpURLConnection c = (HttpURLConnection) url.openConnection();
                            c.setRequestMethod("GET");
                            c.setDoOutput(true);
                            c.connect();
                            String PATH = Environment.getExternalStorageDirectory() + "/mydownload/";
                            File file = new File(PATH);
                            file.mkdirs();
                            File outputFile = new File(file, fileName+fileExtension);
                            FileOutputStream fos = new FileOutputStream(outputFile);
                            InputStream is = c.getInputStream();
                            byte[] buffer = new byte[1024];
                            int len1 = 0;
                            while ((len1 = is.read(buffer)) != -1) {
                                fos.write(buffer, 0, len1);
                            }
                            fos.flush();
                            fos.close();
                            is.close();

                           System.out.println("--pdf downloaded--ok--"+ url);
                        } catch (Exception e) {
                            e.printStackTrace();

                        }
                    return null;


                    }



                } 

                class open extends DialogFragment {
                    public Dialog onCreateDialog(Bundle savedInstanceState) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        builder.setMessage(R.string.YN3open)
                               .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                   public void onClick(DialogInterface dialog, int id) {
                                   }
                               });
                               builder.setPositiveButton(R.string.open, new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // TODO Auto-generated method stub
                                    File e4pdf = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/mydownload/E4.pdf");
                                    if(e4pdf.exists()){
                                        Uri path = Uri.fromFile(e4pdf);
                                        Intent pdfintent = new Intent(Intent.ACTION_VIEW);
                                        pdfintent.setDataAndType(path, "application/pdf");
                                        pdfintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                        try{
                                            startActivity(pdfintent);
                                        } catch(ActivityNotFoundException e) {
                                            Toast.makeText(YNrank.this, "No Application Available To View PDF File.", Toast.LENGTH_LONG).show();

                                        }}
                                        else {
                                            Toast.makeText(YNrank.this, "File Not Found", Toast.LENGTH_LONG).show();
                                        }



                                }
                            });
                               return builder.create();
                    }};});





}}

文件已创建,但未写入。它最终作为一个空白的pdf文件,我无法打开,因为它的文件大小为0.我尝试了几种不同的方法,他们要么这样做,要么根本没有。

Also I have the following permissions:


<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

1 个答案:

答案 0 :(得分:1)

public void onClick(View v){
      new download().execute(url1);
      DialogFragment newFragment = new open();
      newFragment.show(getFragmentManager(), "YN3");
}

您必须等待异步任务完成。覆盖asynctask的onPostExecute触发器并在那里调用对话框片段。