下面列出了android.app.DownloadManager#ACTION_DOWNLOAD_COMPLETE 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected void onCreate(Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
getWindow().setStatusBarColor(getIntent().getIntExtra(EXTRA_COLOR, Color.BLACK));
super.onCreate(savedInstanceState);
//noinspection ConstantConditions
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
filter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
registerReceiver(mDownloadReceiver, filter);
mUrl = getIntent().getStringExtra(EXTRA_URL);
setContentView(R.layout.a_web_viewer);
bindView();
mPresenter = new WebViewPresenterImpl(this, this);
mPresenter.validateUrl(mUrl);
}
@Override
public void onReceive(Context context, Intent intent) {
long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
switch (intent.getAction()) {
case DownloadManager.ACTION_DOWNLOAD_COMPLETE:
if (downloadId == downId && downId != -1 && downloadManager != null) {
Uri downIdUri = downloadManager.getUriForDownloadedFile(downloadId);
close();
if (downIdUri != null) {
LogUtil.i(TAG, "广播监听下载完成,APK存储路径为 :" + downIdUri.getPath());
SPUtil.put(Constant.SP_DOWNLOAD_PATH, downIdUri.getPath());
APPUtil.installApk(context, downIdUri);
}
if (onProgressListener != null) {
onProgressListener.onProgress(UNBIND_SERVICE);
}
}
break;
default:
break;
}
}
/**
* Installs an application to the device.
*
* @param url - APK Url should be passed in as a String.
*/
public void installApp(String url, String packageName) {
Toast.makeText(context, "Please wait, Application is being installed.", Toast.LENGTH_LONG).show();
Preference.putString(context, resources.getString(R.string.current_downloading_app), packageName);
if (isPackageInstalled(Constants.AGENT_PACKAGE_NAME)) {
CommonUtils.callAgentApp(context, Constants.Operation.INSTALL_APPLICATION,
url, null);
} else if (isDownloadManagerAvailable(context)) {
downloadedAppName = getAppNameFromPackage(packageName);
IntentFilter filter = new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE);
context.registerReceiver(downloadReceiver, filter);
downloadViaDownloadManager(url, downloadedAppName);
} else {
downloadApp(url);
}
}
public void download(XModel xModel){
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH);
Date now = new Date();
String fileName = formatter.format(now) + "_xStreamPlayer.mp4";
if (!new File(mBaseFolderPath).exists()) {
new File(mBaseFolderPath).mkdir();
}
String mFilePath = "file://" + mBaseFolderPath + fileName;
Uri downloadUri = Uri.parse(xModel.getUrl());
mRequest = new DownloadManager.Request(downloadUri);
mRequest.setDestinationUri(Uri.parse(mFilePath));
//If google drive you need to set cookie
if (xModel.getCookie()!=null){
mRequest.addRequestHeader("cookie", xModel.getCookie());
}
mRequest.setMimeType("video/*");
mRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
mDownloadedFileID = mDownloadManager.enqueue(mRequest);
IntentFilter downloaded = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
activity.registerReceiver(downloadCompletedReceiver, downloaded);
Toast.makeText(activity, "Starting Download : " + fileName, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
try {
intent.setDataAndType(Uri.parse(URLDecoder.decode(xModel.getUrl(), "UTF-8")), "video/mp4");
activity.startActivity(Intent.createChooser(intent, "Download with..."));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
}
}
@Override
public void onResume()throws NullPointerException {
super.onResume();
if (didThemeChange) {
didThemeChange = false;
finish();
startActivity(getIntent());
}
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadBR, filter);
if(updateEnable)
updater(0);
permission();
}
public static void download(DownloadPayload downloadPayload) {
final File file = new File(downloadPayload.getSaveDirectory(), downloadPayload.getFileName());
final String filePath = file.getPath();
XposedBridge.log("[SoundCloud Downloader] Download path: " + filePath);
if (file.exists()) {
Toast.makeText(XposedMod.currentActivity, "File already exists!", Toast.LENGTH_SHORT).show();
return;
}
final DownloadManager downloadManager = (DownloadManager) XposedMod.currentActivity.getSystemService(Context.DOWNLOAD_SERVICE);
final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadPayload.getUrl()));
final IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
request.setTitle(downloadPayload.getTitle());
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationUri(Uri.fromFile(file));
try {
if (downloadPayload.includeMetadata()) {
XposedBridge.log("[SoundCloud Downloader] Adding metadata injector...");
XposedMod.currentActivity.registerReceiver(new MetadataInjector(downloadPayload), filter);
}
downloadManager.enqueue(request);
Toast.makeText(XposedMod.currentActivity, "Downloading...", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
XposedBridge.log("[SoundCloud Downloader] Download Error: " + e.getMessage());
Toast.makeText(XposedMod.currentActivity, "Download failed!", Toast.LENGTH_SHORT).show();
}
}
public ReactNativeDownloadManagerModule(ReactApplicationContext reactContext) {
super(reactContext);
downloader = new Downloader(reactContext);
appDownloads = new LongSparseArray<>();
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
reactContext.registerReceiver(downloadReceiver, filter);
}
public InstaAdapter(Context context) {
this.inContext = context;
this.media = new ArrayList<>();
//set filter to only when download is complete and register broadcast receiver
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
inContext.registerReceiver(downloadReceiver, filter);
}
@Override
public void onReceive(Context context, Intent intent) {
String action = Objects.requireNonNull(intent.getAction());
DebugLog.d(TAG, "onReceive: action=" + action);
DownloadManager manager = (DownloadManager) Objects.requireNonNull(context.getSystemService(Context.DOWNLOAD_SERVICE));
long id = ConfigManager.getPrivateLong(context, ConfigManager.LATEST_RELEASE_DOWNLOAD_ID, NULL_DOWNLOAD_ID);
DebugLog.i(TAG, "id=" + id);
switch (action) {
//下载完成自动打开安装
case DownloadManager.ACTION_DOWNLOAD_COMPLETE:
if (intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0) == id) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(id);
Cursor cursor = manager.query(query);
if (!cursor.moveToFirst()) {
DebugLog.e(TAG, "moveToFirst failed!");
cursor.close();
return;
}
String localFilePath = cursor.getString(cursor.getColumnIndex(
Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
? DownloadManager.COLUMN_LOCAL_URI : DownloadManager.COLUMN_LOCAL_FILENAME));
DebugLog.v(TAG, "Download Completed! -> " + localFilePath);
if (localFilePath.startsWith("file://"))
localFilePath = localFilePath.replace("file://", "");
UIUtils.openFile(context, localFilePath);
cursor.close();
}
break;
//安装完成自动删除
case Intent.ACTION_MY_PACKAGE_REPLACED:
if (id != NULL_DOWNLOAD_ID) {
DebugLog.i(TAG, "delete dl id:" + id + " ret=" + manager.remove(id));
ConfigManager.setPrivateLong(context, ConfigManager.LATEST_RELEASE_DOWNLOAD_ID, NULL_DOWNLOAD_ID);
}
}
}
private void registerReceiver(){
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadCompleteReceiver, filter);
IntentFilter filterReceiver = new IntentFilter(ActionManager.ACTION_FILE_CHANGED);
registerReceiver(fileChangeReceiver, filterReceiver);
}
@Override
protected void handleReceive(final Context context, final Intent data) {
if (data != null && data.getAction() != null) {
switch (data.getAction()) {
case DownloadManager.ACTION_DOWNLOAD_COMPLETE:
handleDownloadCompleteIntent(data);
break;
case DownloadManager.ACTION_NOTIFICATION_CLICKED:
// Open downloads activity
environment.getRouter().showDownloads(context);
break;
}
}
}
private void handleDownloadNotify(long downloadId) {
Intent intent = new Intent(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
intent.putExtra(DownloadManager.EXTRA_DOWNLOAD_ID, downloadId);
new UpdateApkReadyListener().onReceive(context, intent);
}
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);
}
@Rpc(
description =
"Download a file using HTTP. Return content Uri (file remains on device). "
+ "The Uri should be treated as an opaque handle for further operations.")
public String networkHttpDownload(String url)
throws IllegalArgumentException, NetworkingSnippetException {
Uri uri = Uri.parse(url);
List<String> pathsegments = uri.getPathSegments();
if (pathsegments.size() < 1) {
throw new IllegalArgumentException(
String.format(Locale.US, "The Uri %s does not have a path.", uri.toString()));
}
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, pathsegments.get(pathsegments.size() - 1));
mIsDownloadComplete = false;
mReqid = 0;
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
BroadcastReceiver receiver = new DownloadReceiver();
mContext.registerReceiver(receiver, filter);
try {
mReqid = mDownloadManager.enqueue(request);
Log.d(
String.format(
Locale.US,
"networkHttpDownload download of %s with id %d",
url,
mReqid));
if (!Utils.waitUntil(() -> mIsDownloadComplete, 30)) {
Log.d(
String.format(
Locale.US, "networkHttpDownload timed out waiting for completion"));
throw new NetworkingSnippetException("networkHttpDownload timed out.");
}
} finally {
mContext.unregisterReceiver(receiver);
}
Uri resp = mDownloadManager.getUriForDownloadedFile(mReqid);
if (resp != null) {
Log.d(String.format(Locale.US, "networkHttpDownload completed to %s", resp.toString()));
mReqid = 0;
return resp.toString();
} else {
Log.d(
String.format(
Locale.US,
"networkHttpDownload Failed to download %s",
uri.toString()));
throw new NetworkingSnippetException("networkHttpDownload didn't get downloaded file.");
}
}
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);
}
/**
* Start app download for install on device.
*
* @param url - APK Url should be passed in as a String.
* @param operationId - Id of the operation.
* @param operationCode - Requested operation code.
*/
public void setupAppDownload(String url, int operationId, String operationCode) {
Preference.putInt(context, context.getResources().getString(
R.string.app_install_id), operationId);
Preference.putString(context, context.getResources().getString(
R.string.app_install_code), operationCode);
if (url.contains(Constants.APP_DOWNLOAD_ENDPOINT) && Constants.APP_MANAGER_HOST != null) {
url = url.substring(url.lastIndexOf("/"), url.length());
this.appUrl = Constants.APP_MANAGER_HOST + Constants.APP_DOWNLOAD_ENDPOINT + url;
} else if (url.contains(Constants.APP_DOWNLOAD_ENDPOINT)) {
url = url.substring(url.lastIndexOf("/"), url.length());
String ipSaved = Constants.DEFAULT_HOST;
String prefIP = Preference.getString(context, Constants.PreferenceFlag.IP);
if (prefIP != null) {
ipSaved = prefIP;
}
ServerConfig utils = new ServerConfig();
if (ipSaved != null && !ipSaved.isEmpty()) {
utils.setServerIP(ipSaved);
this.appUrl = utils.getAPIServerURL(context) + Constants.APP_DOWNLOAD_ENDPOINT + url;
} else {
Log.e(TAG, "There is no valid IP to contact the server");
}
} else {
this.appUrl = url;
}
Preference.putString(context, context.getResources().getString(
R.string.app_install_status), context.getResources().getString(
R.string.app_status_value_download_started));
if (isDownloadManagerAvailable(context) && !url.contains(Constants.HTTPS_PROTOCOL)) {
IntentFilter filter = new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE);
context.registerReceiver(downloadReceiver, filter);
removeExistingFile();
downloadViaDownloadManager(this.appUrl, resources.getString(R.string.download_mgr_download_file_name));
} else {
downloadApp(this.appUrl);
}
}
public RxDownloader(@NonNull Context context) {
this.context = context.getApplicationContext();
DownloadStatusReceiver downloadStatusReceiver = new DownloadStatusReceiver();
IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
context.registerReceiver(downloadStatusReceiver, intentFilter);
}
static void goToUpdate(Context context, UpdateFrom updateFrom, URL url) {
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
context.registerReceiver(downloadReceiver, filter);
descargar(context, url);
}