com.liulishuo.filedownloader.model.FileDownloadStatus Java Examples

The following examples show how to use com.liulishuo.filedownloader.model.FileDownloadStatus. 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: FileDownloader.java    From FileDownloader with Apache License 2.0 6 votes vote down vote up
/**
 * @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 #2
Source File: CacheDownloadingAdapter.java    From YCAudioPlayer with Apache License 2.0 6 votes vote down vote up
@Override
public void updateNotDownloaded(int status, long sofar, long total) {
    AppLogUtils.e("ViewHolder----"+"updateNotDownloaded--------"+status+"---"+sofar+"---"+total);
    if (sofar > 0 && total > 0) {
        final float percent = sofar / (float) total;
        pb.setProgress((int) (percent * 100));
    } else {
        pb.setProgress(0);
    }
    switch (status) {
        case FileDownloadStatus.error:
            ivDownload.setBackgroundResource(R.drawable.ic_note_btn_play_white);
            ivDownload.setTag(R.drawable.ic_note_btn_play_white);
            tvState.setText("错误");
            break;
        case FileDownloadStatus.paused:
            ivDownload.setBackgroundResource(R.drawable.ic_note_btn_play_white);
            ivDownload.setTag(R.drawable.ic_note_btn_play_white);
            tvState.setText("暂停");
            break;
        default:
            ivDownload.setBackgroundResource(R.drawable.ic_note_btn_play_white);
            ivDownload.setTag(R.drawable.ic_note_btn_play_white);
            break;
    }
}
 
Example #3
Source File: DialogListAdapter.java    From YCAudioPlayer with Apache License 2.0 6 votes vote down vote up
@Override
public void updateNotDownloaded(int status, long sofar, long total) {
    AppLogUtils.e("ViewHolder----"+"updateNotDownloaded--------"+status+"---"+sofar+"---"+total);
    if (sofar > 0 && total > 0) {
        final float percent = sofar / (float) total;
        circlePb.setProgress((int) (percent * 100));
    } else {
        circlePb.setProgress(0);
    }
    switch (status) {
        case FileDownloadStatus.error:
            ivDownload.setBackgroundResource(R.drawable.icon_cache_download);
            tvState.setText("错误");
            break;
        case FileDownloadStatus.paused:
            ivDownload.setBackgroundResource(R.drawable.icon_cache_download);
            tvState.setText("暂停");
            break;
        default:
            ivDownload.setBackgroundResource(R.drawable.icon_cache_download);
            break;
    }
    tvState.setTag(STATE_START);
}
 
Example #4
Source File: TaskFileDownloadListener.java    From YCAudioPlayer with Apache License 2.0 6 votes vote down vote up
/**
 * 队列中
 */
@Override
protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
    super.pending(task, soFarBytes, totalBytes);
    final TaskViewHolderImp tag = checkCurrentHolder(task);
    if (tag == null) {
        return;
    }
    AppLogUtils.e("taskDownloadListener----"+"pending--------");
    if(tag instanceof DialogListAdapter.ViewHolder){
        AppLogUtils.e("taskDownloadListener----"+"pending--------DialogListAdapter");
        ((DialogListAdapter.ViewHolder)tag).updateDownloading(FileDownloadStatus.pending, soFarBytes, totalBytes);
    }
    if(tag instanceof CacheDownloadingAdapter.MyViewHolder){
        AppLogUtils.e("taskDownloadListener----"+"pending--------CacheDownloadingAdapter");
        ((CacheDownloadingAdapter.MyViewHolder)tag).updateDownloading(FileDownloadStatus.pending, soFarBytes, totalBytes);
    }
}
 
Example #5
Source File: FileDownloadList.java    From FileDownloader with Apache License 2.0 6 votes vote down vote up
List<BaseDownloadTask.IRunningTask> getReceiveServiceTaskList(final int id) {
    final List<BaseDownloadTask.IRunningTask> list = new ArrayList<>();
    synchronized (this.mList) {
        for (BaseDownloadTask.IRunningTask task : this.mList) {
            if (task.is(id) && !task.isOver()) {

                final byte status = task.getOrigin().getStatus();
                if (status != FileDownloadStatus.INVALID_STATUS
                        && status != FileDownloadStatus.toLaunchPool) {
                    list.add(task);
                }
            }
        }
    }

    return list;
}
 
Example #6
Source File: TaskFileDownloadListener.java    From YCAudioPlayer with Apache License 2.0 6 votes vote down vote up
/**
 * 状态: 下载中
 */
@Override
protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
    super.progress(task, soFarBytes, totalBytes);
    final TaskViewHolderImp tag = checkCurrentHolder(task);
    if (tag == null) {
        return;
    }
    AppLogUtils.e("taskDownloadListener----"+"progress--------");
    if(tag instanceof DialogListAdapter.ViewHolder){
        AppLogUtils.e("taskDownloadListener----"+"progress--------DialogListAdapter");
        ((DialogListAdapter.ViewHolder)tag).updateDownloading(FileDownloadStatus.progress, soFarBytes, totalBytes);
    }
    if(tag instanceof CacheDownloadingAdapter.MyViewHolder){
        AppLogUtils.e("taskDownloadListener----"+"progress--------CacheDownloadingAdapter");
        ((CacheDownloadingAdapter.MyViewHolder)tag).updateDownloading(FileDownloadStatus.progress, soFarBytes, totalBytes);
    }
}
 
Example #7
Source File: DownloadStatusCallback.java    From FileDownloader with Apache License 2.0 6 votes vote down vote up
private void handleError(Exception exception) {
    Exception errProcessEx = exFiltrate(exception);

    if (errProcessEx instanceof SQLiteFullException) {
        // If the error is sqLite full exception already, no need to  update it to the database
        // again.
        handleSQLiteFullException((SQLiteFullException) errProcessEx);
    } else {
        // Normal case.
        try {

            model.setStatus(FileDownloadStatus.error);
            model.setErrMsg(exception.toString());

            database.updateError(model.getId(), errProcessEx, model.getSoFar());
        } catch (SQLiteFullException fullException) {
            errProcessEx = fullException;
            handleSQLiteFullException((SQLiteFullException) errProcessEx);
        }
    }

    processParams.setException(errProcessEx);
    onStatusChanged(FileDownloadStatus.error);
}
 
Example #8
Source File: TaskFileDownloadListener.java    From YCAudioPlayer with Apache License 2.0 6 votes vote down vote up
/**
 * 状态: 暂停
 */
@Override
protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
    super.paused(task, soFarBytes, totalBytes);
    final TaskViewHolderImp tag = checkCurrentHolder(task);
    if (tag == null) {
        return;
    }
    AppLogUtils.e("taskDownloadListener----"+"paused--------");
    if(tag instanceof DialogListAdapter.ViewHolder){
        AppLogUtils.e("taskDownloadListener----"+"paused--------DialogListAdapter");
        ((DialogListAdapter.ViewHolder)tag).updateNotDownloaded(FileDownloadStatus.paused, soFarBytes, totalBytes);
    }
    if(tag instanceof CacheDownloadingAdapter.MyViewHolder){
        AppLogUtils.e("taskDownloadListener----"+"paused--------CacheDownloadingAdapter");
        ((CacheDownloadingAdapter.MyViewHolder)tag).updateNotDownloaded(FileDownloadStatus.paused, soFarBytes, totalBytes);

    }
    TasksManager.getImpl().removeTaskForViewHolder(task.getId());
}
 
Example #9
Source File: DownloadStatusCallback.java    From FileDownloader with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleMessage(Message msg) {
    handlingMessage = true;
    final int status = msg.what;

    try {
        switch (status) {
            case FileDownloadStatus.progress:
                handleProgress();
                break;
            case FileDownloadStatus.retry:
                handleRetry((Exception) msg.obj, msg.arg1);
                break;
            default:
                // ignored.
        }
    } finally {
        handlingMessage = false;
        if (parkThread != null) LockSupport.unpark(parkThread);
    }


    return true;
}
 
Example #10
Source File: DownloadStatusCallback.java    From FileDownloader with Apache License 2.0 6 votes vote down vote up
void onProgress(long increaseBytes) {
    callbackIncreaseBuffer.addAndGet(increaseBytes);
    model.increaseSoFar(increaseBytes);

    final long now = SystemClock.elapsedRealtime();

    inspectNeedCallbackToUser(now);

    if (handler == null) {
        // direct
        handleProgress();
    } else if (needCallbackProgressToUser.get()) {
        // flow
        sendMessage(handler.obtainMessage(FileDownloadStatus.progress));
    }
}
 
Example #11
Source File: FileDownloaderExecutor.java    From Mysplash with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 #12
Source File: TasksManagerDemoActivity.java    From FileDownloader with Apache License 2.0 6 votes vote down vote up
public void updateNotDownloaded(final int status, final long sofar, final long total) {
    if (sofar > 0 && total > 0) {
        final float percent = sofar
                / (float) total;
        taskPb.setMax(100);
        taskPb.setProgress((int) (percent * 100));
    } else {
        taskPb.setMax(1);
        taskPb.setProgress(0);
    }

    switch (status) {
        case FileDownloadStatus.error:
            taskStatusTv.setText(R.string.tasks_manager_demo_status_error);
            break;
        case FileDownloadStatus.paused:
            taskStatusTv.setText(R.string.tasks_manager_demo_status_paused);
            break;
        default:
            taskStatusTv.setText(R.string.tasks_manager_demo_status_not_downloaded);
            break;
    }
    taskActionBtn.setText(R.string.start);
}
 
Example #13
Source File: DownloadStatusCallback.java    From FileDownloader with Apache License 2.0 6 votes vote down vote up
private void onStatusChanged(final byte status) {
    // In current situation, it maybe invoke this method simultaneously between #onPause() and
    // others.
    if (status == FileDownloadStatus.paused) {
        if (FileDownloadLog.NEED_LOG) {
            /**
             * Already paused or the current status is paused.
             *
             * We don't need to call-back to Task in here, because the pause status has
             * already handled by {@link BaseDownloadTask#pause()} manually.
             *
             * In some case, it will arrive here by High concurrent cause.  For performance
             * more make sense.
             *
             * High concurrent cause.
             */
            FileDownloadLog.d(this, "High concurrent cause, Already paused and we don't "
                    + "need to call-back to Task in here, %d", model.getId());
        }
        return;
    }

    MessageSnapshotFlow.getImpl().inflow(
            MessageSnapshotTaker.take(status, model, processParams));
}
 
Example #14
Source File: DownloadLaunchRunnableTest.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
@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 #15
Source File: DownloadStatusCallback.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
void onRetry(Exception exception, int remainRetryTimes) {
    this.callbackIncreaseBuffer.set(0);

    if (handler == null) {
        // direct
        handleRetry(exception, remainRetryTimes);
    } else {
        // flow
        sendMessage(handler.obtainMessage(FileDownloadStatus.retry, remainRetryTimes, 0,
                exception));
    }
}
 
Example #16
Source File: TasksManagerDemoActivity.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
@Override
protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
    super.pending(task, soFarBytes, totalBytes);
    final TaskItemViewHolder tag = checkCurrentHolder(task);
    if (tag == null) {
        return;
    }

    tag.updateDownloading(FileDownloadStatus.pending, soFarBytes
            , totalBytes);
    tag.taskStatusTv.setText(R.string.tasks_manager_demo_status_pending);
}
 
Example #17
Source File: SqliteDatabaseImpl.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
@Override
public void updatePause(int id, long sofar) {
    ContentValues cv = new ContentValues();
    cv.put(FileDownloadModel.STATUS, FileDownloadStatus.paused);
    cv.put(FileDownloadModel.SOFAR, sofar);

    update(id, cv);
}
 
Example #18
Source File: TasksManagerDemoActivity.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
@Override
protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
    super.progress(task, soFarBytes, totalBytes);
    final TaskItemViewHolder tag = checkCurrentHolder(task);
    if (tag == null) {
        return;
    }

    tag.updateDownloading(FileDownloadStatus.progress, soFarBytes
            , totalBytes);
}
 
Example #19
Source File: TasksManagerDemoActivity.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
@Override
protected void error(BaseDownloadTask task, Throwable e) {
    super.error(task, e);
    final TaskItemViewHolder tag = checkCurrentHolder(task);
    if (tag == null) {
        return;
    }

    tag.updateNotDownloaded(FileDownloadStatus.error, task.getLargeFileSoFarBytes()
            , task.getLargeFileTotalBytes());
    TasksManager.getImpl().removeTaskForViewHolder(task.getId());
}
 
Example #20
Source File: FileDownloadServiceUIGuard.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
@Override
public byte getStatus(final int id) {
    if (!isConnected()) {
        return DownloadServiceNotConnectedHelper.getStatus(id);
    }

    byte status = FileDownloadStatus.INVALID_STATUS;
    try {
        status = getService().getStatus(id);
    } catch (RemoteException e) {
        e.printStackTrace();
    }

    return status;
}
 
Example #21
Source File: TasksManagerDemoActivity.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
@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 #22
Source File: DownloadManager.java    From v9porn with 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 #23
Source File: DownloadTaskHunter.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
@Override
public boolean updateKeepFlow(MessageSnapshot snapshot) {
    final int currentStatus = getStatus();
    final int nextStatus = snapshot.getStatus();

    if (FileDownloadStatus.paused == currentStatus && FileDownloadStatus.isIng(nextStatus)) {
        if (FileDownloadLog.NEED_LOG) {
            /**
             * Occur such situation, must be the running-mStatus waiting for turning up in flow
             * thread pool(or binder thread) when there is someone invoked the {@link #pause()}.
             *
             * High concurrent cause.
             */
            FileDownloadLog.d(this, "High concurrent cause, callback pending, but has already"
                    + " be paused %d", getId());
        }
        return true;
    }

    if (!FileDownloadStatus.isKeepFlow(currentStatus, nextStatus)) {
        if (FileDownloadLog.NEED_LOG) {
            FileDownloadLog.d(this, "can't update mStatus change by keep flow, %d, but the"
                    + " current mStatus is %d, %d", mStatus, getStatus(), getId());
        }

        return false;
    }

    update(snapshot);
    return true;
}
 
Example #24
Source File: SqliteDatabaseImpl.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
@Override
public void updateError(int id, Throwable throwable, long sofar) {
    ContentValues cv = new ContentValues();
    cv.put(FileDownloadModel.ERR_MSG, throwable.toString());
    cv.put(FileDownloadModel.STATUS, FileDownloadStatus.error);
    cv.put(FileDownloadModel.SOFAR, sofar);

    update(id, cv);
}
 
Example #25
Source File: SqliteDatabaseImpl.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
@Override
public void updateProgress(int id, long sofarBytes) {
    ContentValues cv = new ContentValues();
    cv.put(FileDownloadModel.STATUS, FileDownloadStatus.progress);
    cv.put(FileDownloadModel.SOFAR, sofarBytes);

    update(id, cv);
}
 
Example #26
Source File: SqliteDatabaseImpl.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
@Override
public void updateConnected(int id, long total, String etag, String filename) {
    ContentValues cv = new ContentValues();
    cv.put(FileDownloadModel.STATUS, FileDownloadStatus.connected);
    cv.put(FileDownloadModel.TOTAL, total);
    cv.put(FileDownloadModel.ETAG, etag); // maybe null.
    cv.put(FileDownloadModel.FILENAME, filename); // maybe null.

    update(id, cv);
}
 
Example #27
Source File: DownloadTaskHunter.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
@Override
public void free() {
    if (FileDownloadLog.NEED_LOG) {
        FileDownloadLog.d(this, "free the task %d, when the status is %d", getId(), mStatus);
    }
    mStatus = FileDownloadStatus.INVALID_STATUS;
}
 
Example #28
Source File: BlockCompleteMessage.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
public BlockCompleteMessageImpl(MessageSnapshot snapshot) {
    super(snapshot.getId());
    if (snapshot.getStatus() != FileDownloadStatus.completed) {
        throw new IllegalArgumentException(FileDownloadUtils.formatString(
                "can't create the block complete message for id[%d], status[%d]",
                snapshot.getId(), snapshot.getStatus()));
    }
    this.mCompletedSnapshot = snapshot;
}
 
Example #29
Source File: MessageSnapshotTaker.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
public static MessageSnapshot takeBlockCompleted(MessageSnapshot snapshot) {
    if (snapshot.getStatus() != FileDownloadStatus.completed) {
        throw new IllegalStateException(
                FileDownloadUtils.formatString("take block completed snapshot, must has "
                                + "already be completed. %d %d",
                        snapshot.getId(), snapshot.getStatus()));
    }

    return new BlockCompleteMessage.BlockCompleteMessageImpl(snapshot);
}
 
Example #30
Source File: FileDownloadBroadcastHandler.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
public static void sendCompletedBroadcast(FileDownloadModel model) {
    if (model == null) throw new IllegalArgumentException();
    if (model.getStatus() != FileDownloadStatus.completed) throw new IllegalStateException();

    final Intent intent = new Intent(ACTION_COMPLETED);
    intent.putExtra(KEY_MODEL, model);

    FileDownloadHelper.getAppContext().sendBroadcast(intent);
}