Загрузка файлов PDF во внутреннее хранилище - PullRequest
0 голосов
/ 01 июля 2019

Я делаю задачу Android.

Я загружаю файл с URL и сохраняю во внутреннем хранилище / каталоге телефона Android? мой код написан ниже, но это код внешнего хранилища. Мне нужен код внутреннего хранилища.

 public void onClick(View v) {
                    Toast.makeText(Computer.this,"Please Wait until the file is download",Toast.LENGTH_LONG).show();
                    downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                    Uri uri = Uri.parse("url");
                    DownloadManager.Request request = new DownloadManager.Request(uri);
                    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
                    request.setAllowedOverRoaming(false);
                    request.setTitle("" + "filename" + ".pdf");
                    request.setVisibleInDownloadsUi(true);
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    Long reference = downloadManager.enqueue(request);
                    request.setDestinationInExternalFilesDir(Environment.DIRECTORY_DOWNLOADS, "/"+ "filename");
                    refid = downloadManager.enqueue(request);
                    Log.e("OUT", "" + refid);

Это код внешнего хранилища, но я хочу сохранить его во внутреннем хранилище телефона Android.

Ответы [ 4 ]

1 голос
/ 01 июля 2019

Вы не можете использовать DownloadManager для прямой загрузки в часть внутреннего хранилища вашего приложения . Вам нужно будет использовать OkHttp или какой-либо другой внутрипроцессный API-интерфейс HTTP-клиента.

0 голосов
/ 01 июля 2019

Вы можете просто удалить эту строку, request.setDestinationInExternalFilesDir()

По умолчанию загрузки сохраняются в сгенерированное имя файла в общем кэше загрузок

Из документов

0 голосов
/ 01 июля 2019

Только ваше собственное приложение может Access в приложение internal storage Встроенный менеджер загрузки Android по умолчанию не может получить доступ к внутренней памяти вашего приложения, поэтому вы не можете загрузить его во внутреннюю память.

Решение:

Загрузка файла на SD-карте в качестве временного файла, и после завершения загрузки зарегистрируйте получателя, а затем скопируйте файл с внешнего на внутреннее хранилище, после копирования удалите файл с внешнего хранилища.

Полный код:

public class MainActivity extends Activity {
    private long enqueue;
    private DownloadManager dm;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                    long downloadId = intent.getLongExtra(
                            DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                    DownloadManager.Query query = new DownloadManager.Query();
                    query.setFilterById(enqueue);
                    Cursor c = dm.query(query);
                    if (c.moveToFirst()) {
                        int columnIndex = c
                                .getColumnIndex(DownloadManager.COLUMN_STATUS);
                        if (DownloadManager.STATUS_SUCCESSFUL == c
                                .getInt(columnIndex)) {

                            ImageView view = (ImageView) findViewById(R.id.imageView1);
                            String uriString = c
                                    .getString(c
                                            .getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

                            Uri a = Uri.parse(uriString);
                            File d = new File(a.getPath());
                           // copy file from external to internal storage..After that delete file from external storage..Code will easily avalible on google.
                            view.setImageURI(a);
                        }
                    }
                }
            }
        };

        registerReceiver(receiver, new IntentFilter(
                DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    public void onClick(View view) {
        dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(
                Uri.parse("http://www.vogella.de/img/lars/LarsVogelArticle7.png")).setDestinationInExternalPublicDir("/Sohail_Temp", "test.jpg");
        enqueue = dm.enqueue(request);
    }

    public void showDownload(View view) {
        Intent i = new Intent();
        i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
        startActivity(i);
    }
}

Макет:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="Start Download"></Button>

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="showDownload"
        android:text="View Downloads"></Button>

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/image_1"></ImageView>
</LinearLayout>

Разрешения:

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
0 голосов
/ 01 июля 2019

Вы можете использовать это:

request.setDestinationUri(Uri.fromFile(new File(context.getCacheDir(),"filename.txt")));
...