【问题标题】:Open File PDF automatically After Download Completed下载完成后自动打开文件PDF
【发布时间】:2014-06-06 06:05:55
【问题描述】:

我有问题。我有下载和打开文件 PDF 的代码。我要下载完成后,PDF会自动打开。

这是我下载 pdf 文件的代码:

  private EditText ids;
  private TextView no;
  private TextView per;
  private EditText surat_fi;
  private EditText disp;
  private Button kepada, baca;

  Context context=this;

  @Override
  public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.suratmasuk);

        ids = (EditText) findViewById(R.id.edid);
        no = (TextView) findViewById(R.id.ednomor);
        per = (TextView) findViewById(R.id.edperihal);
        surat_fi = (EditText) findViewById(R.id.surat);
        disp = (EditText) findViewById(R.id.eddisposisi);

  ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
  JSONObject json = JSONSuratMasuk.getJSONfromURL("http://link...");

        try{
        JSONArray  data = json.getJSONArray("data");

        for(int i=0;i<data.length();i++){
        HashMap<String, String> map = new HashMap<String, String>();
        JSONObject jsonobj = data.getJSONObject(i);

               map.put("id1",  jsonobj.getString("id"));
               map.put("nomor",  jsonobj.getString("nosurat"));
               map.put("perihal", jsonobj.getString("perihal"));
               map.put("surat", jsonobj.getString("surat"));
        mylist.add(map);
 }
        }catch(JSONException e)        {
        Log.e("log_tag", "Error parsing data "+e.toString());
 }

              ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.row,
              new String[] { "nomor", "perihal" },
              new int[] { R.id.lvnomor, R.id.lvperihal });

              setListAdapter(adapter);

         final ListView lv = getListView();
         lv.setTextFilterEnabled(true);
         lv.setOnItemClickListener(new OnItemClickListener() {

     public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

     @SuppressWarnings("unchecked")
     HashMap<String, String> o = (HashMap<String, String>)         lv.getItemAtPosition(position);

     no.setText(String.valueOf(o.get("nomor")));
     per.setText(String.valueOf(o.get("perihal")));
     surat_fi.setText(String.valueOf(o.get("surat")));


      Boolean result=isDownloadManagerAvailable(getApplicationContext());
      if (result)
      downloadFile();
    }
    });            
      }
    });


@SuppressLint("NewApi")
public void downloadFile() {
    String surfil = surat_fi.getText().toString();      
    String DownloadUrl = "http://link...";
    String fs = DownloadUrl+surfil;
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(fs));
    request.setDescription("Sedang download");
    request.setTitle(surfil);                

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
          request.allowScanningByMediaScanner();
          request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        }
        request.setDestinationInExternalFilesDir(getApplicationContext(),null, surfil);

         DownloadManager manager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
         manager.enqueue(request);
     }
}   

@SuppressLint("NewApi")
public static boolean isDownloadManagerAvailable(Context context) {
    try {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
            return false;
        }
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setClassName("com.android.providers.downloads.ui","com.android.providers.downloads.ui.DownloadList");

        List <ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent,
        PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    } catch (Exception e) {
        return false; 
    }
}     

这是打开 PDF 文件的代码:

String sur_fil = surat_fi.getText().toString();     
String baca_file = "/sdcard/Android/data/com.e_office/files/";
String fs_baca = baca_file+sur_fil;
File pdfFile = new File(fs_baca); 
if(pdfFile.exists()) {
    Uri path = Uri.fromFile(pdfFile); 
    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(SuratMasuk.this, "No Application available to view pdf", Toast.LENGTH_LONG).show(); 
    }
}

我应该把它放在哪里?

【问题讨论】:

    标签: java android eclipse pdf android-download-manager


    【解决方案1】:

    使用此操作写Broadcast ReceiverDownloadManager.ACTION_DOWNLOAD_COMPLETE。下载文件后,它会到达您接收器中的onReceive()

    【讨论】:

      【解决方案2】:

      将您的下载调用放在 try catch 块中,一旦调用成功,就在结束前调用一个名为 openpdf() 的新方法,您可以在其中放置此代码。

      【讨论】:

        【解决方案3】:

        嗯!嗯! 每当下载任务时,最好将代码放在带有进度对话框的异步任务中。因为它需要一点时间。所以你可以这样做。

        ==> 将您的下载代码放入/调用doinBackground() 部分的Async() 任务。

        ==>preexecute()postexecute() 中调用progressdialog(),如下所示。

        ==>mProgressDialog.dismiss(); 之后的 post execute() 中调用 openfile() 函数并在 fileopen() 函数中编写文件打开器代码。

        class MyAsyncTask extends AsyncTask<String, String, Void> {
        
                boolean running;
        
        
                @Override
                protected Void doInBackground(String...fUrl) {
                    int count;
        
        
                    InputStream input = null;
                    OutputStream output = null;
                    HttpURLConnection connection = null;
                    try {
        
                        URL url = new URL(fUrl[0]);
                        connection = (HttpURLConnection) url.openConnection();
                        connection.connect();
        
                        int lenghtOfFile = connection.getContentLength();
        
        
                        // download the file
                        input = connection.getInputStream();
                        output = new FileOutputStream(
                                Environment.getExternalStorageDirectory() + "/MDroid/"
                                        + fileName);
        
            //#################################
                mydownload(fileUrl, filepath, fileName,
                    visibility);  //i am calling download function() here
        
        
            //##########################################
        
                        byte data[] = new byte[4096];
                        long total = 0;
                        while ((count = input.read(data)) != -1) {
                            total += count;
                            publishProgress(""+(int)((total*100)/lenghtOfFile));
                            output.write(data, 0, count);
                        }
        
                        output.close();
                        input.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
            return null;
        
                }
        
                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    running = true;
        
                    mProgressDialog.show();
                }
        
                @Override
                protected void onPostExecute(Void aVoid) {
                    super.onPostExecute(aVoid);
        
                    mProgressDialog.dismiss();
                    openfile();
                }
        
                 @Override
                protected void onProgressUpdate(String... progress) {
        
                    // Update the progress dialog
                    mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        
                }
        
            }
        

        ==> openfile() 函数代码是这样的。

        public void openfile()
        {
        
        
            try {
                File file = new File(Environment
                        .getExternalStoragePublicDirectory("/MDroid")
                        + filepath + fileName);
        
                Intent testIntent = new Intent("com.adobe.reader");
                testIntent.setType("application/pdf");
                testIntent.setAction(Intent.ACTION_VIEW);
                Uri uri = Uri.fromFile(file);
                testIntent.setDataAndType(uri, "application/pdf");
                context.startActivity(testIntent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        
        }
        

        【讨论】:

          猜你喜欢
          • 2021-10-30
          • 2016-02-25
          • 1970-01-01
          • 1970-01-01
          • 2019-01-01
          • 2015-02-27
          • 2014-05-13
          • 2015-04-20
          • 1970-01-01
          相关资源
          最近更新 更多