com.liulishuo.filedownloader.FileDownloader Java Examples
The following examples show how to use
com.liulishuo.filedownloader.FileDownloader.
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: NotificationSampleActivity.java From FileDownloader with Apache License 2.0 | 6 votes |
@SuppressWarnings("ResultOfMethodCallIgnored") public void onClickDelete(final View view) { FileDownloader.getImpl().pause(listener); new Thread(new Runnable() { @Override public void run() { final File file = new File(savePath); if (file.isFile()) file.delete(); if (file.exists()) { final File[] files = file.listFiles(); if (files == null) return; for (File f : files) { f.delete(); } file.delete(); } } }).start(); }
Example #2
Source File: MainActivity.java From v9porn with MIT License | 6 votes |
@Override public void onBackPressed() { if (mCurrentFragment instanceof BaseMainFragment && ((BaseMainFragment) mCurrentFragment).onBackPressed()) { return; } showMessage("再次点击退出程序", TastyToast.INFO); long currentTime = Calendar.getInstance().getTimeInMillis(); if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) { lastClickTime = currentTime; } else { FileDownloader.getImpl().pauseAll(); FileDownloader.getImpl().unBindService(); //没啥意义 if (!existActivityWithAnimation && !isFinishing()) { super.onBackPressed(); } finishAffinity(); new Handler().postDelayed(() -> { int pid = android.os.Process.myPid(); android.os.Process.killProcess(pid); }, 500); } }
Example #3
Source File: DownloadManager.java From v9porn with MIT License | 6 votes |
public int startDownload(String url, final String path, boolean isDownloadNeedWifi, boolean isForceReDownload) { Logger.t(TAG).d("url::" + url); Logger.t(TAG).d("path::" + path); Logger.t(TAG).d("isDownloadNeedWifi::" + isDownloadNeedWifi); Logger.t(TAG).d("isForceReDownload::" + isForceReDownload); int id = FileDownloader.getImpl().create(url) .setPath(path) .setListener(lis) .setWifiRequired(isDownloadNeedWifi) .setAutoRetryTimes(3) .setForceReDownload(isForceReDownload) .asInQueueTask() .enqueue(); FileDownloader.getImpl().start(lis, false); return id; }
Example #4
Source File: MainActivity.java From v9porn with MIT License | 6 votes |
@Override public void onBackPressed() { if (mCurrentFragment instanceof BaseMainFragment && ((BaseMainFragment) mCurrentFragment).onBackPressed()) { return; } showMessage("再次点击退出程序", TastyToast.INFO); long currentTime = Calendar.getInstance().getTimeInMillis(); if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) { lastClickTime = currentTime; } else { FileDownloader.getImpl().pauseAll(); FileDownloader.getImpl().unBindService(); //没啥意义 if (!existActivityWithAnimation && !isFinishing()) { super.onBackPressed(); } finishAffinity(); new Handler().postDelayed(() -> { int pid = android.os.Process.myPid(); android.os.Process.killProcess(pid); }, 500); } }
Example #5
Source File: ProgressAssistTest.java From okdownload with Apache License 2.0 | 6 votes |
@Test public void onProgress() { final ProgressAssist progressAssist = new ProgressAssist(5); progressAssist.calculateCallbackMinIntervalBytes(100); assertThat(progressAssist.callbackMinIntervalBytes).isEqualTo(20); final DownloadTaskAdapter mockTask = spy(FileDownloader.getImpl().create("url")); final CompatListenerAssist.CompatListenerAssistCallback callback = mock(CompatListenerAssist.CompatListenerAssistCallback.class); doReturn(100L).when(mockTask).getTotalBytesInLong(); for (int i = 0; i < 100; i++) { progressAssist.onProgress(mockTask, 1, callback); } verify(callback, times(5)).progress(eq(mockTask), anyLong(), eq(100L)); assertThat(progressAssist.getSofarBytes()).isEqualTo(100); }
Example #6
Source File: ProgressAssistTest.java From okdownload with Apache License 2.0 | 6 votes |
@Test public void onProgress_noAnyProgress() { final SpeedCalculator mockSpeedCalculator = mock(SpeedCalculator.class); final ProgressAssist progressAssist = new ProgressAssist(-1, mockSpeedCalculator); progressAssist.calculateCallbackMinIntervalBytes(100); assertThat(progressAssist.callbackMinIntervalBytes) .isEqualTo(ProgressAssist.NO_ANY_PROGRESS_CALLBACK); final DownloadTaskAdapter mockTask = spy(FileDownloader.getImpl().create("url")); final CompatListenerAssist.CompatListenerAssistCallback callback = mock(CompatListenerAssist.CompatListenerAssistCallback.class); doReturn(100L).when(mockTask).getTotalBytesInLong(); for (int i = 0; i < 100; i++) { progressAssist.onProgress(mockTask, 1, callback); } verify(mockSpeedCalculator, times(100)).downloading(1); verify(callback, never()).progress(any(DownloadTaskAdapter.class), anyLong(), anyLong()); assertThat(progressAssist.getSofarBytes()).isEqualTo(100); }
Example #7
Source File: FileDownloadUtilsTest.java From okdownload with Apache License 2.0 | 6 votes |
@Test public void findDownloadTaskAdapter() { DownloadTask downloadTask = mock(DownloadTask.class); DownloadTaskAdapter downloadTaskAdapter = FileDownloadUtils .findDownloadTaskAdapter(downloadTask); assertNull(downloadTaskAdapter); final String url = "url"; final String path = "path"; final DownloadTaskAdapter mockDownloadTaskAdapter = (DownloadTaskAdapter) FileDownloader.getImpl().create(url).setPath(path); mockDownloadTaskAdapter.insureAssembleDownloadTask(); downloadTaskAdapter = FileDownloadUtils .findDownloadTaskAdapter(mockDownloadTaskAdapter.getDownloadTask()); assertThat(downloadTaskAdapter).isEqualTo(mockDownloadTaskAdapter); final DownloadTaskAdapter sameIdTask = (DownloadTaskAdapter) FileDownloader.getImpl().create(url).setPath(path); sameIdTask.insureAssembleDownloadTask(); assertThat(sameIdTask.getId()).isEqualTo(mockDownloadTaskAdapter.getId()); downloadTaskAdapter = FileDownloadUtils .findDownloadTaskAdapter(sameIdTask.getDownloadTask()); assertThat(downloadTaskAdapter).isEqualTo(sameIdTask); assertThat(sameIdTask).isNotEqualTo(mockDownloadTaskAdapter); }
Example #8
Source File: FileDownloadSerialQueueTest.java From okdownload with Apache License 2.0 | 6 votes |
@Test public void enqueue() { final DownloadTaskAdapter mockBaseTask = spy(FileDownloader.getImpl().create("url")); final DownloadTask mockDownloadTask = mock(DownloadTask.class); final CompatListenerAdapter mockCompatListener = mock(CompatListenerAdapter.class); final int taskId = 1; doReturn(taskId).when(mockBaseTask).getId(); doReturn(mockDownloadTask).when(mockBaseTask).getDownloadTask(); doReturn(mockCompatListener).when(mockBaseTask).getCompatListener(); doNothing().when(mockBaseTask).insureAssembleDownloadTask(); fileDownloadSerialQueue.enqueue(mockBaseTask); verify(mockBaseTask).insureAssembleDownloadTask(); verify(fileDownloadList).addIndependentTask(mockBaseTask); verify(listenerManager).addAutoRemoveListenersWhenTaskEnd(taskId); verify(listenerManager).attachListener(mockDownloadTask, mockCompatListener); verify(serialQueue).enqueue(mockDownloadTask); }
Example #9
Source File: CacheDownLoadService.java From Aurora with Apache License 2.0 | 6 votes |
@Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent.getBooleanExtra(PAUSE_DOWNLOAD, false)) { queue.pause(); return START_REDELIVER_INTENT; } VideoDownLoadInfo video = (VideoDownLoadInfo) intent.getSerializableExtra(VIDEOS_INFO); EventBus.getDefault().postSticky(video,EventBusTags.CACHE_DOWNLOAD_BEGIN); videos.put(video.getId()+"",video); File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Sunny_Videos"); if (!dir.exists()) { dir.mkdirs(); } DaoMaster master = GreenDaoHelper.getInstance().create(video.getDbName()).getMaster(); master.newSession().startAsyncSession().insertOrReplace(video); File file = new File(dir.getAbsolutePath(), video.getId() + ".mp4"); BaseDownloadTask task = (FileDownloader.getImpl().create(video.getVideo().getPlayUrl()).setPath(file.getAbsolutePath()).setTag(video.getId()+"")); task.setListener(new CommonDownloadListener()); queue.enqueue(task); if (isInit){ queue.resume(); isInit = false; } return START_NOT_STICKY; }
Example #10
Source File: ApplicationModule.java From aptoide-client-v8 with GNU General Public License v3.0 | 6 votes |
@Provides @Singleton FileDownloaderProvider providesFileDownloaderProvider( @Named("cachePath") String cachePath, @Named("user-agent") Interceptor userAgentInterceptor, AuthenticationPersistence authenticationPersistence, DownloadAnalytics downloadAnalytics, InstallAnalytics installAnalytics, Md5Comparator md5Comparator) { final OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder().addInterceptor(userAgentInterceptor) .addInterceptor(new DownloadMirrorEventInterceptor(downloadAnalytics, installAnalytics)) .connectTimeout(20, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS); FileDownloader.init(application, new DownloadMgrInitialParams.InitCustomMaker().connectionCreator( new OkHttp3Connection.Creator(httpClientBuilder))); return new FileDownloadManagerProvider(cachePath, FileDownloader.getImpl(), md5Comparator); }
Example #11
Source File: FileDownloaderExecutor.java From Mysplash with GNU Lesser General Public License v3.0 | 6 votes |
@NonNull @Override public List<DownloadTask> clearTask(Context c) { List<DownloadTask> taskList = new ArrayList<>(); lockableTaskList.write((list, setter) -> { taskList.addAll(list); clearDownloadingTask(list); setter.setList(list); FileDownloader.getImpl().clearAllTaskData(); ComponentFactory.getDatabaseService().clearDownloadTask(); }); return taskList; }
Example #12
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 #13
Source File: DownloadHelper.java From Mysplash with GNU Lesser General Public License v3.0 | 6 votes |
private long addMission(Context c, DownloadMissionEntity entity) { FileUtils.deleteFile(entity); final OnDownloadListener listener = new OnDownloadListener(c.getApplicationContext(), entity); entity.missionId = FileDownloader.getImpl() .create(entity.downloadUrl) .setPath(entity.getFilePath()) .setCallbackProgressMinInterval(NotificationHelper.REFRESH_RATE) .setListener(listener) .asInQueueTask() .enqueue(); FileDownloader.getImpl().start(listener, false); entity.result = DownloadHelper.RESULT_DOWNLOADING; DatabaseHelper.getInstance(c).writeDownloadTask(entity); NotificationHelper.showSnackbar( c.getString(R.string.feedback_download_start), Snackbar.LENGTH_SHORT); return entity.missionId; }
Example #14
Source File: DownloadHelper.java From Mysplash with GNU Lesser General Public License v3.0 | 6 votes |
@Nullable public DownloadMission restartMission(Context c, long missionId) { DownloadMissionEntity entity = DatabaseHelper.getInstance(c).readDownloadTask(missionId); if (entity == null) { return null; } else { FileDownloader.getImpl() .clear((int) missionId, entity.getFilePath()); DatabaseHelper.getInstance(c).deleteDownloadTask(missionId); DownloadMission mission = new DownloadMission(entity); mission.entity.missionId = addMission(c, mission.entity); mission.entity.result = RESULT_DOWNLOADING; mission.process = 0; return mission; } }
Example #15
Source File: HybridTestActivity.java From FileDownloader with Apache License 2.0 | 6 votes |
/** * Start multiple download tasks parallel * <p> * 启动并行多任务下载 * * @param view */ public void onClickMultiParallel(final View view) { updateDisplay(getString(R.string.hybrid_test_start_multiple_tasks_parallel, Constant.URLS.length)); // 以相同的listener作为target,将不同的下载任务绑定起来 final FileDownloadListener parallelTarget = createListener(); final List<BaseDownloadTask> taskList = new ArrayList<>(); int i = 0; for (String url : Constant.URLS) { taskList.add(FileDownloader.getImpl().create(url) .setTag(++i)); } totalCounts += taskList.size(); new FileDownloadQueueSet(parallelTarget) .setCallbackProgressTimes(1) .downloadTogether(taskList) .start(); }
Example #16
Source File: HybridTestActivity.java From FileDownloader with Apache License 2.0 | 6 votes |
/** * Start multiple download tasks serial * <p> * 启动串行多任务下载 * * @param view */ public void onClickMultiSerial(final View view) { updateDisplay(getString(R.string.hybrid_test_start_multiple_tasks_serial, Constant.URLS.length)); // 以相同的listener作为target,将不同的下载任务绑定起来 final List<BaseDownloadTask> taskList = new ArrayList<>(); final FileDownloadListener serialTarget = createListener(); int i = 0; for (String url : Constant.URLS) { taskList.add(FileDownloader.getImpl().create(url) .setTag(++i)); } totalCounts += taskList.size(); new FileDownloadQueueSet(serialTarget) .setCallbackProgressTimes(1) .downloadSequentially(taskList) .start(); }
Example #17
Source File: App.java From Simpler with Apache License 2.0 | 6 votes |
@Override public void onCreate() { super.onCreate(); // 所有Activity生命周期回调 registerActivityLifecycleCallbacks(this); mInstance = this; // 实例化SharedPreferences prefs = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE); editor = prefs.edit(); userServices = new UserServices(this); settingsServices = new SettingsServices(this); // 检查工作目录 checkWorkDir(); // 检查存储卡 checkSdCard(); // 友盟场景类型设置接口 MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL); // 初始化ApplicationToast AppToast.init(this); // FileDownloader全局初始化 FileDownloader.init(getApplicationContext()); }
Example #18
Source File: DownloadManager.java From v9porn with MIT License | 6 votes |
public int startDownload(String url, final String path, boolean isDownloadNeedWifi, boolean isForceReDownload) { Logger.t(TAG).d("url::" + url); Logger.t(TAG).d("path::" + path); Logger.t(TAG).d("isDownloadNeedWifi::" + isDownloadNeedWifi); Logger.t(TAG).d("isForceReDownload::" + isForceReDownload); int id = FileDownloader.getImpl().create(url) .setPath(path) .setListener(lis) .setWifiRequired(isDownloadNeedWifi) .setAutoRetryTimes(3) .setForceReDownload(isForceReDownload) .asInQueueTask() .enqueue(); FileDownloader.getImpl().start(lis, false); return id; }
Example #19
Source File: TasksManagerDemoActivity.java From FileDownloader with Apache License 2.0 | 5 votes |
@Override public void onClick(View v) { if (v.getTag() == null) { return; } TaskItemViewHolder holder = (TaskItemViewHolder) v.getTag(); CharSequence action = ((TextView) v).getText(); if (action.equals(v.getResources().getString(R.string.pause))) { // to pause FileDownloader.getImpl().pause(holder.id); } else if (action.equals(v.getResources().getString(R.string.start))) { // to start // to start final TasksManagerModel model = TasksManager.getImpl().get(holder.position); final BaseDownloadTask task = FileDownloader.getImpl().create(model.getUrl()) .setPath(model.getPath()) .setCallbackProgressTimes(100) .setListener(taskDownloadListener); TasksManager.getImpl() .addTaskForViewHolder(task); TasksManager.getImpl() .updateViewHolder(holder.id, holder); task.start(); } else if (action.equals(v.getResources().getString(R.string.delete))) { // to delete new File(TasksManager.getImpl().get(holder.position).getPath()).delete(); holder.taskActionBtn.setEnabled(true); holder.updateNotDownloaded(FileDownloadStatus.INVALID_STATUS, 0, 0); } }
Example #20
Source File: TasksManagerDemoActivity.java From FileDownloader with Apache License 2.0 | 5 votes |
@Override protected void onDestroy() { TasksManager.getImpl().onDestroy(); adapter = null; FileDownloader.getImpl().pauseAll(); super.onDestroy(); }
Example #21
Source File: DownloadLaunchRunnableTest.java From FileDownloader with Apache License 2.0 | 5 votes |
@Test public void run_noWifiButRequired_callbackNetworkError() { // init context final Application spyApplication = spy(application); when(spyApplication.getApplicationContext()).thenReturn(spyApplication); FileDownloader.setupOnApplicationOnCreate(spyApplication) .database(getMockNonOptDatabaseMaker()) .commit(); // no wifi state mockContextNoWifiState(spyApplication); // pending model final FileDownloadModel model = mock(FileDownloadModel.class); when(model.getId()).thenReturn(1); when(model.getStatus()).thenReturn(FileDownloadStatus.pending); // mock launch runnable. final DownloadStatusCallback callback = mock(DownloadStatusCallback.class); final DownloadLaunchRunnable launchRunnable = DownloadLaunchRunnable.createForTest(callback, model, mock(FileDownloadHeader.class), mock(IThreadPoolMonitor.class), 1000, 100, false, true, 0); launchRunnable.run(); verify(callback).onErrorDirectly(any(FileDownloadNetworkPolicyException.class)); }
Example #22
Source File: DownloadHelper.java From Mysplash with GNU Lesser General Public License v3.0 | 5 votes |
public void removeMission(Context c, long id) { DownloadMissionEntity entity = DatabaseHelper.getInstance(c).readDownloadTask(id); if (entity != null && entity.result != RESULT_SUCCEED) { FileDownloader.getImpl() .clear((int) id, entity.getFilePath()); } DatabaseHelper.getInstance(c).deleteDownloadTask(id); }
Example #23
Source File: DownloadHelper.java From Mysplash with GNU Lesser General Public License v3.0 | 5 votes |
void setForeground(Notification notification) { if (notification != null) { if (!foreground) { foreground = true; FileDownloader.getImpl() .startForeground( NotificationHelper.DOWNLOAD_NOTIFICATION_ID, notification); } } }
Example #24
Source File: DownloadHelper.java From Mysplash with GNU Lesser General Public License v3.0 | 5 votes |
public void setServiceAlive(boolean alive) { if (alive) { FileDownloader.getImpl().bindService(); } else { FileDownloader.getImpl().unBindServiceIfIdle(); } }
Example #25
Source File: FileDownloaderExecutor.java From Mysplash with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void removeTask(Context c, @NonNull DownloadTask task, boolean deleteEntity) { lockableTaskList.write((list, setter) -> { unregisterDownloadingTask(list, task); setter.setList(list); if (task.result != DownloadTask.RESULT_SUCCEED) { FileDownloader.getImpl().clear((int) task.taskId, ""); FileDownloadUtils.deleteTempFile(FileDownloadUtils.getTempPath(task.getFilePath(c))); } if (deleteEntity) { ComponentFactory.getDatabaseService().deleteDownloadTask(task.taskId); } }); }
Example #26
Source File: FileDownloaderExecutor.java From Mysplash with GNU Lesser General Public License v3.0 | 5 votes |
@Override public long restartTask(Context c, @NonNull DownloadTask task) { lockableTaskList.write((list, setter) -> { unregisterDownloadingTask(list, task); setter.setList(list); FileDownloader.getImpl().clear((int) task.taskId, ""); FileDownloadUtils.deleteTempFile(FileDownloadUtils.getTempPath(task.getFilePath(c))); ComponentFactory.getDatabaseService().deleteDownloadTask(task.taskId); }); return addTask(c, task, true); }
Example #27
Source File: FileDownloaderExecutor.java From Mysplash with GNU Lesser General Public License v3.0 | 5 votes |
@Override public long addTask(Context c, @NonNull DownloadTask task, boolean showSnackbar) { TaskDownloadListener l = new TaskDownloadListener(task); task.result = DownloadTask.RESULT_DOWNLOADING; task.process = 0; lockableTaskList.write((list, setter) -> { if (registerDownloadingTask(list, task, l)) { setter.setList(list); task.taskId = FileDownloader.getImpl() .create(task.downloadUrl) .setPath(task.getFilePath(c)) .setCallbackProgressMinInterval(50) .setForceReDownload(true) .setListener(l) .start(); ComponentFactory.getDatabaseService().writeDownloadTask(task); } }); if (showSnackbar) { NotificationHelper.showSnackbar(c.getString(R.string.feedback_download_start)); } return task.taskId; }
Example #28
Source File: FileDownloaderExecutor.java From Mysplash with GNU Lesser General Public License v3.0 | 5 votes |
private FileDownloaderExecutor(Context context) { super(); this.context = context.getApplicationContext(); this.innerListenerList = new ArrayList<>(); FileDownloader.setup(context); FileDownloader.setGlobalPost2UIInterval(100); List<DownloadTask> downloadingList = ComponentFactory.getDatabaseService().readDownloadTaskList( DownloadTask.RESULT_DOWNLOADING); for (DownloadTask t : downloadingList) { finishTask(context, t); } }
Example #29
Source File: DownloadingFragment.java From v9porn with MIT License | 5 votes |
@Override protected void onLazyLoadOnce() { super.onLazyLoadOnce(); if (!FileDownloader.getImpl().isServiceConnected()) { FileDownloader.getImpl().bindService(); Logger.t(TAG).d("启动下载服务"); } else { presenter.loadDownloadingData(); Logger.t(TAG).d("下载服务已经连接"); } }
Example #30
Source File: UpdateAgent.java From TLint with Apache License 2.0 | 5 votes |
private void showUpdateDialog(final UpdateInfo updateInfo) { if (updateInfo != null) { MaterialDialog.Builder builder = new MaterialDialog.Builder(mActivity).title("升级新版本"); builder.positiveText("立刻升级").negativeText("取消").content(Html.fromHtml(updateInfo.updateInfo)); builder.callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { try { String url = updateInfo.updateUrl; mBuilder.setContentTitle(mActivity.getString(R.string.app_name) + "正在更新") .setAutoCancel(true) .setSmallIcon(mActivity.getPackageManager() .getPackageInfo(mActivity.getPackageName(), 0).applicationInfo.icon); destinationUri = Uri.parse(SDCARD_ROOT + File.separator + FormatUtil.getFileNameFromUrl(url)); FileDownloader.getImpl() .create(url) .setPath(SDCARD_ROOT + File.separator + FormatUtil.getFileNameFromUrl(url)) .setListener(listener) .start(); Toast.makeText(mActivity, "开始下载新版本,稍后会开始安装", Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); } } }).show(); } }