- Находки программиста
- четверг, 19 января 2012 г.
- Android: загрузка файла из сети с отображением прогресса
- Android — How to download a file from a webserver
- Download a file with Android, and showing the progress in a ProgressDialog
- 16 Answers 16
- 1. Use AsyncTask and show the download progress in a dialog
- 2. Download from Service
- 2.1 Use Groundy library
- 2.2 Use https://github.com/koush/ion
- 3. Use DownloadManager class ( GingerBread and newer only)
- Final thoughts
- Android Download a File from Internet URL in Java
- How to Download a File from URL Link in Android Java Tutorial
- Conclusion
- Contact Now
- Meet Advanced Plus
- Лучший способ загрузки изображения с url в Android
- ОТВЕТЫ
- Ответ 1
- Ответ 2
- Ответ 3
- Ответ 4
- Ответ 5
- Ответ 6
- Ответ 7
- Ответ 8
- Ответ 9
- Ответ 10
- Ответ 11
Находки программиста
Решения конкретных задач программирования. Java, Android, JavaScript, Flex и прочее. Настройка софта под Linux, методики разработки и просто размышления.
четверг, 19 января 2012 г.
Android: загрузка файла из сети с отображением прогресса
Хорошо сделанное Android-приложение (кроме всего прочего) не заставляет клиента угадывать что в данный момент происходит «по ту сторону экрана». Приятное и аккуратное приложение показывает при всех продолжительных операциях прогресс-бар, который реализует, как правило, с помощью класса AsyncTask. Давайте посмотрим как правильно использовать этот замечательный инструмент на примере загрузки файла из сети:
В этом маленьком приложении при нажатии на кнопку запускается загрузка файла, при этом пользователь наблюдает прогресс-бар. Не забудьте добавить в манифест запрос разрешений на доступ к интернет и файловой системе.
Основой примера является метод, который я взял отсюда (и поправил пару ошибок).
Этот метод принимает url файла, который нужно загрузить, загружает файл, отображая при этом горизонатальный прогресс-бар. При этом прогресс-бар реально показывает какая часть файла в данный момент загружена. По окончании загрузки файл удаляется.
Разберём работу метода подробнее:
Главная часть метода — создание AcyncTask-а и переопределение его методов.
В методе onPreExecute мы запускаем progressDialog, установив предварительно текст сообщения и максимальное значение прогресса: 100%.
В методе doInBackground — выполняем собственно загрузку файла. Файл читаем из urlConnection порциями по 1024 байт, каждый раз прибавляя размер полученной порции к общему счётчику. Счётчик и общий размер файла передаём при каждой итерации в метод publishProgress, благодаря чему в методе onProgressUpdate мы получаем эти данные и обновляем текущий статус progressDialog-а.
И, наконец, в методе onPostExecute мы прячем диалог и удаляем временный файл.
Особенностью использования AsyncTask-a является способ, как он объявляется и как в него передаются параметры. Типы, которыми параметризуется экземпляр AsyncTask-a определяю по порядку: тип входящего значения, тип параметра, опреляющего прогресс опреации и тип результата фоновой операции (то что возвращает doInBackground и принимает onPostExecute). Кроме того конструктор и чаcть методов AsyncTask-а принимает varargs, т.е. произвольное число параметров, что весьма удобно в некоторых случаях.
Источник
Android — How to download a file from a webserver
In my app I am downloading a kml file from a webserver. I have set the permission for external storage and internet in my android manifest file. I am new to Android, your help is greatly appreciated.
MainActivity.java
Android Manifest File
Logcat error:
FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo
: android.os.NetworkOnMainThreadException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) at android.app.ActivityThread.access$600(ActivityThread.java:123) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4424) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) at dalvik.system.NativeStart.main(Native Method) Caused by: android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099) at java.net.InetAddress.lookupHostByName(InetAddress.java:391) at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242) at java.net.InetAddress.getAllByName(InetAddress.java:220) at libcore.net.http.HttpConnection.(HttpConnection.java:71) at libcore.net.http.HttpConnection.(HttpConnection.java:50) at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351) at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86) at libcore.net.http.HttpConnection.connect(HttpConnection.java:128) at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308) at libcore.net.http.HttpEngine.connect(HttpEngine.java:303) at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282) at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232) at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273) at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168) at java.net.URL.openStream(URL.java:462) at com.example.demo.MainActivity.DownloadFiles(MainActivity.java:30) at com.example.demo.MainActivity.onCreate(MainActivity.java:24) at android.app.Activity.performCreate(Activity.java:4465) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
EDIT
When I run this code in the emulator the code still does not work — the file is not getting downloaded.
Источник
Download a file with Android, and showing the progress in a ProgressDialog
I am trying to write a simple application that gets updated. For this I need a simple function that can download a file and show the current progress in a ProgressDialog . I know how to do the ProgressDialog , but I’m not sure how to display the current progress and how to download the file in the first place.
16 Answers 16
There are many ways to download files. Following I will post most common ways; it is up to you to decide which method is better for your app.
1. Use AsyncTask and show the download progress in a dialog
This method will allow you to execute some background processes and update the UI at the same time (in this case, we’ll update a progress bar).
This is an example code:
The AsyncTask will look like this:
The method above ( doInBackground ) runs always on a background thread. You shouldn’t do any UI tasks there. On the other hand, the onProgressUpdate and onPreExecute run on the UI thread, so there you can change the progress bar:
For this to run, you need the WAKE_LOCK permission.
2. Download from Service
The big question here is: how do I update my activity from a service?. In the next example we are going to use two classes you may not be aware of: ResultReceiver and IntentService . ResultReceiver is the one that will allow us to update our thread from a service; IntentService is a subclass of Service which spawns a thread to do background work from there (you should know that a Service runs actually in the same thread of your app; when you extends Service , you must manually spawn new threads to run CPU blocking operations).
Download service can look like this:
Add the service to your manifest:
And the activity will look like this:
Here is were ResultReceiver comes to play:
2.1 Use Groundy library
Groundy is a library that basically helps you run pieces of code in a background service, and it is based on the ResultReceiver concept shown above. This library is deprecated at the moment. This is how the whole code would look like:
The activity where you are showing the dialog.
A GroundyTask implementation used by Groundy to download the file and show the progress:
And just add this to the manifest:
It couldn’t be easier I think. Just grab the latest jar from Github and you are ready to go. Keep in mind that Groundy‘s main purpose is to make calls to external REST apis in a background service and post results to the UI with easily. If you are doing something like that in your app, it could be really useful.
2.2 Use https://github.com/koush/ion
3. Use DownloadManager class ( GingerBread and newer only)
GingerBread brought a new feature, DownloadManager , which allows you to download files easily and delegate the hard work of handling threads, streams, etc. to the system.
First, let’s see a utility method:
Method’s name explains it all. Once you are sure DownloadManager is available, you can do something like this:
Download progress will be showing in the notification bar.
Final thoughts
First and second methods are just the tip of the iceberg. There are lots of things you have to keep in mind if you want your app to be robust. Here is a brief list:
- You must check whether user has an internet connection available
- Make sure you have the right permissions ( INTERNET and WRITE_EXTERNAL_STORAGE ); also ACCESS_NETWORK_STATE if you want to check internet availability.
- Make sure the directory were you are going to download files exist and has write permissions.
- If download is too big you may want to implement a way to resume the download if previous attempts failed.
- Users will be grateful if you allow them to interrupt the download.
Unless you need detailed control of the download process, then consider using DownloadManager (3) because it already handles most of the items listed above.
But also consider that your needs may change. For example, DownloadManager does no response caching. It will blindly download the same big file multiple times. There’s no easy way to fix it after the fact. Where if you start with a basic HttpURLConnection (1, 2), then all you need is to add an HttpResponseCache . So the initial effort of learning the basic, standard tools can be a good investment.
This class was deprecated in API level 26. ProgressDialog is a modal dialog, which prevents the user from interacting with the app. Instead of using this class, you should use a progress indicator like ProgressBar, which can be embedded in your app’s UI. Alternatively, you can use a notification to inform the user of the task’s progress. For more details Link
Источник
Android Download a File from Internet URL in Java
How to Download a File from URL Link in Android Java Tutorial
This tutorial will guide you to learn how to download a file from web in android java, we will first get a link to an image for downloading it, add required permissions and then pass the download link to the download manager for downloading, we will also set a path for saving the file to a location in the android device. If you can’t do it, you can contact me, i will fix or add it for you (see below for contact details)
First, Create a new android project in Android Studio or use an existing project.
Add these permissions in AndroidManifest.xml
Next, we need an image to test our download code, let’s try this cat’s image that is hosted in this website.
This is the direct link of the cat’s image
http://www.zidsworld.com/wp-content/uploads/2018/06/cat_1530281469.jpg
Open the MainActivity.java, Then add this code, this code should be placed below OnCreate method.
So this is the code for downloading image from a Web link URL to your android device’s pictures directory, the code will be executed as soon as you start the app or the MainActivity.
Conclusion
- This code will not cause exceptions because exceptions are caught, so your app will not crash when executing this code
- If your android device runs on marshmallow, you will need request permission before executing this code.
- This code is just for test, you can assign this code to a button or to your desired activity.
- You can try other direct download links to test this code
Update: If you are new to android development, or just want fix this error, i can fix it for you for a small fee of US $5. Just send me your project or that java/kotlin file (The Activity where you wish to add this code) through email or google drive, i can also do it online through TeamViewer, AnyDesk etc. I will fix your project or file and send it back to you. You can pay me through Paypal, PayTM, GooglePay, PhonePe, UPI etc. For more details, contact me below
Contact Now
- WhatsApp: SendWhatsAppMessage (+91 963303 9471)
- Call: Clicktocall
- Telegram: TelegramMessage
- Email: [email protected]
Meet Advanced Plus
I highly recommend you use the new and advanced Android Webview Advanced Plus Source Code we developed to easily convert any website to android app. No coding required, just set your website link, app color, icon etc and the app will be ready!, and it supports upload, download (blob pdf download also supported), loading progress bars, notification, night mode etc. To learn more about the Android Advanced Webview Source Code and to download it, head over to this page Download Android Webview Source Code
Источник
Лучший способ загрузки изображения с url в Android
Я использую ниже метод для загрузки одного изображения из URL
Иногда я получаю исключение outofmemory.
Я не могу исключить исключение из памяти. Приложение закроется. Как предотвратить это?
Есть ли лучший способ загрузки изображений, который также быстрее?
ОТВЕТЫ
Ответ 1
Попробуйте использовать это:
И для проблемы OutOfMemory:
Ответ 2
Я использую эту библиотеку, это действительно здорово, когда вам приходится иметь дело с большим количеством изображений. Он загружает их асинхронно, кэширует их и т.д.
Что касается исключений OOM, использование этого и этого класса резко сократило их для меня.
Ответ 3
Ответ 4
вы можете скачать изображение Asyn task используйте этот класс:
и назовите это так:
Ответ 5
Вы можете использовать функцию ниже, чтобы загрузить изображение с URL.
Смотрите полное объяснение здесь
Ответ 6
Добавьте эту зависимость для сети Android в свой проект
После запуска этого кода Проверка памяти телефона Вы можете увидеть там папку — ИзображениеПроверьте внутри этой папки, вы видите там файл изображения с именем «image.jpeg»
Ответ 7
Исключение OOM можно было бы избежать, следуя официальному руководству загрузить большое растровое изображение.
Не запускайте свой код в потоке пользовательского интерфейса. Используйте AsyncTask, и все будет в порядке.
Ответ 8
OUTPUT
Ответ 9
Шаг 1. Объявление разрешения в манифесте Android
Первое, что нужно сделать в своем первом Android-проекте, — это указать необходимые разрешения в файле ‘AndroidManifest.xml.
Для загрузки изображения Android с URL-адреса нам необходимо разрешение на доступ к Интернету для загрузки файла, чтения и записи во внутреннее хранилище для сохранения изображения во внутреннем хранилище.
Добавьте следующие строки кода в верхней части тега файла AndroidManifest.xml:
Шаг 2. Запросите требуемое разрешение у пользователя
Android позволяет запускать каждое приложение в песочнице. Если приложению требуется доступ к определенным ресурсам или информации за пределами этой изолированной программной среды, оно должно запросить разрешение у пользователя.
Начиная с Android 6.0, Google хочет, чтобы разработчики запрашивали разрешение у пользователя из приложения, чтобы узнать больше о разрешениях, прочитайте это.
Поэтому для загрузки изображения Android с URL-адреса вам потребуется запросить чтение хранилища и запись
Для этого мы будем использовать следующие строки кода, чтобы сначала проверить, предоставлено ли пользователю необходимое разрешение, а если нет, то мы запросим разрешение на чтение и запись в хранилище.
Мы создавали метод la Downlaod Image, вы можете просто вызывать его везде, где вам нужно загрузить изображение.
Теперь, когда мы запросили и получили разрешение пользователя, чтобы начать загрузку образа Android с URL-адреса, мы создадим AsyncTask, поскольку вам не разрешено запускать фоновый процесс в главном потоке.
В приведенных выше строках кода создается URL-адрес и растровое изображение, с использованием BitmapFactory.decodeStream файл загружается.
Путь к файлу создается для сохранения изображения (мы создали папку с именем AndroidDvlpr в DIRECTORY_PICTURES), и загрузка инициализируется.
После загрузки файла MediaScannerConnection вызывается для чтения метаданных из файла и добавления файла к поставщику медиа-контента, чтобы изображение было доступно для пользователя.
В приведенных выше строках кода мы также создали метод showToast() для отображения Toast. полный код здесь:
Ответ 10
Сначала объявите разрешение в манифесте Android: —
MainActivityForDownloadImages.java
DownloadService.java
Ответ 11
Я все еще изучаю Android, поэтому я не могу предоставить богатый контекст или причину моего предложения, но это то, что я использую для извлечения файлов из https и локальных URL-адресов. Я использую это в своем отчете onActivity (как для съемки, так и для выбора из галереи), а также в AsyncTask для извлечения https-адресов.
Источник