com.liulishuo.filedownloader.util.FileDownloadHelper Java Examples

The following examples show how to use com.liulishuo.filedownloader.util.FileDownloadHelper. 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 okdownload with Apache License 2.0 6 votes vote down vote up
@Nullable
public static OkDownload.Builder okDownloadBuilder(
        @NonNull Context context,
        @Nullable final FileDownloadHelper.OkHttpClientCustomMaker okHttpClientCustomMaker) {
    OkDownload.Builder builder = null;
    final OkHttpClient okHttpClient;
    if (okHttpClientCustomMaker == null) {
        okHttpClient = null;
    } else {
        okHttpClient = okHttpClientCustomMaker.customMake();
    }
    if (okHttpClient != null) {
        builder = new OkDownload.Builder(context);
        builder.connectionFactory(url -> new DownloadOkHttp3Connection.Factory()
                .setBuilder(okHttpClient.newBuilder())
                .create(url));
    }
    final DownloadMonitor downloadMonitor = FileDownloadMonitor.getDownloadMonitor();
    if (downloadMonitor != null) {
        if (builder == null) builder = new OkDownload.Builder(context);
        builder.monitor(downloadMonitor);
    }
    return builder;
}
 
Example #2
Source File: LostServiceConnectedHandler.java    From FileDownloader with Apache License 2.0 6 votes vote down vote up
@Override
public boolean dispatchTaskStart(BaseDownloadTask.IRunningTask task) {
    if (!FileDownloader.getImpl().isServiceConnected()) {
        synchronized (mWaitingList) {
            if (!FileDownloader.getImpl().isServiceConnected()) {
                if (FileDownloadLog.NEED_LOG) {
                    FileDownloadLog.d(this, "Waiting for connecting with the downloader "
                            + "service... %d", task.getOrigin().getId());
                }
                FileDownloadServiceProxy.getImpl().
                        bindStartByContext(FileDownloadHelper.getAppContext());
                if (!mWaitingList.contains(task)) {
                    task.free();
                    mWaitingList.add(task);
                }
                return true;
            }
        }
    }

    taskWorkFine(task);

    return false;
}
 
Example #3
Source File: DownloadMgrInitialParams.java    From FileDownloader with Apache License 2.0 6 votes vote down vote up
/**
 * Customize the output stream component.
 * <p>
 * If you don't customize the output stream component, we use the result of
 * {@link #createDefaultOutputStreamCreator()} as the default one.
 *
 * @param creator The output stream creator is used for creating
 *                {@link FileDownloadOutputStream} which is used to write the input stream
 *                to the file for downloading.
 */
public InitCustomMaker outputStreamCreator(FileDownloadHelper.OutputStreamCreator creator) {
    this.mOutputStreamCreator = creator;
    if (mOutputStreamCreator != null && !mOutputStreamCreator.supportSeek()) {
        if (!FileDownloadProperties.getImpl().fileNonPreAllocation) {
            throw new IllegalArgumentException(
                    "Since the provided FileDownloadOutputStream "
                            + "does not support the seek function, if FileDownloader"
                            + " pre-allocates file size at the beginning of the download,"
                            + " it will can not be resumed from the breakpoint. If you need"
                            + " to ensure that the resumption is available, please add and"
                            + " set the value of 'file.non-pre-allocation' field to 'true'"
                            + " in the 'filedownloader.properties' file which is in your"
                            + " application assets folder manually for resolving this "
                            + "problem.");
        }
    }
    return this;
}
 
Example #4
Source File: DownloadMgrInitialParams.java    From FileDownloader with Apache License 2.0 6 votes vote down vote up
public FileDownloadHelper.IdGenerator createIdGenerator() {
    if (mMaker == null) {
        return createDefaultIdGenerator();
    }

    final FileDownloadHelper.IdGenerator idGenerator = mMaker.mIdGenerator;
    if (idGenerator != null) {
        if (FileDownloadLog.NEED_LOG) {
            FileDownloadLog.d(this, "initial FileDownloader manager with the customize "
                    + "id generator: %s", idGenerator);
        }

        return idGenerator;
    } else {
        return createDefaultIdGenerator();
    }
}
 
Example #5
Source File: DownloadMgrInitialParams.java    From FileDownloader with Apache License 2.0 6 votes vote down vote up
public FileDownloadHelper.ConnectionCountAdapter createConnectionCountAdapter() {
    if (mMaker == null) {
        return createDefaultConnectionCountAdapter();
    }

    final FileDownloadHelper.ConnectionCountAdapter adapter = mMaker.mConnectionCountAdapter;
    if (adapter != null) {
        if (FileDownloadLog.NEED_LOG) {
            FileDownloadLog.d(this, "initial FileDownloader manager with the customize "
                    + "connection count adapter: %s", adapter);
        }
        return adapter;
    } else {
        return createDefaultConnectionCountAdapter();
    }
}
 
Example #6
Source File: DownloadMgrInitialParams.java    From FileDownloader with Apache License 2.0 6 votes vote down vote up
public FileDownloadHelper.ConnectionCreator createConnectionCreator() {
    if (mMaker == null) {
        return createDefaultConnectionCreator();
    }

    final FileDownloadHelper.ConnectionCreator connectionCreator = mMaker.mConnectionCreator;

    if (connectionCreator != null) {
        if (FileDownloadLog.NEED_LOG) {
            FileDownloadLog.d(this, "initial FileDownloader manager with the customize "
                    + "connection creator: %s", connectionCreator);
        }
        return connectionCreator;
    } else {
        return createDefaultConnectionCreator();
    }
}
 
Example #7
Source File: NotificationSampleActivity.java    From FileDownloader with Apache License 2.0 6 votes vote down vote up
private NotificationItem(int id, String title, String desc, String channelId) {
    super(id, title, desc);
    final Intent[] intents = new Intent[2];
    intents[0] = Intent.makeMainActivity(
            new ComponentName(DemoApplication.CONTEXT, MainActivity.class));
    intents[1] = new Intent(DemoApplication.CONTEXT, NotificationSampleActivity.class);
    final PendingIntent pendingIntent = PendingIntent.getActivities(
            DemoApplication.CONTEXT, 0, intents,
            PendingIntent.FLAG_UPDATE_CURRENT);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        builder = new NotificationCompat.Builder(
                FileDownloadHelper.getAppContext(),
                channelId);
    } else {
        //noinspection deprecation
        builder = new NotificationCompat.Builder(FileDownloadHelper.getAppContext())
                .setDefaults(Notification.DEFAULT_LIGHTS)
                .setPriority(NotificationCompat.PRIORITY_MIN);
    }

    builder.setContentTitle(getTitle())
            .setContentText(desc)
            .setContentIntent(pendingIntent)
            .setSmallIcon(R.mipmap.ic_launcher);
}
 
Example #8
Source File: DownloadMgrInitialParams.java    From FileDownloader with Apache License 2.0 6 votes vote down vote up
public FileDownloadHelper.OutputStreamCreator createOutputStreamCreator() {
    if (mMaker == null) {
        return createDefaultOutputStreamCreator();
    }

    final FileDownloadHelper.OutputStreamCreator outputStreamCreator =
            mMaker.mOutputStreamCreator;
    if (outputStreamCreator != null) {
        if (FileDownloadLog.NEED_LOG) {
            FileDownloadLog.d(this, "initial FileDownloader manager with the customize "
                    + "output stream: %s", outputStreamCreator);
        }
        return outputStreamCreator;
    } else {
        return createDefaultOutputStreamCreator();
    }
}
 
Example #9
Source File: FileDownloadService.java    From FileDownloader with Apache License 2.0 6 votes vote down vote up
@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 #10
Source File: FileDownloader.java    From FileDownloader with Apache License 2.0 6 votes vote down vote up
/**
 * @deprecated please using {@link #setupOnApplicationOnCreate(Application)} instead.
 */
public static void init(final Context context,
                        final DownloadMgrInitialParams.InitCustomMaker maker) {
    if (FileDownloadLog.NEED_LOG) {
        FileDownloadLog.d(FileDownloader.class, "init Downloader with params: %s %s",
                context, maker);
    }

    if (context == null) {
        throw new IllegalArgumentException("the provided context must not be null!");
    }

    FileDownloadHelper.holdContext(context.getApplicationContext());

    CustomComponentHolder.getImpl().setInitCustomMaker(maker);
}
 
Example #11
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 #12
Source File: CustomComponentHolder.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
public FileDownloadHelper.IdGenerator getIdGeneratorInstance() {
    if (idGenerator != null) return idGenerator;

    synchronized (this) {
        if (idGenerator == null) {
            idGenerator = getDownloadMgrInitialParams().createIdGenerator();
        }
    }

    return idGenerator;
}
 
Example #13
Source File: CustomComponentHolder.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
private FileDownloadHelper.ConnectionCountAdapter getConnectionCountAdapter() {
    if (connectionCountAdapter != null) return connectionCountAdapter;

    synchronized (this) {
        if (connectionCountAdapter == null) {
            connectionCountAdapter = getDownloadMgrInitialParams()
                    .createConnectionCountAdapter();
        }
    }

    return connectionCountAdapter;
}
 
Example #14
Source File: CustomComponentHolder.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
private FileDownloadHelper.ConnectionCreator getConnectionCreator() {
    if (connectionCreator != null) return connectionCreator;

    synchronized (this) {
        if (connectionCreator == null) {
            connectionCreator = getDownloadMgrInitialParams().createConnectionCreator();
        }
    }

    return connectionCreator;
}
 
Example #15
Source File: CustomComponentHolder.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
private FileDownloadHelper.OutputStreamCreator getOutputStreamCreator() {
    if (outputStreamCreator != null) return outputStreamCreator;

    synchronized (this) {
        if (outputStreamCreator == null) {
            outputStreamCreator = getDownloadMgrInitialParams().createOutputStreamCreator();
        }
    }

    return outputStreamCreator;
}
 
Example #16
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);
}
 
Example #17
Source File: FileDownloaderTest.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
@Test
public void setup_withContext_hold() {
    FileDownloader.setup(application);

    Assert.assertEquals(application.getApplicationContext(),
            FileDownloadHelper.getAppContext());
}
 
Example #18
Source File: FileDownloaderTest.java    From FileDownloader with Apache License 2.0 5 votes vote down vote up
@Test
public void setupOnApplicationOnCreate_withContext_hold() {
    FileDownloader.setupOnApplicationOnCreate(application);

    Assert.assertEquals(application.getApplicationContext(),
            FileDownloadHelper.getAppContext());
}
 
Example #19
Source File: MyApplication.java    From TLint with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    initComponent();
    initUser();
    FileDownloader.init(this, new FileDownloadHelper.OkHttpClientCustomMaker() {
        @Override
        public OkHttpClient customMake() {
            return mOkHttpClient;
        }
    });
    initFrescoConfig();
    ToastUtil.register(this);
    LeakCanary.install(this);
}
 
Example #20
Source File: DownloadMgrInitialParams.java    From FileDownloader with Apache License 2.0 4 votes vote down vote up
private FileDownloadHelper.OutputStreamCreator createDefaultOutputStreamCreator() {
    return new FileDownloadRandomAccessFile.Creator();
}
 
Example #21
Source File: FileDownloader.java    From okdownload with Apache License 2.0 4 votes vote down vote up
public static void init(
        @NonNull Context context,
        @Nullable FileDownloadHelper.OkHttpClientCustomMaker okHttpClientCustomMaker) {
    init(context, okHttpClientCustomMaker, 0);
}
 
Example #22
Source File: DownloadTaskHunter.java    From FileDownloader with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("checkstyle:emptyblock")
@Override
public void start() {
    if (mStatus != FileDownloadStatus.toLaunchPool) {
        FileDownloadLog.w(this, "High concurrent cause, this task %d will not start,"
                        + " because the of status isn't toLaunchPool: %d",
                getId(), mStatus);
        return;
    }

    final BaseDownloadTask.IRunningTask runningTask = mTask.getRunningTask();
    final BaseDownloadTask origin = runningTask.getOrigin();

    final ILostServiceConnectedHandler lostConnectedHandler = FileDownloader.getImpl().
            getLostConnectedHandler();
    try {

        if (lostConnectedHandler.dispatchTaskStart(runningTask)) {
            return;
        }

        synchronized (mPauseLock) {
            if (mStatus != FileDownloadStatus.toLaunchPool) {
                FileDownloadLog.w(this, "High concurrent cause, this task %d will not start,"
                                + " the status can't assign to toFileDownloadService, because "
                                + "the status isn't toLaunchPool: %d",
                        getId(), mStatus);
                return;
            }

            mStatus = FileDownloadStatus.toFileDownloadService;
        }

        FileDownloadList.getImpl().add(runningTask);
        if (FileDownloadHelper.inspectAndInflowDownloaded(
                origin.getId(), origin.getTargetFilePath(), origin.isForceReDownload(), true)
                ) {
            // Will be removed when the complete message is received in #update
            return;
        }

        final boolean succeed = FileDownloadServiceProxy.getImpl().
                start(
                        origin.getUrl(),
                        origin.getPath(),
                        origin.isPathAsDirectory(),
                        origin.getCallbackProgressTimes(),
                        origin.getCallbackProgressMinInterval(),
                        origin.getAutoRetryTimes(),
                        origin.isForceReDownload(),
                        mTask.getHeader(),
                        origin.isWifiRequired());

        if (mStatus == FileDownloadStatus.paused) {
            FileDownloadLog.w(this, "High concurrent cause, this task %d will be paused,"
                            + "because of the status is paused, so the pause action must be "
                            + "applied",
                    getId());
            if (succeed) {
                FileDownloadServiceProxy.getImpl().pause(getId());
            }
            return;
        }

        if (!succeed) {
            //noinspection StatementWithEmptyBody
            if (!lostConnectedHandler.dispatchTaskStart(runningTask)) {
                final MessageSnapshot snapshot = prepareErrorMessage(
                        new RuntimeException("Occur Unknown Error, when request to start"
                                + " maybe some problem in binder, maybe the process was killed "
                                + "in unexpected."));

                if (FileDownloadList.getImpl().isNotContains(runningTask)) {
                    lostConnectedHandler.taskWorkFine(runningTask);
                    FileDownloadList.getImpl().add(runningTask);
                }

                FileDownloadList.getImpl().remove(runningTask, snapshot);

            } else {
                // the FileDownload Service host process was killed when request stating and it
                // will be restarted by LostServiceConnectedHandler.
            }
        } else {
            lostConnectedHandler.taskWorkFine(runningTask);
        }

    } catch (Throwable e) {
        e.printStackTrace();

        FileDownloadList.getImpl().remove(runningTask, prepareErrorMessage(e));
    }
}
 
Example #23
Source File: DownloadMgrInitialParams.java    From okdownload with Apache License 2.0 4 votes vote down vote up
public InitCustomMaker connectionCountAdapter(
        FileDownloadHelper.ConnectionCountAdapter adapter) {
    return this;
}
 
Example #24
Source File: DownloadMgrInitialParams.java    From okdownload with Apache License 2.0 4 votes vote down vote up
public InitCustomMaker database(FileDownloadHelper.DatabaseCustomMaker maker) {
    return this;
}
 
Example #25
Source File: DownloadMgrInitialParams.java    From FileDownloader with Apache License 2.0 4 votes vote down vote up
private FileDownloadHelper.ConnectionCountAdapter createDefaultConnectionCountAdapter() {
    return new DefaultConnectionCountAdapter();
}
 
Example #26
Source File: DownloadMgrInitialParams.java    From FileDownloader with Apache License 2.0 4 votes vote down vote up
private FileDownloadHelper.ConnectionCreator createDefaultConnectionCreator() {
    return new FileDownloadUrlConnection.Creator();
}
 
Example #27
Source File: DownloadLaunchRunnable.java    From FileDownloader with Apache License 2.0 4 votes vote down vote up
private void checkupAfterGetFilename() throws RetryDirectly, DiscardSafely {
    final int id = model.getId();

    if (model.isPathAsDirectory()) {
        // this scope for caring about the case of there is another task is provided
        // the same path to store file and the same url.

        final String targetFilePath = model.getTargetFilePath();

        // get the ID after got the filename.
        final int fileCaseId = FileDownloadUtils.generateId(model.getUrl(),
                targetFilePath);

        // whether the file with the filename has been existed.
        if (FileDownloadHelper.inspectAndInflowDownloaded(id,
                targetFilePath, isForceReDownload, false)) {
            database.remove(id);
            database.removeConnections(id);
            throw new DiscardSafely();
        }

        final FileDownloadModel fileCaseModel = database.find(fileCaseId);

        if (fileCaseModel != null) {
            // the task with the same file name and url has been exist.

            // whether the another task with the same file and url is downloading.
            if (FileDownloadHelper.inspectAndInflowDownloading(id, fileCaseModel,
                    threadPoolMonitor, false)) {
                //it has been post to upper layer the 'warn' message, so the current
                // task no need to continue download.
                database.remove(id);
                database.removeConnections(id);
                throw new DiscardSafely();
            }

            final List<ConnectionModel> connectionModelList = database
                    .findConnectionModel(fileCaseId);

            // the another task with the same file name and url is paused
            database.remove(fileCaseId);
            database.removeConnections(fileCaseId);
            FileDownloadUtils.deleteTargetFile(model.getTargetFilePath());

            if (FileDownloadUtils.isBreakpointAvailable(fileCaseId, fileCaseModel)) {
                model.setSoFar(fileCaseModel.getSoFar());
                model.setTotal(fileCaseModel.getTotal());
                model.setETag(fileCaseModel.getETag());
                model.setConnectionCount(fileCaseModel.getConnectionCount());
                database.update(model);

                // re connect to resume from breakpoint.
                if (connectionModelList != null) {
                    for (ConnectionModel connectionModel : connectionModelList) {
                        connectionModel.setId(id);
                        database.insertConnectionModel(connectionModel);
                    }
                }

                // retry
                throw new RetryDirectly();
            }
        }

        // whether there is an another running task with the same target-file-path.
        if (FileDownloadHelper.inspectAndInflowConflictPath(id, model.getSoFar(),
                model.getTempFilePath(),
                targetFilePath,
                threadPoolMonitor)) {
            database.remove(id);
            database.removeConnections(id);

            throw new DiscardSafely();
        }
    }
}
 
Example #28
Source File: DownloadMgrInitialParams.java    From FileDownloader with Apache License 2.0 4 votes vote down vote up
private FileDownloadHelper.IdGenerator createDefaultIdGenerator() {
    return new DefaultIdGenerator();
}
 
Example #29
Source File: DownloadConnectionAdapter.java    From okdownload with Apache License 2.0 4 votes vote down vote up
public Factory(@NonNull FileDownloadHelper.ConnectionCreator creator) {
    this.creator = creator;
}
 
Example #30
Source File: FileDownloader.java    From FileDownloader with Apache License 2.0 4 votes vote down vote up
/**
 * Unbind and stop the downloader service.
 */
public void unBindService() {
    if (isServiceConnected()) {
        FileDownloadServiceProxy.getImpl().unbindByContext(FileDownloadHelper.getAppContext());
    }
}