Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void downloadPdf(Context context, String url, String name, final Callback callback){
- Uri uri;
- try{
- uri = Uri.parse(url);
- }
- catch(Exception e){
- Log.e(LogTags.UI, "Error parsing pdf url " + url, e);
- callback.onError();
- return;
- }
- DownloadManager.Request r = new DownloadManager.Request(uri);
- // This put the download in the same Download dir the browser uses
- r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, name);
- // When downloading music and videos they will be listed in the player
- // (Seems to be available since Honeycomb only)
- r.allowScanningByMediaScanner();
- // Notify user when download is completed
- // (Seems to be available since Honeycomb only)
- r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
- // Start download
- final DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
- final long downloadId = dm.enqueue(r);
- BroadcastReceiver receiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- String action = intent.getAction();
- if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
- if(intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0) != downloadId){
- // Quick exit - its not our download!
- return;
- }
- DownloadManager.Query query = new DownloadManager.Query();
- query.setFilterById(downloadId);
- Cursor c = dm.query(query);
- if (c.moveToFirst()) {
- int columnIndex = c
- .getColumnIndex(DownloadManager.COLUMN_STATUS);
- if (DownloadManager.STATUS_SUCCESSFUL == c
- .getInt(columnIndex)) {
- String uriString = c
- .getString(c
- .getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
- Uri uri = Uri.parse(uriString);
- intent = new Intent();
- intent.setAction(Intent.ACTION_VIEW);
- intent.setDataAndType(uri, "application/pdf");
- callback.onSuccess();
- context.startActivity(intent);
- }
- else{
- callback.onError();
- }
- }
- else{
- callback.onError();
- }
- context.unregisterReceiver(this);
- }
- }
- };
- context.registerReceiver(receiver, new IntentFilter(
- DownloadManager.ACTION_DOWNLOAD_COMPLETE));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement