- Android ListFragment with Images and Text using Android Support Library
- Обновляемся на новую версию API Android по наставлению Google
- Что происходит
- Переход на новую версию
- Fotophire Editing Toolkit
- Photo Editor on Different System and Device
- 1. Mac Photo Editor
- 2.Mobile Photo Editor
- 3. Windows Photo Editor
- 4. Camera or Dslr Photo Editor
- 5. Photo Editor on PC
- 6. Alternatives
- 8 Helpful Android Photo Editors with Layer Support
- Part 1. Helpful Android Photo Editor with Layer Supports
- 1. Adobe Photoshop Mix
- 2. Pixlr
- 3. Multi-Layer Photo Editor
- 4. PicsArt Photo Studio
- 5. Canva
- 6. Photo Layers
- 7. Byte Mobile- Image Editor
- 8. Photo Editor by Aviary
- Part 2. A Recommended Efficient Desktop Photo Editor with Layer Support
- How to Use Fotophire Editing Toolkit
- Conclusion
Android ListFragment with Images and Text using Android Support Library
In this article, we will develop an Android application which lists a set of countries with their names, currencies and flags. For listing the countries, we are using the ListFragment class.
The screenshot of this application is shown in Figure 6.
This application is developed in Eclipse (4.2.1) with ADT plugin (21.1.0) and Android SDK (21.1.0) .
1. Create new Android application project namely “ListFragmentImagesText”
Figure 1 : Create new Android application project
2. Configure the application project
Figure 2 : Configure the application project
3. Design application launcher icon
Figure 3 : Design application launcher icon
4. Create a blank activity
Figure 4 : Create a blank activity
5. Enter MainActivity Details
Figure 5 : Enter MainActivity Details
6. Add Android Support library to this project
By default, Android support library (android-support-v4.jar ) is added to this project by Eclipse IDE to the directory libs. If it is not added, we can do it manually by doing the following steps :
- Open Project Explorer by Clicking “Window -> Show View -> Project Explorer”
- Right click this project
- Then from popup menu, Click “Android Tools -> Add Support Library “
7. Download and extract the zip file containing flag’s images to the directory /res/drawable
8. Update the layout file res/layout/activity_main.xml
9. Create a layout file listview_layout.xml in the folder res/layout
10. Create a ListFragment class in the file src/in/wptrafficanalyzer/listfragmentimagestext/CountryList.java
11. Update the file src/in/wptrafficanalyzer/listfragmentimagestext/MainActivity.java
12. Screenshot of the application
Figure 6 : Screenshot of the application in execution
13. Download source code
I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in
You can hire me on hourly basis or on project basis for Android applications development.
For hiring me, please mail your requirements to info@wptrafficanalyzer.in.
Ready to test your knowledge in Android? Take this quiz :
Источник
Обновляемся на новую версию API Android по наставлению Google
Скоро выходит Android 12, но в этом августе уже с 11-й версии разработчикам придётся использовать новые стандарты доступа приложений к внешним файлам. Если раньше можно было просто поставить флаг, что ваше приложение не поддерживает нововведения, то скоро они станут обязательными для всех. Главный фокус — повышение безопасности.
Переход на новую версию API — довольно трудоёмкая операция, требующая больших затрат на её поддержку при введении крупных апдейтов. Далее расскажу немного про наш переход и возникшие при этом трудности.
Что происходит
Если вы уже знакомы с теорией, то этот раздел можно пропустить — тут я хочу поверхностно сравнить подходы к предмету в разных версиях операционной системы.
В Android есть внутреннее Internal Storage (IS) и внешнее хранилище External Storage (ES). Исторически это были встроенная память в телефоне и внешняя SD-карта, поэтому ES был больше, но медленнее и дешевле. Отсюда и разделение — настройки и критически важное записывали в IS, а в ES хранили данные и большие файлы, например, медиа. Потом ES тоже стал встраиваться в телефон, но разделение, по крайней мере логическое, осталось.
У приложения всегда есть доступ к IS, и там оно может делать что угодно. Но эта папка только для конкретного приложения и она ограничена в памяти. К ES нужно было получать доступ и, кроме манипуляции со своими данными, можно было получить доступ к данным других приложений и производить с ними любые действия (редактировать, удалять или украсть).
Но после разделения на внутреннее и внешнее хранилища все равно оставались проблемы. Многие приложения могли хранить чувствительную информацию не только в IS, но и в ES — то есть ответственность лежала целиком на разработчиках и на том, кто хочет завладеть файлами.
В Android решили всё это переделать ещё в 10-й версии, а в 11-й это стало обязательным.
Чтобы минимизировать риски для пользователя в Google решили внедрить Scoped Storage (SS) в ES. Возможность проникнуть в папки других приложений убрали, а доступ есть только к своим данным — теперь это сугубо личная папка. А IS с 10-й версии ещё и зашифрована по умолчанию.
В Android 11 Google зафорсировала использование SS — когда таргет-версия SDK повышается до 30-й версии API, то нужно использовать SS, иначе будут ошибки, связанные с доступом к файлам. Фишка Android в том, что можно заявить совместимость с определённой версией ОС. Те, кто не переходили на 11, просто говорили, что пока не совместимы с этой версий, но теперь нужно начать поддерживать нововведения всем. С осени не получится заливать апдейты, если не поддерживаешь Android 11, а с августа нельзя будет заливать новые приложения.
Если SS не поддерживается (для девайсов ниже 10-й версии), то для доступа к данным других приложений требуется получить доступ к чтению и записи в память. Иначе придётся получать доступ к файлам через Media Content, Storage Access Framework или новый, появившийся в 11-м Android, фреймворк Datasets в зависимости от типа данных. Здесь тоже придётся получать разрешение доступа к файлу, но по более интересной схеме. Когда расшариваемый файл создаёшь сам, то доступ к нему не нужен. Но если переустановить приложение — доступ к нему опять потребуется. К каждому файлу система привязывает приложение, поэтому когда запрашиваешь доступ, его может не оказаться. Особо беспокоиться не нужно, это сложно отследить, поэтому лучше просто сразу запрашивать пермишен.
Media Content, SAF и Datasets относятся к Shared Storage (ShS). При удалении приложения расшаренные данные не удаляются. Это полезно, если не хочется потерять нужный контент.
Хотя даже при наличии SS можно дать доступ к своим файлам по определённой технологии — через FileProvider можно указать возможность получения доступа к своим файлам из другого приложения. Это нормально, потому что файлы расшаривает сам разработчик.
Также добавилась фича — если приложение не использовалось несколько месяцев, то снимаются все пермишены и доступы к системным элементам. По best practice разрешение запрашивается по необходимости (то есть непосредственно перед использованием того, на что спрашиваем разрешение), поэтому мы просто перед выполнением какого-либо действия проверяем, есть ли у нас пермишены. Если нет, то запрашиваем.
В то же время перекрыли доступы к приложениям внутри девайса. Если раньше можно было отследить, что установлены определённые приложения и отправлять к ним соответствующие интенты, то сейчас мы должны прямо в манифесте прописать, что работаем именно с этими приложениями, и только после этого получить доступ.
В качестве примера можем взять шаринг — мы шарим множество приложений, и их всех нужно указывать в манифесте, иначе они не обнаружатся. Начнём перебирать пакет установленных приложений — будет информация, что не указанного в манифесте приложения нет и при шаринге всё отвалится.
Перейдём к практике.
Переход на новую версию
Основная функциональность по работе с файлами в приложении iFunny представлена в виде сохранения мемов в память и расшаривания их между приложениями. Это было первое, что требовалось починить.
Для этого выделили в общий интерфейс работу с файлами, реализация которого зависела от версии API.
FilesManipulator представляет собой интерфейс, который знает, как работать с файлами и предоставляет разработчику API для записи информации в файл. Copier — это интерфейс, который разработчик должен реализовать, и в который передаётся поток вывода. Грубо говоря, мы не заботимся о том, как создаются файлы, мы работаем только с потоком вывода. Под капотом до 10-й версии Android в FilesManipulator происходит работа с File API, после 10-й (и включая её) — MediaStore API.
Рассмотрим на примере сохранения картинки.
Так как операция сохранения медиафайлов достаточно длительная, то целесообразно использовать MediaStore.Images.Media.IS_PENDING , которая при установлении значения 0 не дает видеть файл приложениям, отличного от текущего.
По сути, вся работа с файлами реализована через эти классы. Шаринг в другие приложения автоматически сохраняют медиа в память устройства и последующая работа с URI уже происходит по новому пути. Но есть такие SDK, которые ещё не успели перестроиться под новые реалии и до сих пор используют File API для проверки медиа. В этом случае используем кеш из External Storage и при необходимости провайдим доступ к файлу через FileProvider API.
Помимо ограничений с памятью в приложениях, таргетированных на 30-ю версию API, появилось ограничение на видимость приложения. Так как iFunny использует шаринг во множество приложений, то данная функциональность была сломана полностью. К счастью, достаточно добавить в манифест query, открывающую область видимости к приложению, и можно будет также полноценно использовать SDK.
Для неявных интентов тоже приходится добавлять код в манифест, чтобы задекларировать то, с чем будет работать приложение. В качестве примера выложу часть кода, добавленного в манифест.
После проверок запуска UI-тестов на девайсах с версиями API 29-30 было выявлено, что они также перестали корректно отрабатываться.
Первоначально в LogCat обнаружил, что приложение не может приконнектиться к процессу Orchestrator и выдает ошибку java.lang.RuntimeException: Cannot connect to androidx.test.orchestrator.OrchestratorService.
Эта проблема из разряда видимости других приложений, поэтому достаточно было добавить строку
Тест удачно запустился, но возникла другая ошибка — Allure не может сохранить отчёт в память устройства, падает с ошибкой.
Очевидно из-за Scoped Storage стало невозможно сохранять файлы в другие папки, поэтому снова почитав документацию по управлению файлами в памяти на девайсе, обнаружил интересный раздел. Там рассказано, как для нужд тестов открыть доступ к папкам девайса, но с существенными ограничениями, которые можно почитать тут.
Так как нам нужно использовать этот пермишен только для тестов, то нам условия подходят. Поэтому я быстренько написал свой ShellCommandExecutor, который выполняет команду adb shell appops set —uid PACKAGE_NAME MANAGE_EXTERNAL_STORAGE allow на создании раннера тестов.
На Android 11 тесты удачно запустились и стали проходить без ошибок.
После попытки запуска на 10-й версии Android обнаружил, что отчет Allure также перестал сохраняться в память девайса. Посмотрев issue Allure, обнаружил, что проблема известная, как и с 11-й версией. Достаточно выполнить команду adb shell appops set —uid PACKAGE_NAME LEGACY_STORAGE allow . Сказано, сделано.
Запустил тесты — всё еще не происходит сохранения в память отчёта. Тогда я обнаружил, что в манифесте WRITE_EXTERNAL_STORAGE ограничен верхней планкой до 28 версии API, то есть запрашивая работу памятью мы не предоставили все разрешения. После изменения верхней планки (конечно, для варианта debug) и запроса пермишена на запись тесты удачно запустились и отчёт Allure сохранился в память устройства.
Добавлены следующие определения пермишенов для debug-сборки.
После всех вышеописанных манипуляций с приложением, можно спокойно устанавливать targetSdkVersion 30, загружать в Google Play и не беспокоиться про дедлайн, после которого загружать приложения версией ниже станет невозможно.
Источник
Fotophire Editing Toolkit
Photo Editor on Different System and Device
1. Mac Photo Editor
2.Mobile Photo Editor
3. Windows Photo Editor
4. Camera or Dslr Photo Editor
5. Photo Editor on PC
6. Alternatives
8 Helpful Android Photo Editors with Layer Support
There are huge numbers of android photo editors with layer support, but what is best, is difficult for one to choose.I have brought finely confined best photo editors that allow the layer support. Layers are important since they allow changing single feature out of multiple, without affecting the others. Hence, for the perfection and professional approach for your pictures, you can use any of these apps to make your picture, a perfect one.
Part 1. Helpful Android Photo Editor with Layer Supports
1. Adobe Photoshop Mix
With the advanced features and easy handling, Adobe Photoshop mix can change your average picture into an exceptional one. With layer opacity up to five layers, you can easily cut and combine your pictures as well as you can enhance the picture using a variety of filters and effects. This app allows you to resize the canvas. Also, you can easily download the app from play store.
- Easy file sharing due to cloud creative system.
- Convenient interface.
- Image editing without distortion.
- Supports the file size up to 5,000 pixels only.
- Few tools could be accessed only after opting for the paid subscription.
- No layers reordering option available.
2. Pixlr
Pixlr, with its amazing features, has cornered the market. This a cloud-based photo editing tool that provides you with a vast range of editing feature that includes easy as well as the advanced one. Now you can devise an image, fetch directly from the web or can upload it from your gallery. It gives you an easily accessible interface which helps you to edit your picture, without any hazard. Auto Fix and Focal Blur tool with more than 600 effects, makes it a remarkable app.
- Comprises advanced filters.
- Allows image editing in Google drive itself.
- Cloud compatible.
- Contains Ads.
- Requires Flash to run.
- Have only basic filters.
3. Multi-Layer Photo Editor
As its name suggests, this amazing app allows you to edit a picture with multiple layers. Just pinching your fingers, you can easily move, rotate or zoom the layers. This app gives you hundreds of filters options to enhance your picture. Its premium feature allows you to work with selection mask as well as you can use blend mode with layers. Also, you can set the custom resolution of your picture. It also removes ads.
- Easy to use.
- Can use its premium features for free.
- Allows background layer zooming.
- Contains Ads.
- Adds watermark on the images.
- Reduces the image quality while applying some features.
4. PicsArt Photo Studio
PicsArt is one of the popular photo editing apps on the Android platform. With its phenomenal editing features, this app allows you to create beautiful collages and memes. With a complete library of artistic photo filters, frames, backgrounds and stickers, you can fine-tune your picture with an ease. Thus, you can produce a great piece with this brilliant app.
- Abundant photo editing tools.
- Allows easy sharing on social platforms.
- Feasible interface.
- Lacks some effects.
- Few features are ambiguous.
- The absence of the feathering option.
5. Canva
If you really want to remove the bruises from your picture and convert it into a flawless one, you can choose Canva that supports multilayers. It is an online photo editing app that provides, a complete tool library that enhances your picture in no more time. Get the free icons and stickers and give a creative touch to your images. This app gives a number of filters and effects to devise a perfect piece of art.
- Intuitive interface.
- Easy sharing on social media.
- Availability of pre-made templates.
- No cropping option in the basic version.
- Difficult to find the needed picture from the huge free image library.
- No option to sort the own designs.
6. Photo Layers
Photo Layers is the android editing app with simple features. You can easily cut, crop and blend different pictures into one with the convenient user interface. Either I can say you can play with its tools to get a pitch-perfect picture. This app allows using 11 pictures at the same time to build a photomontage. This app is suitable for those who want to give a try to photo editing.
- Presence of a detailed guide to help.
- Easy to use.
- Availability of zooming for background layers.
- Contains Ads.
- Lacks advanced tools.
- Limited layers.
7. Byte Mobile- Image Editor
It is a convenient, lightweight app that could be used on an android platform. This app automatically adds images, stickers, frames, and so many other elements on a new layer. It provides standard tools to make changes in a picture. This includes crop, erase, resize, cut, rotate, flip and many more.
- Simple and ease of use.
- A number of filters.
- Allows quick editing.
- Contains Ads.
- Have basic features only.
- Distorts image quality.
8. Photo Editor by Aviary
This is one of the amazing android photo editing apps that beautifies your picture. It is a handy app that comprises of easy to use tools and let you cut, crop, add filters to your picture. It allows you to easily import a picture from gallery or built-in camera. Its high-quality colour correction and a wide range of tools make it perfect to be in the top list.
- Easy to use.
- Diverse editing tools.
- Supports multiple languages.
- Lacks undo and redo options.
- No resize option available.
- Costs extra for some effects.
Part 2. A Recommended Efficient Desktop Photo Editor with Layer Support
If you are looking for an efficient photo editor software that gives a professional touch to a picture and comprises a complete toolkit, then you must go for Wondershare Fotophire Editing Toolkit. It is an all in one photo editing desktop application that converts your good picture into an optimal one. It has an easy to use interface that could be used by dilettante as well as a professional aptly. This app is trending and gaining its popularity among editors due to its astounding features and tools.
- Enables you to apply more than 200 effects to your photos to make them better.
- Crop or cut pictures to the size to meet any of your need.
- Help you to remove any unwanted objects from your photos.
- Allow you to use the Creative Blur to refocus your photos in a click.
- You can easily add more than 200 effects, frames and texture and text to your picture .
- It allows you to adjust tone and colour with blur as well as vignette effect.
- You can compare the before and after view of the image simultaneously.
- Crop, Erase and Clone in the Photo Eraser make your old scratchy picture look all new.
- You can remove the watermark as well as date stamp effortlessly.
How to Use Fotophire Editing Toolkit
Step 1: Download and launch the Fotophire Editing Toolkit on your computer.
Step 2: Then you can browse the image which you want to edit from your computer by clicking «Open» on the screen.
Step 3: Now, after selecting an image, you will be displayed with main editor screen comprising of various editing tools that include effects, crop, and add frames and text option with other basic editing tools. Choose the effects you wanted.
Step 4: You can save your edited image with just a single click on the save button at present the top middle of the screen. Here, Fotophire gives you various image format options to choose from for your image.
Conclusion
In this article, we have introduced several android photo eidtor with layer support, With various photo editors, it has become as easy as pie to edit an image but using Wondershare Fotophire editirng toolkit is something like a cherry on the top. With its user-friendly interface and best features, it has cornered the market.
Источник