如何从服务器下载pdf文件,将其存储在SD卡中并通过android中的意图查看?

时间:2015-03-15 18:34:37

标签: java android pdf

我已经编写了一个程序,可以将我的pdf文件从服务器下载到我的SD卡中,这是正确的下载,但是当我通过我的pdfviewer查看它时,它说无法打开这个文件。 文件大小也是4.5mb,但是下载到我的sdcards pdf文件夹的pdf大小为0。

private void processPDF(String subject_pdf) {
    new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {
            String result = "";
            StringBuilder builder = new StringBuilder(100000);
            try {
                String URL = 
                "http://192.168.1.3:8082/APP_Server/subject_pdfs_result.jsp? 
                 branch_year="+ type; //type = branches(e.g computers , IT) 
                HttpClient httpclient = new DefaultHttpClient();
                HttpGet httpget = new HttpGet(URL);
                HttpResponse response = httpclient.execute(httpget);
                InputStream is = response.getEntity().getContent();
                BufferedReader buffer = new BufferedReader(new 
                InputStreamReader(is));
                // result = is.toString();
                while ((result = buffer.readLine()) != null) {
                    builder.append(result);
                }

            } catch (Exception ex) {
                ex.printStackTrace();

            }
            return builder.toString().replaceAll("\\<.*?\\>", "");
        }

        @Override
        protected void onPostExecute(String builder) {
            //url has the pdf name 
            name= builder.replace("\t", "");
            image_url = 
            "http://192.168.1.3:8082/APP_Server/Images/Books_Pdf/" + url;
            extStorageDirectory = 
            Environment.getExternalStorageDirectory().toString();
            File folder = new File(extStorageDirectory, "pdf");
            folder.mkdir();
            File file = new File(folder, name);
            try {
                file.createNewFile();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            PDFDownloader.DownloadFile(image_url, file);

            showPdf();

        }

    }.execute(null, null, null);

}

private void showPdf() {
    File file = new File(Environment.getExternalStorageDirectory() + "/pdf/" 
               + name);
    PackageManager packageManager = getPackageManager();
    Intent testIntent = new Intent(Intent.ACTION_VIEW);
    testIntent.setType("application/pdf");
    List list = packageManager.queryIntentActivities(testIntent, 
    PackageManager.MATCH_DEFAULT_ONLY);
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    Uri uri = Uri.fromFile(file);
    intent.setDataAndType(uri, "application/pdf");
    startActivity(Intent.createChooser(intent, "Open File"));

}

PDFDownloader.java

public static void DownloadFile(String fileURL, File directory) {
    try {
        FileOutputStream f = new FileOutputStream(directory);
        URL u = new URL(fileURL);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.connect();

        InputStream in = c.getInputStream();

        byte[] buffer = new byte[1024];
        int len1 = 0;
        while ((len1 = in.read(buffer)) > 0) {
            f.write(buffer, 0, len1);
        }
        f.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

我需要一些关于我哪里出错的指导。 谢谢。

1 个答案:

答案 0 :(得分:0)

作为我插入的代码工作

public class Tapir extends ListActivity {

// flag for Internet connection status
Boolean isInternetPresent = false;

// Connection detector class
ConnectionDetector cd;

public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
 private ProgressDialog  mProgressDialog;
 public  MediaPlayer    mp;

 private String       URLDwnTapir="http://internetwan.xzn.ir/tapir_vocalisation.mp3";
 private String       URLDwnTapir_pic="http://internetwan.xzn.ir/tapir.jpg";

 File sdcard=Environment.getExternalStorageDirectory();
 File dir=new File(sdcard.getAbsolutePath()+"/WorldOfSounds/Tapir");
 //Objects of files
 File Tapir_obj=new File(dir,"Tapir.mp3");

 File Tapir_PIC_obj=new File(dir,"Tapir.jpg");


 String   Tapir=Environment.getExternalStorageDirectory().getAbsolutePath()+"/WorldOfSounds/Tapir/Tapir.jpg";
 @Override
    public void onBackPressed() {
        super.onBackPressed();
        if(mp!=null&&mp.isPlaying()){
            mp.release();
            mp.stop();
        }
    }

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tapir);

    setListAdapter (new ArrayAdapter  <String> (this,
            android.R.layout.simple_list_item_1,
            getResources ().getStringArray(R.array.Tapir_value)));

    // creating connection detector class instance
    cd = new ConnectionDetector(getApplicationContext());


}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);
    switch(position){
    case 0:
         if(!dir.exists()){
                dir.mkdirs();
            }
         if(Tapir_obj.exists()){
                if(mp!=null){
                    mp.release();
                }if(Tapir_PIC_obj.exists()){
                    LinearLayout linl=(LinearLayout)findViewById(R.id.LinearLayout1);
                    //FileInputStream streamIn = new FileInputStream(Tapir_PIC_obj);
                    //Bitmap bitmap = BitmapFactory.decodeStream(streamIn);
                    //Uri  imgUri=Uri.fromFile(Tapir_PIC_obj);

                    BitmapDrawable d = new BitmapDrawable(Tapir);
                    linl.setBackgroundDrawable(d);


                }else{
                    StartDwnTapir_pic();
                }


                final AudioManager mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
                final int originalVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
                mp = new MediaPlayer();
                mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mp=MediaPlayer.create(null, Uri.fromFile(Tapir_obj)) ;  
                mp.start();
                mp.setOnCompletionListener(new OnCompletionListener()
                {
                   @Override
                   public void onCompletion(MediaPlayer mp)
                   {
                      mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, originalVolume, 0);
                   }
                });

                //LinearLayout linl=(LinearLayout)findViewById(R.id.LinearLayout1);
                //linl.setBackgroundResource(R.drawable.tapir);

            }else{
                // get Internet status
                isInternetPresent = cd.isConnectingToInternet();

                // check for Internet status
                if (isInternetPresent) {
                    // Internet Connection is Present
                    // make HTTP requests
                    startDwnTapir_obj();

                } else {
                    // Internet connection is not present
                    // Ask user to connect to Internet
                    Toast.makeText(this,"مشکل در اتصال به شبکه اینترنت!",Toast.LENGTH_LONG).show();

                }



            }//end else

            //Toast.makeText(this,"you selected position 0",Toast.LENGTH_LONG).show();
            break;
    }//end switch

}//end onlistitem

private void startDwnTapir_obj(){

    new DwnstartDwnTapir_objAsync().execute(URLDwnTapir);       

                                }

private void StartDwnTapir_pic(){

    new StartDwnTapir_picAsync().execute(URLDwnTapir_pic);      

                                }



 @Override
    protected Dialog onCreateDialog(int id) {
         //String SmallFountain = URLDownloadSmallFountain.substring(URLDownloadSmallFountain.lastIndexOf('/') + 1, URLDownloadSmallFountain.length());
           // String msg="downloading file : "+SmallFountain;
        switch (id) {
                    case DIALOG_DOWNLOAD_PROGRESS:

                mProgressDialog = new ProgressDialog(this);

                mProgressDialog.setMessage("downloading file... \n Please wait");

                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

                mProgressDialog.setCancelable(false);

                mProgressDialog.show();

                return mProgressDialog;

            default:

                return null;

        }

    }//end onCreatDialog

 class DwnstartDwnTapir_objAsync extends AsyncTask<String, String, String> {

        @Override
           protected void onPreExecute() {

               super.onPreExecute();

               showDialog(DIALOG_DOWNLOAD_PROGRESS);

           }



        @Override
           protected String doInBackground(String... aurl) {

               int count;

               try {

                   URL URLDwnTapir = new URL(aurl[0]);

                   HttpURLConnection conexion = (HttpURLConnection) URLDwnTapir.openConnection();

                   conexion.connect();

                   int lenghtOfFile = conexion.getContentLength();

                   Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

                   InputStream input = new BufferedInputStream(URLDwnTapir.openStream());

                  if(!dir.exists()){
                   dir.mkdirs();
                  }           

                   OutputStream output = new FileOutputStream(Tapir_obj);

                   byte data[] = new byte[1024];

                   long total = 0;

                   while ((count = input.read(data)) != -1) {

                       total += count;

                       publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                       output.write(data, 0, count);

                   }
                   Log.d("ANDRO_ASYNC", "end download Tapir_obj File ");

                   output.flush();

                   output.close();

                   input.close();

               }
               catch (Exception e) {}

               return null;

           }



           @Override
           protected void onProgressUpdate(String... progress) {

               Log.d("ANDRO_ASYNC", progress[0]);

               mProgressDialog.setProgress(Integer.parseInt(progress[0]));

           }



        @Override
           protected void onPostExecute(String unused) {

               dismissDialog(DIALOG_DOWNLOAD_PROGRESS);

           }


       }//end Class DwnTapirAsync