Java Code Examples for android.app.DownloadManager#query()

The following examples show how to use android.app.DownloadManager#query() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SplashActivity.java    From pokemon-go-xposed-mitm with GNU General Public License v3.0 6 votes vote down vote up
private int getProgressPercentage() {
    int downloadedBytesSoFar = 0, totalBytes = 0, percentage = 0;
    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    try {
        Cursor c = dm.query(new DownloadManager.Query().setFilterById(enqueue));
        if (c.moveToFirst()) {
            int soFarIndex =c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
            downloadedBytesSoFar = (int) c.getLong(soFarIndex);
            int totalSizeIndex = c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
            totalBytes = (int) c.getLong(totalSizeIndex);
        }
        System.out.println("PERCEN ------" + downloadedBytesSoFar
                           + " ------ " + totalBytes + "****" + percentage);
        percentage = (downloadedBytesSoFar * 100 / totalBytes);
        System.out.println("percentage % " + percentage);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return percentage;
}
 
Example 2
Source File: UpdateApkReceiver.java    From Yuan-WanAndroid with Apache License 2.0 6 votes vote down vote up
/**
 * 查询下载完成文件的状态
 */
private void checkDownloadStatus(Context context, long downloadId) {
    mDownloadManager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
    DownloadManager.Query query = new DownloadManager.Query();
    query.setFilterById(downloadId);
    Cursor cursor = mDownloadManager.query(query);
    if (cursor.moveToFirst()) {
        int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
        switch (status) {
            case DownloadManager.STATUS_SUCCESSFUL:
                LogUtil.d(LogUtil.TAG_COMMON, "下载完成!");
                installApk(context,mDownloadManager.getUriForDownloadedFile(downloadId));
                break;
            case DownloadManager.STATUS_FAILED://下载失败
                LogUtil.d(LogUtil.TAG_COMMON, "下载失败.....");
                break;
            case DownloadManager.STATUS_RUNNING://正在下载
                LogUtil.d(LogUtil.TAG_COMMON, "正在下载.....");
                break;
            default:
                break;
        }
    }
}
 
Example 3
Source File: FontViewHolder.java    From FontProvider with MIT License 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
    if (id != -1) {
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Cursor cursor = downloadManager.query(new DownloadManager.Query().setFilterById(id));

        if (cursor != null && cursor.getCount() > 0) {
            cursor.moveToFirst();
            if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) != DownloadManager.STATUS_SUCCESSFUL) {
                String title = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE));
                Toast.makeText(context, context.getString(R.string.toast_download_failed, title), Toast.LENGTH_SHORT).show();
                return;
            }
        }

        ids.remove(id);

        if (ids.isEmpty()) {
            getAdapter().notifyItemChanged(getAdapterPosition(), new Object());
            context.unregisterReceiver(this);

            mBroadcastReceiver = null;
        }
    }
}
 
Example 4
Source File: DownloadManagerService.java    From delion with Apache License 2.0 5 votes vote down vote up
@Override
public Pair<Integer, Boolean> doInBackground(Void...voids) {
    DownloadManager manager =
            (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    Cursor c = manager.query(new DownloadManager.Query().setFilterById(
            mDownloadItem.getSystemDownloadId()));
    int statusIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
    int reasonIndex = c.getColumnIndex(DownloadManager.COLUMN_REASON);
    int titleIndex = c.getColumnIndex(DownloadManager.COLUMN_TITLE);
    int status = DownloadManager.STATUS_FAILED;
    Boolean canResolve = false;
    if (c.moveToNext()) {
        status = c.getInt(statusIndex);
        String title = c.getString(titleIndex);
        if (mDownloadInfo == null) {
            // Chrome has been killed, reconstruct a DownloadInfo.
            mDownloadInfo = new DownloadInfo.Builder()
                    .setFileName(title)
                    .setDescription(c.getString(
                            c.getColumnIndex(DownloadManager.COLUMN_DESCRIPTION)))
                    .setMimeType(c.getString(
                            c.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE)))
                    .setContentLength(Long.parseLong(c.getString(
                            c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))))
                    .build();
        }
        if (status == DownloadManager.STATUS_SUCCESSFUL) {
            mDownloadInfo = DownloadInfo.Builder.fromDownloadInfo(mDownloadInfo)
                    .setFileName(title)
                    .build();
            mDownloadItem.setDownloadInfo(mDownloadInfo);
            canResolve = canResolveDownloadItem(mContext, mDownloadItem);
        } else if (status == DownloadManager.STATUS_FAILED) {
            mFailureReason = c.getInt(reasonIndex);
            manager.remove(mDownloadItem.getSystemDownloadId());
        }
    }
    c.close();
    return Pair.create(status, canResolve);
}
 
Example 5
Source File: CompleteReceiver.java    From MeiZiNews with MIT License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {

    String action = intent.getAction();
    if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {

        downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
        DownloadManager.Query myDownloadQuery = new DownloadManager.Query();
        myDownloadQuery.setFilterById(id);

        Cursor myDownload = downloadManager.query(myDownloadQuery);
        if (myDownload.moveToFirst()) {
            int fileNameIdx =
                    myDownload.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
            int fileUriIdx =
                    myDownload.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);

            String fileName = myDownload.getString(fileNameIdx);
            String fileUri = myDownload.getString(fileUriIdx);

            // TODO Do something with the file.

            if(TextUtils.isEmpty(fileUri)){

                ShowToast.ShowTextToast(context, "下载失败了, O _ o " + fileUri);
            }else {

                ShowToast.ShowTextToast(context, "下载完成!保存位置 : " + fileUri);
            }

        }
        myDownload.close();

    } else if (action.equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
        ShowToast.ShowTextToast(context, "点击通知了....");
    }
}
 
Example 6
Source File: DownloadReceiver.java    From nono-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {

    DownloadManager manager = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
    if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())){
        DownloadManager.Query query = new DownloadManager.Query();
        //在广播中取出下载任务的id
        long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
        query.setFilterById(id);
        Cursor c = manager.query(query);
        if(c.moveToFirst()) {
            //获取文件下载路径
            String filename = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
            //如果文件名不为空,说明已经存在了,拿到文件名想干嘛都好
            if(filename != null){
                File file  = new File(filename);
                Intent anotherIntent = new Intent();
                anotherIntent.addFlags(anotherIntent.FLAG_ACTIVITY_NEW_TASK);
                anotherIntent.setAction(android.content.Intent.ACTION_VIEW);
                anotherIntent.setDataAndType(Uri.fromFile(file),
                        "application/vnd.android.package-archive");
                context.startActivity(anotherIntent);
            }
        }
    }else if(DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(intent.getAction())){
        long[] ids = intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);
        //点击通知栏取消下载
        manager.remove(ids);
        //ShowToastUtil.showShortToast(context, "已经取消下载");
    }

}
 
Example 7
Source File: DownloadCompletedReceiver.java    From magpi-android with MIT License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
       String action = intent.getAction();
       DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
       if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
           Query query = new Query();
           query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
           Cursor c = dm.query(query);
           if (c.moveToFirst()) {
               int titleColumnIndex = c.getColumnIndex(DownloadManager.COLUMN_TITLE);
               String title = context.getString(R.string.menu_view) + " " + c.getString(titleColumnIndex);
               int pdfPathColumnIndex = c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
               String pdfPath = c.getString(pdfPathColumnIndex);
               Intent intentPdf = new Intent(Intent.ACTION_VIEW);
               intentPdf.setDataAndType(Uri.parse(pdfPath), "application/pdf");
       		PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
       				intentPdf, PendingIntent.FLAG_CANCEL_CURRENT);
       		
       		SharedPreferences settings = context.getSharedPreferences("IssueDownloadNotification", Context.MODE_PRIVATE);
       		if(settings.getBoolean(title, false))
       			return;
       		settings.edit().putBoolean(title, true).commit();

       		Notification noti = new NotificationCompat.Builder(context)
       				.setContentTitle(title)
       				.setContentText(context.getString(R.string.download_completed_text))
       				.setContentIntent(contentIntent)
       				.setSmallIcon(R.drawable.new_issue)
       				.getNotification();
       		
       		PebbleNotifier.notify(context, title, context.getString(R.string.download_completed_text));

       		NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
       		noti.flags |= Notification.FLAG_AUTO_CANCEL;
       		notificationManager.notify(ID_NOTIFICATION++, noti);
           }
           c.close();
       }
}
 
Example 8
Source File: PNetwork.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
@PhonkMethod(description = "Downloads a file from a given Uri. Returns the progress", example = "")
public void downloadWithSystemManager(String url, final ReturnInterface callback) {
    final DownloadManager dm = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    final long enqueue = dm.enqueue(request);

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(enqueue);
                Cursor c = dm.query(query);
                if (c.moveToFirst()) {
                    int columnIndex = c
                            .getColumnIndex(DownloadManager.COLUMN_STATUS);
                    if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
                        if (callback != null) callback.event(null);
                        // callback successful
                    }
                }
            }
        }
    };

    getContext().registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));


}
 
Example 9
Source File: DownloadNewVersionJob.java    From WayHoo with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("static-access")
private boolean checkDownloadRunning() {
	UpgradeInfo prefUpgradeInfo = Preferences.getUpgradeInfo(mContext);
	String version = prefUpgradeInfo.getVersion();
	int downloadStatus = Preferences.getDownloadStatus(mContext);
	if (version != null && version.trim().length() != 0
			&& version.equals(mUpgradeInfo.getVersion())) {
		long downloadId = Preferences.getDownloadId(mContext);
		if (downloadId != -1) {
			final DownloadManager downloadManager = (DownloadManager) mContext
					.getSystemService(mContext.DOWNLOAD_SERVICE);
			DownloadManager.Query mDownloadQuery = new DownloadManager.Query();
			mDownloadQuery.setFilterById(downloadId);
			Cursor cursor = downloadManager.query(mDownloadQuery);
			if (cursor != null && cursor.moveToFirst()) {
				int status = cursor.getInt(cursor
						.getColumnIndex(DownloadManager.COLUMN_STATUS));
				if (status == DownloadManager.STATUS_RUNNING
						|| downloadStatus == Constants.DOWNLOAD_STATUS_RUNNING) {
					return true;
				}
			}

		}
	}
	return false;
}
 
Example 10
Source File: FontManager.java    From FontProvider with MIT License 5 votes vote down vote up
public static List<Long> download(FontInfo font, List<String> files, Context context, boolean allowDownloadOverMetered) {
    DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    if (downloadManager == null) {
        return null;
    }

    Cursor cursor = downloadManager.query(new DownloadManager.Query()
            .setFilterByStatus(DownloadManager.STATUS_PAUSED
                    | DownloadManager.STATUS_PENDING
                    | DownloadManager.STATUS_RUNNING));

    if (cursor != null) {
        if (cursor.getCount() > 0) {
            cursor.moveToFirst();

            do {
                int titleIndex = cursor.getColumnIndex(DownloadManager.COLUMN_TITLE);
                String file = cursor.getString(titleIndex);
                Log.d(TAG, file + " is already downloading");
                files.remove(file);
            } while (cursor.moveToNext());
        }

        cursor.close();
    }

    List<Long> ids = new ArrayList<>();
    for (String f : files) {
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(font.getUrlPrefix() + f))
                .setTitle(f)
                .setDestinationInExternalFilesDir(context, null, f)
                .setVisibleInDownloadsUi(false)
                .setAllowedOverMetered(allowDownloadOverMetered)
                .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        ids.add(downloadManager.enqueue(request));
    }

    return ids;
}
 
Example 11
Source File: DownloadCompleteBroadcastReceiver.java    From leanback-showcase with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    final DownloadManager dm = (DownloadManager) context.getSystemService(
            Context.DOWNLOAD_SERVICE);
    Long downloadingTaskId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1L);
    if (NetworkManagerUtil.downloadingTaskQueue.containsKey(downloadingTaskId)) {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(downloadingTaskId);
        Cursor cursor = dm.query(query);

        // retrieve downloaded content's information through download manager.
        if (!cursor.moveToFirst()) {
            return;
        }

        if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
                != DownloadManager.STATUS_SUCCESSFUL) {
            return;
        }

        String path = cursor.getString(
                cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

        final DownloadingTaskDescription desc =
                NetworkManagerUtil.downloadingTaskQueue.get(downloadingTaskId);

        // update local storage path
        desc.setStoragePath(path);

        for (final DownloadCompleteListener listener: downloadingCompletionListener) {
                    listener.onDownloadingCompleted(desc);
        }
    }
}
 
Example 12
Source File: DownloadManagerService.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@Override
public Pair<Integer, Boolean> doInBackground(Void...voids) {
    DownloadManager manager =
            (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    Cursor c = manager.query(new DownloadManager.Query().setFilterById(
            mDownloadItem.getSystemDownloadId()));
    int statusIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
    int reasonIndex = c.getColumnIndex(DownloadManager.COLUMN_REASON);
    int titleIndex = c.getColumnIndex(DownloadManager.COLUMN_TITLE);
    int status = DownloadManager.STATUS_FAILED;
    Boolean canResolve = false;
    if (c.moveToNext()) {
        status = c.getInt(statusIndex);
        String title = c.getString(titleIndex);
        if (mDownloadInfo == null) {
            // Chrome has been killed, reconstruct a DownloadInfo.
            mDownloadInfo = new DownloadInfo.Builder()
                    .setFileName(title)
                    .setDescription(c.getString(
                            c.getColumnIndex(DownloadManager.COLUMN_DESCRIPTION)))
                    .setMimeType(c.getString(
                            c.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE)))
                    .setContentLength(Long.parseLong(c.getString(
                            c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))))
                    .build();
        }
        if (status == DownloadManager.STATUS_SUCCESSFUL) {
            mDownloadInfo = DownloadInfo.Builder.fromDownloadInfo(mDownloadInfo)
                    .setFileName(title)
                    .build();
            mDownloadItem.setDownloadInfo(mDownloadInfo);
            canResolve = canResolveDownloadItem(mContext, mDownloadItem, false);
        } else if (status == DownloadManager.STATUS_FAILED) {
            mFailureReason = c.getInt(reasonIndex);
            manager.remove(mDownloadItem.getSystemDownloadId());
        }
    }
    c.close();
    return Pair.create(status, canResolve);
}
 
Example 13
Source File: MainActivity.java    From Rucky with GNU General Public License v3.0 4 votes vote down vote up
void download(Uri uri) {
    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
    alertBuilder.setMessage(getResources().getString(R.string.screen_on))
            .setCancelable(false);
    waitDialog = alertBuilder.create();
    Objects.requireNonNull(waitDialog.getWindow()).setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
    waitDialog.show();
    File fDel = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),"rucky.apk");
    if (fDel.exists()) {
        fDel.delete();
        if(fDel.exists()){
            try {
                fDel.getCanonicalFile().delete();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(fDel.exists()){
                getApplicationContext().deleteFile(fDel.getName());
            }
        }
    }
    downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    DownloadManager.Request req = new DownloadManager.Request(uri);
    req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
    req.setAllowedOverRoaming(true);
    req.setTitle("rucky.apk");
    req.setDestinationInExternalFilesDir(this,Environment.DIRECTORY_DOWNLOADS,"rucky.apk");
    req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
    DownloadManager.Query q = new DownloadManager.Query();
    q.setFilterById(DownloadManager.STATUS_FAILED | DownloadManager.STATUS_SUCCESSFUL | DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
    Cursor c = downloadManager.query(q);
    while (c.moveToNext()) {
        downloadManager.remove(c.getLong(c.getColumnIndex(DownloadManager.COLUMN_ID)));
    }
    downloadRef = downloadManager.enqueue(req);
    IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
    registerReceiver(downloadBR, filter);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        updateNotify = new Notification.Builder(this, CHANNEL_ID)
                .setContentTitle(getResources().getString(R.string.update_exec))
                .setSmallIcon(R.drawable.ic_notification)
                .setAutoCancel(false)
                .setOngoing(true)
                .build();
    } else {
        updateNotify = new Notification.Builder(this)
                .setContentTitle(getResources().getString(R.string.update_exec))
                .setSmallIcon(R.drawable.ic_notification)
                .setAutoCancel(false)
                .setOngoing(true)
                .build();
    }
    notificationManager.notify(2,updateNotify);
}
 
Example 14
Source File: DownloadProgressActivity.java    From IslamicLibraryAndroid with GNU General Public License v3.0 4 votes vote down vote up
@Nullable
@Override
protected DownloadInfoUpdate doInBackground(Void... voids) {
    //Convert Long[] to long[]

    while (true) {

        DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Query BooksDownloadQuery = new DownloadManager.Query();

        BooksDownloadQuery.setFilterByStatus(DownloadManager.STATUS_RUNNING |
                DownloadManager.STATUS_PAUSED |
                DownloadManager.STATUS_PENDING);

        //Query the download manager about downloads that have been requested.
        Cursor cursor = downloadManager.query(BooksDownloadQuery);
        int progressingDownloadCount = cursor.getCount();

        List<DownloadInfo> progressDownloadInfo = new ArrayList<>();
        if (progressingDownloadCount != 0) {
            for (int i = 0; i < progressingDownloadCount; i++) {
                cursor.moveToPosition(i);
                DownloadInfo downloadInfo = new DownloadInfo(cursor);
                progressDownloadInfo.add(i, downloadInfo);
                Log.d("download_iter", downloadInfo.toString());
            }
            Collections.sort(progressDownloadInfo, (o1, o2) -> {
                if (o1.getProgressPercent() != 0 && o2.getProgressPercent() != 0) {
                    return o1.compareTo(o2);
                } else if (o1.getProgressPercent() != 0 && o2.getProgressPercent() == 0) {
                    return -1;

                } else if (o1.getProgressPercent() == 0 && o2.getProgressPercent() != 0) {
                    return 1;

                } else //(o1.getProgressPercent() == 0 && o2.getProgressPercent() == 0)
                {
                    return o1.compareTo(o2);
                }

            });
        }
        DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(
                new DownloadInfo.DownloadInfoDiffCallback(mOldDownloadList, progressDownloadInfo));
        mOldDownloadList = progressDownloadInfo;
        cursor.close();


        if (progressingDownloadCount != 0) {
            publishProgress(new DownloadInfoUpdate(progressDownloadInfo, diffResult));
        } else {
            return new DownloadInfoUpdate(progressDownloadInfo, diffResult);
        }

        if (isCancelled()) {
            publishProgress(new DownloadInfoUpdate(DownloadInfoUpdate.TYPE_CANCEL));
            DownloadManager.Query non_complete_query = new DownloadManager.Query();
            non_complete_query.setFilterByStatus(DownloadManager.STATUS_FAILED |
                    DownloadManager.STATUS_PENDING |
                    DownloadManager.STATUS_RUNNING);
            Cursor c = downloadManager.query(non_complete_query);
            int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_ID);
            //TODO this loop may cause problems if a download completed and the broadcast is triggered before we cancel it
            while (c.moveToNext()) {
                long enquId = c.getLong(columnIndex);
                downloadManager.remove(enquId);
            }
            DownloadProgressActivity.this.cancelMultipleDownloads(c, columnIndex);
            Intent localIntent =
                    new Intent(BROADCAST_ACTION)
                            .putExtra(EXTRA_NOTIFY_WITHOUT_BOOK_ID, true);
            DownloadProgressActivity.this.sendOrderedBroadcast(localIntent, null);
            c.close();

            return null;
        }
        try {
            Thread.sleep(40);
        } catch (InterruptedException e) {
            Timber.e(e);
        }
    }
}
 
Example 15
Source File: OMADownloadHandler.java    From 365browser with Apache License 2.0 4 votes vote down vote up
@Override
public Pair<Integer, Boolean> doInBackground(Void... voids) {
    DownloadManager manager =
            (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
    Cursor c = manager.query(
            new DownloadManager.Query().setFilterById(mDownloadItem.getSystemDownloadId()));
    int statusIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
    int reasonIndex = c.getColumnIndex(DownloadManager.COLUMN_REASON);
    int titleIndex = c.getColumnIndex(DownloadManager.COLUMN_TITLE);
    int status = DownloadManager.STATUS_FAILED;
    Boolean canResolve = false;
    if (c.moveToNext()) {
        status = c.getInt(statusIndex);
        String title = c.getString(titleIndex);
        if (mDownloadInfo == null) {
            // Chrome has been killed, reconstruct a DownloadInfo.
            mDownloadInfo =
                    new DownloadInfo.Builder()
                            .setFileName(title)
                            .setDescription(c.getString(
                                    c.getColumnIndex(DownloadManager.COLUMN_DESCRIPTION)))
                            .setMimeType(c.getString(
                                    c.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE)))
                            .setBytesReceived(Long.parseLong(c.getString(c.getColumnIndex(
                                    DownloadManager.COLUMN_TOTAL_SIZE_BYTES))))
                            .build();
        }
        if (status == DownloadManager.STATUS_SUCCESSFUL) {
            mDownloadInfo = DownloadInfo.Builder.fromDownloadInfo(mDownloadInfo)
                                    .setFileName(title)
                                    .build();
            mDownloadItem.setDownloadInfo(mDownloadInfo);
            canResolve = DownloadManagerService.canResolveDownloadItem(
                    mContext, mDownloadItem, false);
        } else if (status == DownloadManager.STATUS_FAILED) {
            mFailureReason = c.getInt(reasonIndex);
            manager.remove(mDownloadItem.getSystemDownloadId());
        }
    }
    c.close();
    return Pair.create(status, canResolve);
}
 
Example 16
Source File: DownloadActivity.java    From ClockView with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_download);
    down = (TextView) findViewById(R.id.down);
    progress = (TextView) findViewById(R.id.progress);
    file_name = (TextView) findViewById(R.id.file_name);
    pb_update = (ProgressBar) findViewById(R.id.pb_update);
    down.setOnClickListener(this);
    downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    request = new DownloadManager.Request(Uri.parse(downloadUrl));

    request.setTitle("测试apk包");
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
    request.setAllowedOverRoaming(false);
    request.setMimeType("application/vnd.android.package-archive");
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    //创建目录
    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdir() ;

    //设置文件存放路径
    request.setDestinationInExternalPublicDir(  Environment.DIRECTORY_DOWNLOADS  , "app-release.apk" ) ;
    pb_update.setMax(100);
   final  DownloadManager.Query query = new DownloadManager.Query();
    timer = new Timer();
    task = new TimerTask() {
        @Override
        public void run() {
            Cursor cursor = downloadManager.query(query.setFilterById(id));
            if (cursor != null && cursor.moveToFirst()) {
                if (cursor.getInt(
                        cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
                    pb_update.setProgress(100);
                    install(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/app-release.apk" );
                    task.cancel();
                }
                String title = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE));
                String address = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                int pro =  (bytes_downloaded * 100) / bytes_total;
                Message msg =Message.obtain();
                Bundle bundle = new Bundle();
                bundle.putInt("pro",pro);
                bundle.putString("name",title);
                msg.setData(bundle);
                handler.sendMessage(msg);
            }
            cursor.close();
        }
    };
    timer.schedule(task, 0,1000*3);
}
 
Example 17
Source File: UpdateAppReceiver.java    From TvPlayer with Apache License 2.0 4 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    // 处理下载完成
    Cursor c = null;

    if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) {
        if (DownloadAppUtils.downloadUpdateApkId >= 0) {
            long downloadId = DownloadAppUtils.downloadUpdateApkId;
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(downloadId);
            DownloadManager downloadManager = (DownloadManager) context
                    .getSystemService(Context.DOWNLOAD_SERVICE);
            c = downloadManager.query(query);
            if (c.moveToFirst()) {
                int status = c.getInt(c
                        .getColumnIndex(DownloadManager.COLUMN_STATUS));
                if (status == DownloadManager.STATUS_FAILED) {
                    downloadManager.remove(downloadId);

                } else if (status == DownloadManager.STATUS_SUCCESSFUL) {
                    if (DownloadAppUtils.downloadUpdateApkFilePath != null) {
                        Intent i = new Intent(Intent.ACTION_VIEW);
                        File apkFile = new File(DownloadAppUtils.downloadUpdateApkFilePath);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            Uri contentUri = FileProvider.getUriForFile(
                                    context, context.getPackageName() + ".fileprovider", apkFile);
                            i.setDataAndType(contentUri, "application/vnd.android.package-archive");
                        } else {
                            i.setDataAndType(Uri.fromFile(apkFile),
                                    "application/vnd.android.package-archive");
                        }
                        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(i);
                    }
                }
            }
            c.close();
        }
    }


}
 
Example 18
Source File: DownloadReceiver.java    From youtube-dl-android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    long receivedID = intent.getLongExtra(
            DownloadManager.EXTRA_DOWNLOAD_ID, -1L);
    DownloadManager mgr = (DownloadManager)
            context.getSystemService(Context.DOWNLOAD_SERVICE);

    DownloadManager.Query query = new DownloadManager.Query();
    query.setFilterById(receivedID);
    Cursor cur = mgr.query(query);
    int status_index = cur.getColumnIndex(DownloadManager.COLUMN_STATUS);
    int id_index = cur.getColumnIndex(DownloadManager.COLUMN_ID);
    int uri_index = cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
    int dest_index = cur.getColumnIndex(DownloadManager.COLUMN_DESCRIPTION);

    Gson gson = new Gson();

    SharedPreferences sharedPreferences = context.getSharedPreferences("download_history", Context.MODE_PRIVATE);
    String json = sharedPreferences.getString("in_progress", "");

    Type type = new TypeToken<HashMap<Long, Format>>() {}.getType();
    HashMap<Long, Format> inProgressDownloads = gson.fromJson(json, type);
    if (inProgressDownloads == null) {
        inProgressDownloads = new HashMap<Long, Format>();
    }

    json = sharedPreferences.getString("mixing_downloads", "");
    type = new TypeToken<ArrayList<Pair<Format, Format>>>() {}.getType();
    ArrayList<Pair<Format, Format>> mixingDownloads = gson.fromJson(json, type);
    if (mixingDownloads == null) {
        mixingDownloads = new ArrayList<>();
    }

    if(cur.moveToFirst()) {
        if(cur.getInt(status_index) == DownloadManager.STATUS_SUCCESSFUL){
            long id = cur.getLong(id_index);
            Format format = inProgressDownloads.get(id);
            if(format != null) {
                inProgressDownloads.remove(id);
                URI uri = URI.create(cur.getString(uri_index));
                File file = new File(uri);
                Log.d("DownloadReceiver", file.getAbsolutePath());
                format.setLocation(file.getAbsolutePath());
                File destFile = new File(cur.getString(dest_index));
                if(file.renameTo(destFile)){
                    Log.d("DownloadReceiver", "Move to final dest successful");
                    format.setLocation(destFile.getAbsolutePath());
                    Toast.makeText(context, String.format("YoutubeDL download complete to folder \"%s\"", destFile.getParentFile().getAbsolutePath()), Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
    cur.close();

    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("in_progress", gson.toJson(inProgressDownloads));
    editor.putString("mixing_downloads", gson.toJson(mixingDownloads));
    editor.apply();
}
 
Example 19
Source File: DownloadsUtil.java    From EdXposedManager with GNU General Public License v3.0 4 votes vote down vote up
private static List<DownloadInfo> getAllForUrl(Context context, String url) {
    DownloadManager dm = (DownloadManager) context
            .getSystemService(Context.DOWNLOAD_SERVICE);
    Cursor c = dm.query(new Query());
    int columnId = c.getColumnIndexOrThrow(DownloadManager.COLUMN_ID);
    int columnUri = c.getColumnIndexOrThrow(DownloadManager.COLUMN_URI);
    int columnTitle = c.getColumnIndexOrThrow(DownloadManager.COLUMN_TITLE);
    int columnLastMod = c.getColumnIndexOrThrow(
            DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP);
    int columnLocalUri = c.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI);
    int columnStatus = c.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS);
    int columnTotalSize = c.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
    int columnBytesDownloaded = c.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
    int columnReason = c.getColumnIndexOrThrow(DownloadManager.COLUMN_REASON);

    List<DownloadInfo> downloads = new ArrayList<>();
    while (c.moveToNext()) {
        if (!url.equals(c.getString(columnUri)))
            continue;

        int status = c.getInt(columnStatus);
        String localFilename;
        try {
            localFilename = getFilenameFromUri(c.getString(columnLocalUri));
        } catch (UnsupportedOperationException e) {
            Toast.makeText(context, "An error occurred. Restart app and try again.\n" + e.getMessage(), Toast.LENGTH_SHORT).show();
            return null;
        }
        if (status == DownloadManager.STATUS_SUCCESSFUL && !new File(localFilename).isFile()) {
            dm.remove(c.getLong(columnId));
            continue;
        }

        downloads.add(new DownloadInfo(c.getLong(columnId),
                c.getString(columnUri), c.getString(columnTitle),
                c.getLong(columnLastMod), localFilename,
                status, c.getInt(columnTotalSize),
                c.getInt(columnBytesDownloaded), c.getInt(columnReason)));
    }
    c.close();

    Collections.sort(downloads);
    return downloads;
}
 
Example 20
Source File: SplashActivity.java    From pokemon-go-xposed-mitm with GNU General Public License v3.0 4 votes vote down vote up
private void registerPackageInstallReceiver() {
    receiver = new BroadcastReceiver(){
        public void onReceive(Context context, Intent intent) {
            Log.d("Received intent: " + intent + " (" + intent.getExtras() + ")");
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) {
                long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                if (downloadId == enqueue) {
                    if (localFile.exists()) {
                        return;
                    }
                    Query query = new Query();
                    query.setFilterById(enqueue);
                    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                    Cursor c = dm.query(query);
                    if (c.moveToFirst()) {
                        hideProgress();
                        int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
                        if (DownloadManager.STATUS_SUCCESSFUL == status) {
                            storeDownload(dm, downloadId);
                            installDownload();
                        } else {
                            int reason = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
                            Toast.makeText(context,"Download failed (" + status + "): " + reason, Toast.LENGTH_LONG).show();
                        }
                    } else {
                        Toast.makeText(context,"Download diappeared!", Toast.LENGTH_LONG).show();
                    }
                    c.close();
                }
            } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
                if (intent.getData().toString().equals("package:org.ruboto.core")) {
                    Toast.makeText(context,"Ruboto Core is now installed.",Toast.LENGTH_LONG).show();
                    deleteFile(RUBOTO_APK);
                    if (receiver != null) {
                        unregisterReceiver(receiver);
                        receiver = null;
                    }
                    initJRuby(false);
                } else {
                    Toast.makeText(context,"Installed: " + intent.getData().toString(),Toast.LENGTH_LONG).show();
                }
            }
        }
        };
    IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
    filter.addDataScheme("package");
    registerReceiver(receiver, filter);
    IntentFilter download_filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
    registerReceiver(receiver, download_filter);
}