Java Code Examples for com.liulishuo.filedownloader.FileDownloader

The following examples show how to use com.liulishuo.filedownloader.FileDownloader. These examples are extracted from open source projects. 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 Project: v9porn   Source File: DownloadManager.java    License: MIT License 6 votes vote down vote up
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 2
Source Project: v9porn   Source File: MainActivity.java    License: MIT License 6 votes vote down vote up
@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 Project: v9porn   Source File: DownloadManager.java    License: MIT License 6 votes vote down vote up
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 Project: v9porn   Source File: MainActivity.java    License: MIT License 6 votes vote down vote up
@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 Project: okdownload   Source File: ProgressAssistTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 Project: okdownload   Source File: ProgressAssistTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 Project: okdownload   Source File: FileDownloadUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 Project: okdownload   Source File: FileDownloadSerialQueueTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 Project: Aurora   Source File: CacheDownLoadService.java    License: Apache License 2.0 6 votes vote down vote up
@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 Project: Simpler   Source File: App.java    License: Apache License 2.0 6 votes vote down vote up
@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 11
@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 12
@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 13
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 14
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 15
@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 16
Source Project: FileDownloader   Source File: HybridTestActivity.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 17
Source Project: FileDownloader   Source File: HybridTestActivity.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 18
Source Project: FileDownloader   Source File: NotificationSampleActivity.java    License: Apache License 2.0 6 votes vote down vote up
@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 19
Source Project: v9porn   Source File: DownloadManager.java    License: MIT License 5 votes vote down vote up
/**
 * 实时保存下载信息
 *
 * @param task 任务信息
 */
private void saveDownloadInfo(BaseDownloadTask task) {
    V9PornItem v9PornItem = dataManager.findV9PornItemByDownloadId(task.getId());
    if (v9PornItem == null) {
        //不存在的任务清除掉
        FileDownloader.getImpl().clear(task.getId(), task.getPath());
        if (!BuildConfig.DEBUG) {
          //  Bugsnag.notify(new Throwable(TAG + "::save download info failure:" + task.getUrl()), Severity.WARNING);
        }
        return;
    }
    int soFarBytes = task.getSmallFileSoFarBytes();
    int totalBytes = task.getSmallFileTotalBytes();
    if (soFarBytes > 0) {
        v9PornItem.setSoFarBytes(soFarBytes);
    }

    if (totalBytes > 0) {
        v9PornItem.setTotalFarBytes(totalBytes);
    }
    if (totalBytes > 0) {
        int p = (int) (((float) soFarBytes / totalBytes) * 100);
        v9PornItem.setProgress(p);
    }
    if (task.getStatus() == FileDownloadStatus.completed) {
        v9PornItem.setFinishedDownloadDate(new Date());
    }
    v9PornItem.setSpeed(task.getSpeed());
    v9PornItem.setStatus(task.getStatus());
    dataManager.updateV9PornItem(v9PornItem);
    if (task.getStatus() == FileDownloadStatus.completed) {
        complete(task);
    } else {
        update(task);
    }
}
 
Example 20
Source Project: v9porn   Source File: DownloadingFragment.java    License: MIT License 5 votes vote down vote up
@Override
public void connected() {
    Logger.t(TAG).d("连接上下载服务");
    List<V9PornItem> v9PornItems = presenter.loadDownloadingDatas();
    for (V9PornItem v9PornItem : v9PornItems) {
        int status = FileDownloader.getImpl().getStatus(v9PornItem.getVideoResult().getVideoUrl(), v9PornItem.getDownLoadPath(presenter.getCustomDownloadVideoDirPath()));
        Logger.t(TAG).d("fix status:::" + status);
        if (status != v9PornItem.getStatus()) {
            v9PornItem.setStatus(status);
            presenter.updateV9PornItem(v9PornItem);
        }
    }
    presenter.loadDownloadingData();
}
 
Example 21
Source Project: v9porn   Source File: DownloadingFragment.java    License: MIT License 5 votes vote down vote up
@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 22
Source Project: YCAudioPlayer   Source File: CacheDownloadingAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onClick(View v) {
    if (v.getTag() == null) {
        return;
    }
    AppLogUtils.e("listener----"+"--------");
    int imgResId = (int) holder.ivDownload.getTag();
    TasksManagerModel model = list.get(holder.position);
    String path = model.getPath();
    String url = model.getUrl();
    AppLogUtils.e("listener----"+url+ "--------");
    switch (imgResId) {
        case R.drawable.ic_note_btn_play_white:
            AppLogUtils.e("listener----"+"------开始下载--");
            // 开始下载
            final BaseDownloadTask task = FileDownloader.getImpl().create(url)
                    .setPath(path)
                    .setCallbackProgressTimes(500)
                    .setListener(new TaskFileDownloadListener());
            TasksManager.getImpl().addTaskForViewHolder(task);
            TasksManager.getImpl().updateViewHolder(holder.id, holder);
            task.start();
            break;
        case R.drawable.ic_note_btn_pause_white:
            AppLogUtils.e("listener----"+"------暂停下载--");
            // 暂停下载
            FileDownloader.getImpl().pause(holder.id);
            holder.ivDownload.setBackgroundResource(R.drawable.ic_note_btn_play_white);
            holder.ivDownload.setTag(R.drawable.ic_note_btn_play_white);
            break;
        default:
            break;
    }
}
 
Example 23
Source Project: YCAudioPlayer   Source File: TasksManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 创建的时候调用
 */
public void onCreate(final WeakReference<RecyclerView.Adapter> weakReference) {
    if (!FileDownloader.getImpl().isServiceConnected()) {
        FileDownloader.getImpl().bindService();
        registerServiceConnectionListener(weakReference);
    }
}
 
Example 24
Source Project: YCAudioPlayer   Source File: TasksManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 注销服务连接
 */
private void unregisterServiceConnectionListener() {
    if(listener!=null){
        FileDownloader.getImpl().removeServiceConnectListener(listener);
        listener = null;
    }
}
 
Example 25
Source Project: YCAudioPlayer   Source File: TasksUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 开始下载
 * @param url               下载链接
 */
public static void start(String url , String path){
    final BaseDownloadTask task = FileDownloader.getImpl().create(url)
            .setPath(path)
            .setCallbackProgressTimes(500)
            .setListener(new TaskFileDownloadListener());
    TasksManager.getImpl().addTaskForViewHolder(task);
    TasksManager.getImpl().addTask(url,path);
    task.start();
}
 
Example 26
Source Project: styT   Source File: bilI.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.bilii);
    // FileDownloader.setup(this);
    FileDownloader.init(this);
    Intent intent = new Intent(this, DownloadService.class);
    startService(intent);
    bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
    }

}
 
Example 27
Source Project: v9porn   Source File: DownloadManager.java    License: MIT License 5 votes vote down vote up
/**
 * 实时保存下载信息
 *
 * @param task 任务信息
 */
private void saveDownloadInfo(BaseDownloadTask task) {
    V9PornItem v9PornItem = dataManager.findV9PornItemByDownloadId(task.getId());
    if (v9PornItem == null) {
        //不存在的任务清除掉
        FileDownloader.getImpl().clear(task.getId(), task.getPath());
        if (!BuildConfig.DEBUG) {
          //  Bugsnag.notify(new Throwable(TAG + "::save download info failure:" + task.getUrl()), Severity.WARNING);
        }
        return;
    }
    int soFarBytes = task.getSmallFileSoFarBytes();
    int totalBytes = task.getSmallFileTotalBytes();
    if (soFarBytes > 0) {
        v9PornItem.setSoFarBytes(soFarBytes);
    }

    if (totalBytes > 0) {
        v9PornItem.setTotalFarBytes(totalBytes);
    }
    if (totalBytes > 0) {
        int p = (int) (((float) soFarBytes / totalBytes) * 100);
        v9PornItem.setProgress(p);
    }
    if (task.getStatus() == FileDownloadStatus.completed) {
        v9PornItem.setFinishedDownloadDate(new Date());
    }
    v9PornItem.setSpeed(task.getSpeed());
    v9PornItem.setStatus(task.getStatus());
    dataManager.updateV9PornItem(v9PornItem);
    if (task.getStatus() == FileDownloadStatus.completed) {
        complete(task);
    } else {
        update(task);
    }
}
 
Example 28
Source Project: v9porn   Source File: DownloadingFragment.java    License: MIT License 5 votes vote down vote up
@Override
public void connected() {
    Logger.t(TAG).d("连接上下载服务");
    List<V9PornItem> v9PornItems = presenter.loadDownloadingDatas();
    for (V9PornItem v9PornItem : v9PornItems) {
        int status = FileDownloader.getImpl().getStatus(v9PornItem.getVideoResult().getVideoUrl(), v9PornItem.getDownLoadPath(presenter.getCustomDownloadVideoDirPath()));
        Logger.t(TAG).d("fix status:::" + status);
        if (status != v9PornItem.getStatus()) {
            v9PornItem.setStatus(status);
            presenter.updateV9PornItem(v9PornItem);
        }
    }
    presenter.loadDownloadingData();
}
 
Example 29
Source Project: v9porn   Source File: DownloadingFragment.java    License: MIT License 5 votes vote down vote up
@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 Project: okdownload   Source File: DownloadMgrInitialParams.java    License: Apache License 2.0 5 votes vote down vote up
public void commit() {
    FileDownloader.setup(mContext);
    OkDownload.Builder builder = FileDownloader.okDownloadBuilder(mContext, null);
    if (mOutputStreamCreator != null) {
        if (builder == null) builder = new OkDownload.Builder(mContext);
        builder.outputStreamFactory(
                new DownloadOutputStreamAdapter.Factory(mOutputStreamCreator));
    }
    if (mConnectionCreator != null) {
        if (builder == null) builder = new OkDownload.Builder(mContext);
        builder.connectionFactory(
                new DownloadConnectionAdapter.Factory(mConnectionCreator));
    }
    if (builder != null) OkDownload.setSingletonInstance(builder.build());
}