Как включить Android Download Manager

Я использую Android Download Manager для загрузки списка файлов. В последнее время я столкнулся с сообщением о сбоях, говоря

Unknown java.lang.IllegalArgumentException: Unknown URL content://downloads/my_downloads

Затем я понял, что причина в том, что пользователь отключил Android Download Manager. Я проверяю, отключен ли диспетчер загрузки, проверяя его имя пакета с помощью кода ниже.

int state = this.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");

И теперь мне нужно найти способ включить Менеджер загрузки, если он отключен. Я попытался настроить его включение состояния с разрешением в манифесте, но я продолжаю получать исключение безопасности.

this.getPackageManager().setApplicationEnabledSetting("com.android.providers.downloads", PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0);

<uses-permission android:name="android.permission.CHANGE_COMPONENT_ENABLED_STATE"/>

Итак, я думал, что это может быть невозможно, потому что это системное приложение. (Приложение Google Play делает это).

Есть ли способ перенаправить пользователя в представление сведений о приложении Download Manager? позволить пользователю включить его? Если нет возможности включить его во время выполнения программно.

Ответ 1

Некоторые люди искали ответ на этот вопрос, и я понял, что ответ на этот вопрос каким-то образом удален. Поэтому я хочу ответить на собственный вопрос.

Невозможно активировать/дезактивировать Менеджер загрузки напрямую, так как это системное приложение, и у нас нет доступа к нему.

Только альтернативный вариант - перенаправить пользователя на страницу Info приложения Download Manager.

try {
     //Open the specific App Info page:
     Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
     intent.setData(Uri.parse("package:" + "com.android.providers.downloads"));
     startActivity(intent);

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

     //Open the generic Apps page:
     Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
     startActivity(intent);
}

Ответ 2

Пожалуйста, отредактируйте мой ответ, если он недействителен

Проверьте, доступен ли диспетчер загрузки:

   int state = this.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");

if(state==PackageManager.COMPONENT_ENABLED_STATE_DISABLED||
state==PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
||state==PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED){

// Cannot download using download manager
}

            else {
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
                request.setDescription(fileName);   
                manager.enqueue(request); 
            }

И решение для загрузки менеджера загрузки:

packageName = "com.android.providers.downloads"

try {
    //Open the specific App Info page:
    Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    intent.setData(Uri.parse("package:" + packageName));
    startActivity(intent);

} catch ( ActivityNotFoundException e ) {
    //e.printStackTrace();

    //Open the generic Apps page:
    Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
    startActivity(intent);

}

Ответ 3

Входящие в Google Gmail Входящие проверяют, отключен ли диспетчер загрузки, если true, а затем показать AlertDialog, чтобы указать пользователю включить DownloadManager в настройках. Снимок экрана ниже:

введите описание изображения здесь

Я написал класс под названием DownloadManagerResolver, чтобы исправить это, надеюсь, что это может помочь вашему.:)

public final class DownloadManagerResolver {

private static final String DOWNLOAD_MANAGER_PACKAGE_NAME = "com.android.providers.downloads";

/**
 * Resolve whether the DownloadManager is enable in current devices.
 *
 * @return true if DownloadManager is enable,false otherwise.
 */
public static boolean resolve(Context context) {
    boolean enable = resolveEnable(context);
    if (!enable) {
        AlertDialog alertDialog = createDialog(context);
        alertDialog.show();
    }
    return enable;
}

/**
 * Resolve whether the DownloadManager is enable in current devices.
 *
 * @param context
 * @return true if DownloadManager is enable,false otherwise.
 */
private static boolean resolveEnable(Context context) {
    int state = context.getPackageManager()
            .getApplicationEnabledSetting(DOWNLOAD_MANAGER_PACKAGE_NAME);

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
        return !(state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED ||
                state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED);
    } else {
        return !(state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED ||
                state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER);
    }
}

private static AlertDialog createDialog(final Context context) {
    AppCompatTextView messageTextView = new AppCompatTextView(context);
    messageTextView.setTextSize(16f);
    messageTextView.setText("DownloadManager is disabled. Please enable it.");
    return new AlertDialog.Builder(context)
            .setView(messageTextView, 50, 30, 50, 30)
            .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    enableDownloadManager(context);
                }
            })
            .setCancelable(false)
            .create();
}

/**
 * Start activity to Settings to enable DownloadManager.
 */
private static void enableDownloadManager(Context context) {
    try {
        //Open the specific App Info page:
        Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + DOWNLOAD_MANAGER_PACKAGE_NAME));
        context.startActivity(intent);
    } catch (ActivityNotFoundException e) {
        e.printStackTrace();

        //Open the generic Apps page:
        Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
        context.startActivity(intent);
    }
}
}

Ответ 4

Может быть, это поможет вам.

downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
   DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
   //Restrict the types of networks over which this download may proceed.
   request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
   //Set whether this download may proceed over a roaming connection.
   request.setAllowedOverRoaming(false);
   //Set the title of this download, to be displayed in notifications (if enabled).
   request.setTitle("My Data Download");
   //Set a description of this download, to be displayed in notifications (if enabled)
   request.setDescription("Android Data download using DownloadManager.");
   //Set the local destination for the downloaded file to a path within the application external files directory
   request.setDestinationInExternalFilesDir(this,Environment.DIRECTORY_DOWNLOADS,"CountryList.json");

   //Enqueue a new download and same the referenceId
   downloadReference = downloadManager.enqueue(request);

http://www.mysamplecode.com/2012/09/android-downloadmanager-example.html