com.liulishuo.filedownloader.util.FileDownloadUtils Java Examples
The following examples show how to use
com.liulishuo.filedownloader.util.FileDownloadUtils.
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: FileDownloaderExecutor.java From Mysplash with GNU Lesser General Public License v3.0 | 6 votes |
private static void finishTask(Context context, @NonNull DownloadTask entity) { boolean complete = FileDownloader.getImpl() .getStatus((int) entity.taskId, entity.getFilePath(context)) == FileDownloadStatus.completed; if (complete) { innerUpdateTaskResult(entity, DownloadTask.RESULT_SUCCEED); context.sendBroadcast( new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(entity.getFilePath(context)) ) ); if (entity.downloadType != DownloadTask.COLLECTION_TYPE) { downloadPhotoSuccess(context, entity); } else { downloadCollectionSuccess(context, entity); } } else { FileDownloadUtils.deleteTempFile(FileDownloadUtils.getTempPath(entity.getFilePath(context))); innerUpdateTaskResult(entity, DownloadTask.RESULT_FAILED); if (entity.downloadType != DownloadTask.COLLECTION_TYPE) { downloadPhotoFailed(context, entity); } else { downloadCollectionFailed(context, entity); } } }
Example #2
Source File: TasksUtils.java From YCAudioPlayer with Apache License 2.0 | 6 votes |
/** * 删除所有数据库中的下载内容信息 */ public static void deleteAll(){ File file = new File(FileDownloadUtils.getDefaultSaveRootPath()); if (!file.exists()) { AppLogUtils.e(String.format("check file files not exists %s", file.getAbsolutePath())); return; } if (!file.isDirectory()) { AppLogUtils.e(String.format("check file files not directory %s", file.getAbsolutePath())); return; } File[] files = file.listFiles(); if (files == null) { return; } for (File file1 : files) { //noinspection ResultOfMethodCallIgnored file1.delete(); } if(TasksManager.getImpl().getDownloadedList()!=null){ TasksManager.getImpl().getDownloadedList().clear(); } if(TasksManager.getImpl().getModelList()!=null){ TasksManager.getImpl().getModelList().clear(); } }
Example #3
Source File: TasksManager.java From YCAudioPlayer with Apache License 2.0 | 6 votes |
/** * 将文件音视频内容添加到数据库中 * @param model model */ public void addDownloadedDb(DialogListBean model) { String url = model.getVideo(); String path = TasksManager.getImpl().createPath(url); if (TextUtils.isEmpty(url) || TextUtils.isEmpty(path)) { return ; } final int id = FileDownloadUtils.generateId(url, path); TasksManagerModel bean = new TasksManagerModel(); bean.setId(id); bean.setName(model.getName()); bean.setUrl(url); bean.setUrl(path); modelListed.add(bean); dbController.addDownloadedDb(bean); }
Example #4
Source File: DownloadTask.java From FileDownloader with Apache License 2.0 | 6 votes |
private int startTaskUnchecked() { if (isUsing()) { if (isRunning()) { throw new IllegalStateException( FileDownloadUtils.formatString("This task is running %d, if you" + " want to start the same task, please create a new one by" + " FileDownloader.create", getId())); } else { throw new IllegalStateException("This task is dirty to restart, If you want to " + "reuse this task, please invoke #reuse method manually and retry to " + "restart again." + mHunter.toString()); } } if (!isAttached()) { setAttachKeyDefault(); } mHunter.intoLaunchPool(); return getId(); }
Example #5
Source File: FileDownloadService.java From FileDownloader with Apache License 2.0 | 6 votes |
@Override public void onCreate() { super.onCreate(); FileDownloadHelper.holdContext(this); try { FileDownloadUtils.setMinProgressStep( FileDownloadProperties.getImpl().downloadMinProgressStep); FileDownloadUtils.setMinProgressTime( FileDownloadProperties.getImpl().downloadMinProgressTime); } catch (IllegalAccessException e) { e.printStackTrace(); } final FileDownloadManager manager = new FileDownloadManager(); if (FileDownloadProperties.getImpl().processNonSeparate) { handler = new FDServiceSharedHandler(new WeakReference<>(this), manager); } else { handler = new FDServiceSeparateHandler(new WeakReference<>(this), manager); } PauseAllMarker.clearMarker(); pauseAllMarker = new PauseAllMarker((IFileDownloadIPCService) handler); pauseAllMarker.startPauseAllLooperCheck(); }
Example #6
Source File: DownloadTaskAdapter.java From okdownload with Apache License 2.0 | 6 votes |
DownloadTask build() { if (path == null) { path = FileDownloadUtils.getDefaultSaveFilePath(url); } @NonNull DownloadTask.Builder builder; if (pathAsDirectory) { builder = new DownloadTask.Builder(url, path, null); } else { builder = new DownloadTask.Builder(url, new File(path)); } builder.setMinIntervalMillisCallbackProcess(minIntervalMillisCallbackProgress); builder.setPassIfAlreadyCompleted(!forceReDownload); builder.setWifiRequired(isWifiRequired); for (Map.Entry<String, String> entry : headerMap.entrySet()) { builder.addHeader(entry.getKey(), entry.getValue()); } builder.setAutoCallbackToUIThread(autoCallbackToUIThread); return builder.build(); }
Example #7
Source File: FileDownloadServiceSharedTransmit.java From FileDownloader with Apache License 2.0 | 6 votes |
@Override public void bindStartByContext(Context context, Runnable connectedRunnable) { if (connectedRunnable != null) { if (!connectedRunnableList.contains(connectedRunnable)) { connectedRunnableList.add(connectedRunnable); } } Intent i = new Intent(context, SERVICE_CLASS); runServiceForeground = FileDownloadUtils.needMakeServiceForeground(context); i.putExtra(ExtraKeys.IS_FOREGROUND, runServiceForeground); if (runServiceForeground) { if (FileDownloadLog.NEED_LOG) FileDownloadLog.d(this, "start foreground service"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(i); } else { context.startService(i); } }
Example #8
Source File: TasksManager.java From YCAudioPlayer with Apache License 2.0 | 6 votes |
/** * 将某个链接资源添加到下载的队列中 * @param url 资源url * @param path 路径 * @return model */ public TasksManagerModel addTask(final String url, final String path) { if (TextUtils.isEmpty(url) || TextUtils.isEmpty(path)) { return null; } //根据链接和地址查找对应id final int id = FileDownloadUtils.generateId(url, path); TasksManagerModel model = getById(id); if (model != null) { return model; } //天机到数据库 final TasksManagerModel newModel = dbController.addTask(url, path); if (newModel != null) { modelList.add(newModel); } return newModel; }
Example #9
Source File: DownloadTaskAdapterTest.java From okdownload with Apache License 2.0 | 6 votes |
@Test public void build_default() { final FileDownloadListener mockListener = mock(FileDownloadListener.class); final DownloadTaskAdapter taskAdapter = (DownloadTaskAdapter) FileDownloader.getImpl() .create("url").setListener(mockListener); FileDownloadUtils.setDefaultSaveRootPath("/sdcard"); taskAdapter.insureAssembleDownloadTask(); assertThat(taskAdapter.getPath()) .isEqualTo(FileDownloadUtils.getDefaultSaveFilePath("url")); assertThat(taskAdapter.getCallbackProgressMinInterval()) .isEqualTo(DownloadTaskAdapter.DEFAULT_CALLBACK_PROGRESS_MIN_INTERVAL_MILLIS); assertThat(taskAdapter.isSyncCallback()).isFalse(); assertThat(taskAdapter.isWifiRequired()).isFalse(); assertThat(taskAdapter.isForceReDownload()).isFalse(); }
Example #10
Source File: ConnectionProfile.java From FileDownloader with Apache License 2.0 | 6 votes |
public void processProfile(FileDownloadConnection connection) throws ProtocolException { if (isForceNoRange) return; if (isTrialConnect && FileDownloadProperties.getImpl().trialConnectionHeadMethod) { connection.setRequestMethod("HEAD"); } final String range; if (endOffset == RANGE_INFINITE) { range = FileDownloadUtils.formatString("bytes=%d-", currentOffset); } else { range = FileDownloadUtils .formatString("bytes=%d-%d", currentOffset, endOffset); } connection.addHeader("Range", range); }
Example #11
Source File: SingleTaskTestActivity.java From FileDownloader with Apache License 2.0 | 6 votes |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_single); llsApkFilePath = FileDownloadUtils.getDefaultSaveRootPath() + File.separator + "tmpdir1" + File.separator + Constant.LIULISHUO_CONTENT_DISPOSITION_FILENAME; llsApkDir = FileDownloadUtils.getDefaultSaveRootPath() + File.separator + "tmpdir1"; normalTaskFilePath = FileDownloadUtils.getDefaultSaveRootPath() + File.separator + "tmp2"; chunkedFilePath = FileDownloadUtils.getDefaultSaveRootPath() + File.separator + "chunked_data_tmp1"; assignViews(); initFilePathEqualDirAndFileName(); initNormalDataAction(); initChunkTransferEncodingDataAction(); }
Example #12
Source File: HybridTestActivity.java From FileDownloader with Apache License 2.0 | 6 votes |
public void onClickDel(final View view) { File file = new File(FileDownloadUtils.getDefaultSaveRootPath()); if (!file.exists()) { Log.w(TAG, String.format("check file files not exists %s", file.getAbsolutePath())); return; } if (!file.isDirectory()) { Log.w(TAG, String.format("check file files not directory %s", file.getAbsolutePath())); return; } File[] files = file.listFiles(); if (files == null) { updateDisplay(getString(R.string.del_file_error_empty)); return; } for (File file1 : files) { file1.delete(); updateDisplay(getString(R.string.hybrid_test_deleted_file, file1.getName())); } }
Example #13
Source File: DownloadStatusCallback.java From FileDownloader with Apache License 2.0 | 6 votes |
void onConnected(boolean isResume, long totalLength, String etag, String fileName) throws IllegalArgumentException { final String oldEtag = model.getETag(); if (oldEtag != null && !oldEtag.equals(etag)) throw new IllegalArgumentException(FileDownloadUtils.formatString("callback " + "onConnected must with precondition succeed, but the etag is " + "changes(%s != %s)", etag, oldEtag)); // direct processParams.setResuming(isResume); model.setStatus(FileDownloadStatus.connected); model.setTotal(totalLength); model.setETag(etag); model.setFilename(fileName); database.updateConnected(model.getId(), totalLength, etag, fileName); onStatusChanged(FileDownloadStatus.connected); callbackMinIntervalBytes = calculateCallbackMinIntervalBytes(totalLength, callbackProgressMaxCount); needSetProcess.compareAndSet(false, true); }
Example #14
Source File: TasksManagerDemoActivity.java From FileDownloader with Apache License 2.0 | 6 votes |
public TasksManagerModel addTask(final String url, final String path) { if (TextUtils.isEmpty(url) || TextUtils.isEmpty(path)) { return null; } final int id = FileDownloadUtils.generateId(url, path); TasksManagerModel model = getById(id); if (model != null) { return model; } final TasksManagerModel newModel = dbController.addTask(url, path); if (newModel != null) { modelList.add(newModel); } return newModel; }
Example #15
Source File: TasksManagerDemoActivity.java From FileDownloader with Apache License 2.0 | 6 votes |
public TasksManagerModel addTask(final String url, final String path) { if (TextUtils.isEmpty(url) || TextUtils.isEmpty(path)) { return null; } // have to use FileDownloadUtils.generateId to associate TasksManagerModel with FileDownloader final int id = FileDownloadUtils.generateId(url, path); TasksManagerModel model = new TasksManagerModel(); model.setId(id); model.setName(DemoApplication.CONTEXT.getString(R.string.tasks_manager_demo_name, id)); model.setUrl(url); model.setPath(path); final boolean succeed = db.insert(TABLE_NAME, null, model.toContentValues()) != -1; return succeed ? model : null; }
Example #16
Source File: DownloadLaunchRunnable.java From FileDownloader with Apache License 2.0 | 6 votes |
private void checkupBeforeConnect() throws FileDownloadGiveUpRetryException { // 1. check whether need access-network-state permission? if (isWifiRequired && !FileDownloadUtils.checkPermission(Manifest.permission.ACCESS_NETWORK_STATE)) { throw new FileDownloadGiveUpRetryException( FileDownloadUtils.formatString("Task[%d] can't start the download runnable," + " because this task require wifi, but user application " + "nor current process has %s, so we can't check whether " + "the network type connection.", model.getId(), Manifest.permission.ACCESS_NETWORK_STATE)); } // 2. check whether need wifi to download? if (isWifiRequired && FileDownloadUtils.isNetworkNotOnWifiType()) { throw new FileDownloadNetworkPolicyException(); } }
Example #17
Source File: DownloadLaunchRunnable.java From FileDownloader with Apache License 2.0 | 6 votes |
@Override public boolean isRetry(Exception exception) { if (exception instanceof FileDownloadHttpException) { final FileDownloadHttpException httpException = (FileDownloadHttpException) exception; final int code = httpException.getCode(); if (isSingleConnection && code == HTTP_REQUESTED_RANGE_NOT_SATISFIABLE) { if (!isTriedFixRangeNotSatisfiable) { FileDownloadUtils .deleteTaskFiles(model.getTargetFilePath(), model.getTempFilePath()); isTriedFixRangeNotSatisfiable = true; return true; } } } return validRetryTimes > 0 && !(exception instanceof FileDownloadGiveUpRetryException); }
Example #18
Source File: DownloadLaunchRunnable.java From FileDownloader with Apache License 2.0 | 6 votes |
private void handlePreAllocate(long totalLength, String path) throws IOException, IllegalAccessException { FileDownloadOutputStream outputStream = null; try { if (totalLength != TOTAL_VALUE_IN_CHUNKED_RESOURCE) { outputStream = FileDownloadUtils.createOutputStream(model.getTempFilePath()); final long breakpointBytes = new File(path).length(); final long requiredSpaceBytes = totalLength - breakpointBytes; final long freeSpaceBytes = FileDownloadUtils.getFreeSpaceBytes(path); if (freeSpaceBytes < requiredSpaceBytes) { // throw a out of space exception. throw new FileDownloadOutOfSpaceException(freeSpaceBytes, requiredSpaceBytes, breakpointBytes); } else if (!FileDownloadProperties.getImpl().fileNonPreAllocation) { // pre allocate. outputStream.setLength(totalLength); } } } finally { if (outputStream != null) outputStream.close(); } }
Example #19
Source File: FileDownloader.java From FileDownloader with Apache License 2.0 | 6 votes |
/** * Clear the data with the provided {@code id}. * Normally used to deleting the data in filedownloader database, when it is paused or in * downloading status. If you want to re-download it clearly. * <p/> * <strong>Note:</strong> YOU NO NEED to clear the data when it is already completed downloading * because the data would be deleted when it completed downloading automatically by * FileDownloader. * <p> * If there are tasks with the {@code id} in downloading, will be paused first; * If delete the data with the {@code id} in the filedownloader database successfully, will try * to delete its intermediate downloading file and downloaded file. * * @param id the download {@code id}. * @param targetFilePath the target path. * @return {@code true} if the data with the {@code id} in filedownloader database was deleted, * and tasks with the {@code id} was paused; {@code false} otherwise. */ public boolean clear(final int id, final String targetFilePath) { pause(id); if (FileDownloadServiceProxy.getImpl().clearTaskData(id)) { // delete the task data in the filedownloader database successfully or no data with the // id in filedownloader database. final File intermediateFile = new File(FileDownloadUtils.getTempPath(targetFilePath)); if (intermediateFile.exists()) { //noinspection ResultOfMethodCallIgnored intermediateFile.delete(); } final File targetFile = new File(targetFilePath); if (targetFile.exists()) { //noinspection ResultOfMethodCallIgnored targetFile.delete(); } return true; } return false; }
Example #20
Source File: FileDownloader.java From FileDownloader with Apache License 2.0 | 6 votes |
/** * @param id The downloadId. * @param path The target file path. * @return the downloading status. * @see FileDownloadStatus * @see #getStatus(String, String) * @see #getStatusIgnoreCompleted(int) */ public byte getStatus(final int id, final String path) { byte status; BaseDownloadTask.IRunningTask task = FileDownloadList.getImpl().get(id); if (task == null) { status = FileDownloadServiceProxy.getImpl().getStatus(id); } else { status = task.getOrigin().getStatus(); } if (path != null && status == FileDownloadStatus.INVALID_STATUS) { if (FileDownloadUtils.isFilenameConverted(FileDownloadHelper.getAppContext()) && new File(path).exists()) { status = FileDownloadStatus.completed; } } return status; }
Example #21
Source File: SqliteDatabaseImpl.java From FileDownloader with Apache License 2.0 | 6 votes |
@Override public List<ConnectionModel> findConnectionModel(int id) { final List<ConnectionModel> resultList = new ArrayList<>(); Cursor c = null; try { c = db.rawQuery(FileDownloadUtils.formatString("SELECT * FROM %s WHERE %s = ?", CONNECTION_TABLE_NAME, ConnectionModel.ID), new String[]{Integer.toString(id)}); while (c.moveToNext()) { final ConnectionModel model = new ConnectionModel(); model.setId(id); model.setIndex(c.getInt(c.getColumnIndex(ConnectionModel.INDEX))); model.setStartOffset(c.getLong(c.getColumnIndex(ConnectionModel.START_OFFSET))); model.setCurrentOffset(c.getLong(c.getColumnIndex(ConnectionModel.CURRENT_OFFSET))); model.setEndOffset(c.getLong(c.getColumnIndex(ConnectionModel.END_OFFSET))); resultList.add(model); } } finally { if (c != null) c.close(); } return resultList; }
Example #22
Source File: FileDownloadHttpException.java From FileDownloader with Apache License 2.0 | 5 votes |
public FileDownloadHttpException(final int code, final Map<String, List<String>> requestHeaderMap, final Map<String, List<String>> responseHeaderMap) { super(FileDownloadUtils.formatString("response code error: %d, \n request headers: %s \n " + "response headers: %s", code, requestHeaderMap, responseHeaderMap)); this.mCode = code; this.mRequestHeaderMap = cloneSerializableMap(requestHeaderMap); this.mResponseHeaderMap = cloneSerializableMap(requestHeaderMap); }
Example #23
Source File: FileDownloadTaskAtom.java From FileDownloader with Apache License 2.0 | 5 votes |
public int getId() { if (id != 0) { return id; } return id = FileDownloadUtils.generateId(getUrl(), getPath()); }
Example #24
Source File: DownloadRunnable.java From FileDownloader with Apache License 2.0 | 5 votes |
public DownloadRunnable build() { if (callback == null || path == null || isWifiRequired == null || connectionIndex == null) { throw new IllegalArgumentException(FileDownloadUtils.formatString("%s %s %B", callback, path, isWifiRequired)); } final ConnectTask connectTask = connectTaskBuilder.build(); return new DownloadRunnable(connectTask.downloadId, connectionIndex, connectTask, callback, isWifiRequired, path); }
Example #25
Source File: FileDownloadMessenger.java From FileDownloader with Apache License 2.0 | 5 votes |
@Override public void reAppointment(BaseDownloadTask.IRunningTask task, BaseDownloadTask.LifeCycleCallback callback) { if (this.mTask != null) { throw new IllegalStateException( FileDownloadUtils.formatString("the messenger is working, can't " + "re-appointment for %s", task)); } init(task, callback); }
Example #26
Source File: SqliteDatabaseImpl.java From FileDownloader with Apache License 2.0 | 5 votes |
void onFinishMaintain() { c.close(); if (!needRemoveId.isEmpty()) { String args = TextUtils.join(", ", needRemoveId); if (FileDownloadLog.NEED_LOG) { FileDownloadLog.d(this, "delete %s", args); } //noinspection ThrowFromFinallyBlock db.execSQL(FileDownloadUtils.formatString("DELETE FROM %s WHERE %s IN (%s);", TABLE_NAME, FileDownloadModel.ID, args)); db.execSQL(FileDownloadUtils.formatString("DELETE FROM %s WHERE %s IN (%s);", CONNECTION_TABLE_NAME, ConnectionModel.ID, args)); } }
Example #27
Source File: DownloadTask.java From FileDownloader with Apache License 2.0 | 5 votes |
@Override public int getId() { if (mId != 0) { return mId; } if (!TextUtils.isEmpty(mPath) && !TextUtils.isEmpty(mUrl)) { return mId = FileDownloadUtils.generateId(mUrl, mPath, mPathAsDirectory); } return 0; }
Example #28
Source File: SqliteDatabaseImpl.java From FileDownloader with Apache License 2.0 | 5 votes |
@Override public FileDownloadModel find(final int id) { Cursor c = null; try { c = db.rawQuery(FileDownloadUtils.formatString("SELECT * FROM %s WHERE %s = ?", TABLE_NAME, FileDownloadModel.ID), new String[]{Integer.toString(id)}); if (c.moveToNext()) return createFromCursor(c); } finally { if (c != null) c.close(); } return null; }
Example #29
Source File: RemitDatabase.java From FileDownloader with Apache License 2.0 | 5 votes |
public RemitDatabase() { this.cachedDatabase = new NoDatabaseImpl(); this.realDatabase = new SqliteDatabaseImpl(); this.minInterval = FileDownloadProperties.getImpl().downloadMinProgressTime; final HandlerThread thread = new HandlerThread( FileDownloadUtils.getThreadPoolName("RemitHandoverToDB")); thread.start(); handler = new Handler(thread.getLooper(), new Handler.Callback() { @Override public boolean handleMessage(Message msg) { final int id = msg.what; if (id == WHAT_CLEAN_LOCK) { if (parkThread != null) { LockSupport.unpark(parkThread); parkThread = null; } return false; } try { handlingId.set(id); syncCacheToDB(id); freeToDBIdList.add(id); } finally { handlingId.set(0); if (parkThread != null) { LockSupport.unpark(parkThread); parkThread = null; } } return false; } }); }
Example #30
Source File: DownloadMgrInitialParams.java From FileDownloader with Apache License 2.0 | 5 votes |
@Override public String toString() { return FileDownloadUtils.formatString("component: database[%s], maxNetworkCount[%s]," + " outputStream[%s], connection[%s], connectionCountAdapter[%s]", mDatabaseCustomMaker, mMaxNetworkThreadCount, mOutputStreamCreator, mConnectionCreator, mConnectionCountAdapter); }