Widgets презентация

Содержание


WidgetsЧто такое виджет?
 App Widgets are miniature application views that canТипы виджетов
 As you begin planning your widget, think about whatИнформационные виджеты
 Information widgets typically display a few crucial information elementsВиджеты для коллекций
 As the name implies, collection widgets specialize inУправляющие виджеты
 The main purpose of a control widget is toВиджеты смешанного типа
 While all widgets tend to gravitate towards oneОграничения по жестам
 Because widgets live on the home screen, theyСодержимое виджета
 Widgets are a great mechanism to attract a userОсновные классы
 To create an App Widget, you need the following:
Объявление виджета
 First, declare the AppWidgetProvider class in your application's AndroidManifest.xml file: 
AppWidgetProviderInfo
 The AppWidgetProviderInfo defines the essential qualities of an App Widget, such asАтрибуты AppWidgetProvider
 The values for the minWidth and minHeight attributes specifyАнатомия виджета
 Typical Android app widgets have three main components: aОпределение размера виджета
 When users add a widget to their homeОпределение размера виджета
 Example calculations are below:
 minWidth = 144dp + (2Атрибуты AppWidgetProvider
 The updatePeriodMillis attribute defines how often the App Widget framework shouldАтрибуты AppWidgetProvider
 The initialLayout attribute points to the layout resource that defines theАтрибуты AppWidgetProvider
 The resizeMode attribute specifies the rules by which a widget canАтрибуты AppWidgetProvider
 The widgetCategory attribute declares whether your App Widget can be displayedСоздание макета виджета
 You must define an initial layout for yourПример виджета
 https://git.io/v1MirПроблемы при запуске
 Если при сборке студия выводит сообщение вроде ErrorУстановка виджета
 On most Android devices, you’ll start out by long-pressing a blank,Обновление виджета
 https://git.io/v1SIw
 Особенность параметра updatePeriodMillis: https://developer.android.com/reference/android/appwidget/AppWidgetProviderInfo.html#updatePeriodMillis – минимально допустимое значениеКак удалить виджет из системы
 Чтобы удалить виджет с рабочего стола,Виджет – понятие растяжимое
 https://git.io/v1S6TВиджет + активити
 Добавляем с помощью шаблона новое пустое активити сАктивити + два виджета
 Вообще, добавить новый виджет в приложение неАктивити + два виджетаПрактика
 Добавить Widget2 произвольного размера, home-screen only, без configuration screen
 ДобавитьLollipop+ and LockScreen
 Некоторые приложения, вроде Weather Lockscreen Widget, при установкеПрограммная блокировка
 http://rdcworld-android.blogspot.com/2012/03/lock-phone-screen-programmtically.htmlПрограммная разблокировка
 http://stackoverflow.com/questions/3793221/how-to-display-activity-when-the-screen-is-lockedКласс MediaSession
 При желании, можно разместить элементы управления mp3-плеера на экранеОбновление при щелчке
 https://git.io/v17iBОбновление с помощью сервиса
 Создать файл UpdateWidgetService.java
 https://git.io/v17X7Виджет «Курс валют»
 https://git.io/v1FTzПрактика
 Добавить в виджет «Курс валют» отображение курса покупки доллара
 СоздатьПрактика
 Создать виджет для просмотра картинок с сайта 9gag http://9gag-rss.com/, цитатДополнительные примеры
 http://www.vogella.com/tutorials/AndroidWidgets/article.html
 https://www.sitepoint.com/how-to-code-an-android-widget/
 http://stacktips.com/tutorials/android/app-widgets-example-in-android



Слайды и текст этой презентации
Слайд 1
Описание слайда:
Widgets


Слайд 2
Описание слайда:
Что такое виджет? App Widgets are miniature application views that can be embedded in other applications and receive periodic updates. These views are referred to as Widgets in the user interface, and you can publish one with an App Widget provider. An application component that is able to hold other App Widgets is called an App Widget host. The screenshot below shows the Music App Widget:

Слайд 3
Описание слайда:
Типы виджетов As you begin planning your widget, think about what kind of widget you're trying to build. Widgets typically fall into one of the following categories: Information widgets Collection widgets Control widgets Hybrid widgets

Слайд 4
Описание слайда:
Информационные виджеты Information widgets typically display a few crucial information elements that are important to a user and track how that information changes over time. Good examples for information widgets are weather widgets, clock widgets or sports score trackers. Touching information widgets typically launches the associated app and opens a detail view of the widget information.

Слайд 5
Описание слайда:
Виджеты для коллекций As the name implies, collection widgets specialize in displaying multitude elements of the same type, such as a collection of pictures from a gallery app, a collection of articles from a news app or a collection of emails/messages from a communication app. Collection widgets typically focus on two use cases: browsing the collection, and opening an element of the collection to its detail view for consumption. Collection widgets can scroll vertically.

Слайд 6
Описание слайда:
Управляющие виджеты The main purpose of a control widget is to display often used functions that the user can trigger right from the home screen without having to open the app first. Think of them as remote controls for an app. A typical example of control widgets are music app widgets that allow the user to play, pause or skip music tracks from outside the actual music app. Interacting with control widgets may or may not progress to an associated detail view depending on if the control widget's function generated a data set, such as in the case of a search widget.

Слайд 7
Описание слайда:
Виджеты смешанного типа While all widgets tend to gravitate towards one of the three types described above, many widgets in reality are hybrids that combine elements of different types. For the purpose of your widget planning, center your widget around one of the base types and add elements of other types if needed. A music player widget is primarily a control widget, but also keeps the user informed about what track is currently playing. It essentially combines a control widget with elements of an information widget type.

Слайд 8
Описание слайда:
Ограничения по жестам Because widgets live on the home screen, they have to co-exist with the navigation that is established there. This limits the gesture support that is available in a widget compared to a full-screen app. The only gestures available for widgets are: Touch Vertical swipe

Слайд 9
Описание слайда:
Содержимое виджета Widgets are a great mechanism to attract a user to your app by "advertising" new and interesting content that is available for consumption in your app. Just like the teasers on the front page of a newspaper, widgets should consolidate and concentrate an app's information and then provide a connection to richer detail within the app; or in other words: the widget is the information "snack" while the app is the "meal." As a bottom line, always make sure that your app shows more detail about an information item than what the widget already displays.

Слайд 10
Описание слайда:
Основные классы To create an App Widget, you need the following: AppWidgetProviderInfo object - describes the metadata for an App Widget, such as the App Widget's layout, update frequency, and the AppWidgetProvider class. This should be defined in XML AppWidgetProvider class implementation - defines the basic methods that allow you to programmatically interface with the App Widget, based on broadcast events. Through it, you will receive broadcasts when the App Widget is updated, enabled, disabled and deleted View layout - defines the initial layout for the App Widget, defined in XML

Слайд 11
Описание слайда:
Объявление виджета First, declare the AppWidgetProvider class in your application's AndroidManifest.xml file: The <receiver> element requires the android:name attribute, which specifies the AppWidgetProvider used by the App Widget. The <meta-data> element specifies the AppWidgetProviderInfo resource and requires the following attributes: android:name - specifies the metadata name. Use android.appwidget.provider to identify the data as the AppWidgetProviderInfo descriptor. android:resource - specifies the AppWidgetProviderInfo resource location

Слайд 12
Описание слайда:
AppWidgetProviderInfo The AppWidgetProviderInfo defines the essential qualities of an App Widget, such as its minimum layout dimensions, its initial layout resource, or how often to update the App Widget. Define the AppWidgetProviderInfo object in an XML resource using a single <appwidget-provider> element and save it in the project's res/xml/ folder:

Слайд 13
Описание слайда:
Атрибуты AppWidgetProvider The values for the minWidth and minHeight attributes specify the minimum amount of space the App Widget consumes by default. The default Home screen positions App Widgets in its window based on a grid of cells that have a defined height and width. If the values for an App Widget's minimum width or height don't match the dimensions of the cells, then the App Widget dimensions round up to the nearest cell size.

Слайд 14
Описание слайда:
Анатомия виджета Typical Android app widgets have three main components: a bounding box, a frame, and the widget's graphical controls and other elements. App widgets can contain a subset of the View widgets in Android; supported controls include text labels, buttons, and images. Well-designed widgets leave some margins between the edges of the bounding box and the frame, and padding between the inner edges of the frame and the widget's controls.

Слайд 15
Описание слайда:
Определение размера виджета When users add a widget to their home screen, it will generally occupy more than the minimum width and height you specify. Home screens offer users a grid of available spaces into which they can place widgets and icons. This grid can vary by device; for example, many handsets offer a 4x4 grid, and tablets can offer a larger, 8x7 grid. When your widget is added, it will be stretched to occupy the minimum number of cells, horizontally and vertically, required to satisfy its minWidth and minHeight constraints. While the width and height of a cell — as well as the amount of automatic margins applied to widgets — may vary across devices, you can use the table below to roughly estimate your widget's minimum dimensions, given the desired number of occupied grid cells:

Слайд 16
Описание слайда:
Определение размера виджета Example calculations are below: minWidth = 144dp + (2 × 8dp) + (2 × 56dp) = 272dp minHeight = 48dp + (2 × 4dp) = 56dp

Слайд 17
Описание слайда:
Атрибуты AppWidgetProvider The updatePeriodMillis attribute defines how often the App Widget framework should request an update from the AppWidgetProvider by calling the onUpdate() callback method. The actual update is not guaranteed to occur exactly on time with this value and we suggest updating as infrequently as possible — perhaps no more than once an hour to conserve the battery.  If the device is asleep when it is time for an update (as defined by updatePeriodMillis), then the device will wake up in order to perform the update!

Слайд 18
Описание слайда:
Атрибуты AppWidgetProvider The initialLayout attribute points to the layout resource that defines the App Widget layout The previewImage attribute specifies a preview of what the app widget will look like after it's configured, which the user sees when selecting the app widget. If not supplied, the user instead sees your application's launcher icon:

Слайд 19
Описание слайда:
Атрибуты AppWidgetProvider The resizeMode attribute specifies the rules by which a widget can be resized. You use this attribute to make homescreen widgets resizeable — horizontally, vertically, or on both axes. Users touch-hold a widget to show its resize handles, then drag the horizontal and/or vertical handles to change the size on the layout grid. Values for the resizeMode attribute include "horizontal", "vertical", and "none". To declare a widget as resizeable horizontally and vertically, supply the value "horizontal|vertical"

Слайд 20
Описание слайда:
Атрибуты AppWidgetProvider The widgetCategory attribute declares whether your App Widget can be displayed on the home screen (home_screen), the lock screen (keyguard), or both. Only Android versions lower than 5.0 support lock-screen widgets! For Android 5.0 and higher, only home_screen is valid…

Слайд 21
Описание слайда:
Создание макета виджета You must define an initial layout for your App Widget in XML and save it in the project's res/layout/ directory. You can design your App Widget using the View objects listed below. Creating the App Widget layout is simple if you're familiar with Layouts. However, you must be aware that App Widget layouts are based on RemoteViews, which do not support every kind of layout or view widget. App Widget can support the following layout classes: FrameLayout, LinearLayout, RelativeLayout and GridLayout. And the following widget classes: AnalogClock, Button, ImageButton, ImageView, ProgressBar, TextView, ListView and GridView. Descendants of these classes are not supported! RemoteViews also supports ViewStub, which is an invisible, zero-sized View you can use to lazily inflate layout resources at runtime.

Слайд 22
Описание слайда:
Пример виджета https://git.io/v1Mir

Слайд 23
Описание слайда:
Проблемы при запуске Если при сборке студия выводит сообщение вроде Error running app: Default Activity not found, тогда поможет: File > Invalidate caches / Restart… Build > Rebuild project Run > Edit configurations > Android App > app > Launch Options > Launch: Nothing

Слайд 24
Описание слайда:
Установка виджета On most Android devices, you’ll start out by long-pressing a blank, available space on your home screen — not on an icon or the app launcher. Just hold your finger down on the screen.

Слайд 25
Описание слайда:
Обновление виджета https://git.io/v1SIw Особенность параметра updatePeriodMillis: https://developer.android.com/reference/android/appwidget/AppWidgetProviderInfo.html#updatePeriodMillis – минимально допустимое значение 1800000 мс (30 минут), впрочем AlarmManager или сервис позволит решить эту проблему: http://stackoverflow.com/questions/3310264/frequently-updating-widgets-more-frequently-than-what-updateperiodmillis-allows Добавлена реакция на создание и удаление виджета

Слайд 26
Описание слайда:
Как удалить виджет из системы Чтобы удалить виджет с рабочего стола, удерживайте палец на окне виджета в течении 1-2 секунд и переместите виджет в корзину Чтобы удалить виджет из системы, зайдите в Настройки > Приложения > Установленные приложения, выберите из списка нужный виджет и в его меню выберите "Удалить"

Слайд 27
Описание слайда:
Виджет – понятие растяжимое https://git.io/v1S6T

Слайд 28
Описание слайда:
Виджет + активити Добавляем с помощью шаблона новое пустое активити с названием Widget1 В главном меню Run > Edit Configurations… > Android App > app > Launch Options возвращаем на место Launch: Default Activity Возможно, вновь придётся выполнить Build > Clean Project, затем Build > Make Project, опционально Rebuild Project, и наконец Run > Run app… https://git.io/v1SN5

Слайд 29
Описание слайда:
Активити + два виджета Вообще, добавить новый виджет в приложение не представляет особой сложности:

Слайд 30
Описание слайда:
Активити + два виджета

Слайд 31
Описание слайда:
Практика Добавить Widget2 произвольного размера, home-screen only, без configuration screen Добавить Widget3 с configuration screen, протестировать установку виджетов Если версия ОС KitKat и ниже, создать виджет для keyguard (lock screen)

Слайд 32
Описание слайда:
Lollipop+ and LockScreen Некоторые приложения, вроде Weather Lockscreen Widget, при установке на ОС Lollipop и выше, ведут себя так, будто действительно размещаются на экране блокировки. На самом деле, они лишь эмулируют поведение лок-скрина, реагируя на пробуждение программной разблокировкой.

Слайд 33
Описание слайда:
Программная блокировка http://rdcworld-android.blogspot.com/2012/03/lock-phone-screen-programmtically.html

Слайд 34
Описание слайда:
Программная разблокировка http://stackoverflow.com/questions/3793221/how-to-display-activity-when-the-screen-is-locked

Слайд 35
Описание слайда:
Класс MediaSession При желании, можно разместить элементы управления mp3-плеера на экране блокировки, но для этого потребуется настройка объекта типа MediaSession:

Слайд 36
Описание слайда:
Обновление при щелчке https://git.io/v17iB

Слайд 37
Описание слайда:
Обновление с помощью сервиса Создать файл UpdateWidgetService.java https://git.io/v17X7

Слайд 38
Описание слайда:
Виджет «Курс валют» https://git.io/v1FTz

Слайд 39
Описание слайда:
Практика Добавить в виджет «Курс валют» отображение курса покупки доллара Создать виджет «Электронные часы», который будет отображать текущее время в формате ЧЧ:ММ:СС Создать виджет «Погода», который будет показывать прогноз погоды на сегодня (температуру, скорость ветра)

Слайд 40
Описание слайда:
Практика Создать виджет для просмотра картинок с сайта 9gag http://9gag-rss.com/, цитат с башорга http://bash.im/rss/ или любого другого сайта, предоставляющего RSS. Создать виджет-календарь, который будет обновляться раз в день

Слайд 41
Описание слайда:
Дополнительные примеры http://www.vogella.com/tutorials/AndroidWidgets/article.html https://www.sitepoint.com/how-to-code-an-android-widget/ http://stacktips.com/tutorials/android/app-widgets-example-in-android


Скачать презентацию на тему Widgets можно ниже:

Tags Widgets
Похожие презентации