0% found this document useful (0 votes)
77 views59 pages

2.1 App Widgets

This document discusses app widgets in Android, which are miniature app views that can appear on the home screen. It covers how to create an app widget by adding components like a provider info XML file, layout, and provider class. The provider class receives broadcasts to update the widget. Configurable widgets can have a configuration activity. Maintaining a reasonable update interval is important for battery life.

Uploaded by

Anonn Nymous
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views59 pages

2.1 App Widgets

This document discusses app widgets in Android, which are miniature app views that can appear on the home screen. It covers how to create an app widget by adding components like a provider info XML file, layout, and provider class. The provider class receives broadcasts to update the widget. Configurable widgets can have a configuration activity. Maintaining a reasonable update interval is important for battery life.

Uploaded by

Anonn Nymous
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 59

Advanced Android Development

App widgets

Lesson 2

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 1
national License
2.1 App widgets
Create miniature app views for home screen

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 2
national License
Contents
● Overview of app widgets
● Adding an app widget to an app
● Updating the provider-info file
● Defining the app widget layout
● Creating the app widget-provider class
● App widget updates and actions
● Using a configuration activity
This work is licensed under a
Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 3
national License
Overview
App widgets

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 4
national License
What are app widgets?

● Miniature app views for apps


● Appear on home screen
● Updated with new data even if apps are
not running

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 5
national License
How to install widgets
● When user installs app, associated app
widgets appear in widget picker
● User long-presses home screen and
taps Widgets
○ Widget picker appears with list

● User selects app widget to place on


home screen
This work is licensed under a
Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 6
national License
What can app widgets do?
● Display info
● Perform simple functions such as
○ Showing the time
○ Summarizing calendar events
○ Controlling music playback

● Provide a scrolling list or collection


● Open associated app when tapped
This work is licensed under a
Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 7
national License
App widget components
● Provider-info XML file defines metadata
● Layout XML file for UI
● AppWidgetProvider for Java code
● Configuration activity (optional)
○ Choose what to display
○ See Android News & Weather widget for example

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 8
national License
Provider-info XML metadata

● Initial or minimum size


● Update interval
● Configuration activity (if any)
● Preview image

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 9
national License
Example: Provider-info XML file
<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:initialKeyguardLayout="@layout/new_app_widget"
android:initialLayout="@layout/new_app_widget"
android:minHeight="180dp"
android:minWidth="110dp"
android:previewImage="@drawable/example_appwidget_preview"
android:resizeMode="horizontal|vertical"
android:updatePeriodMillis="1800000"
android:widgetCategory="home_screen">
</appwidget-provider>
This work is licensed under a
Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 10
national License
App widget-provider class

● App widgets are broadcast receivers


● Extend AppWidgetProvider, which extends
BroadcastReceiver
● AppWidgetProvider objects receive only broadcasts
relevant to app widget
○ Including intents for update, enabled, disabled, and deleted
○ App widget providers are declared in Android manifest
This work is licensed under a
Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 11
national License
App widget manager and host
● App widget controlled by manager and host
● AppWidgetManager
○ Manages widget content updates
○ Sends broadcast intents
● AppWidgetHost holds and displays app widgets
○ Home screen is most frequent host
○ Also possible to create your own host

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 12
national License
Update the app widget
● Update interval is defined in provider-info file
○ Must be at least 30 minutes to avoid performance issues

● App can request app widget update explicitly


● App widget manager sends broadcast intent with
ACTION_APPWIDGET_UPDATE
● Widget-provider class receives intent and calls onUpdate()
● Implement onUpdate() in widget-provider class
This work is licensed under a
Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 13
national License
App widget updates and battery life
● Updates occur whether or not app is running
● App widgets can wake sleeping device to do update
● Enabling very frequent updates is bad design
● Best practice is to design app widgets so they do
not need frequent updates

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 14
national License
Configurable app widgets
● Some widgets need to be configured by
user
○ Photo widget needs user to pick photo
○ Stock-ticker widget needs list of stock symbols

● Configuration activity appears when user


first adds app widget
● User can use multiple copies of same app
widget with different configurations
This work is licensed under a
Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 15
national License
Adding an app
widget to an app

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 16
national License
Add app widget in Android Studio (1)

1. Select File > New > Widget >


App Widget
2. Class name must include the
word Widget
3. Placement: Home-screen only

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 17
national License
Add app widget in Android Studio (2)

● Minimum width and height


● Configuration Screen option to
include configuration activity

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 18
national License
Project files related to app widgets
Android Studio adds or modifies the following files:
● Provider class NewAppWidget.java (extends AppWidgetProvider)
● Layout file in res/layouts/new_app_widget.xml
● Provider-info file in res/xml/new_app_widget_info.xml
● Configuration Screen option adds
NewAppWidgetConfigurationActivity.java
● Android manifest is updated to include provider and configuration
activity classes

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 19
national License
Updating the
provider info
Updating the app widget
provider-info file

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 20
national License
App widget provider-info file

App widget info XML file contains a single <appwidget-


provider> element with these attributes:

minHeight previewImage
minWidth resizeMode
initialLayout widgetCategory
updatePeriodMillis configure

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 21
national License
Example app widget provider info (1)

<appwidget-provider

xmlns:android="http://schemas.android.com/apk/res/android"
android:minHeight="40dp"
android:minWidth="40dp"
android:initialLayout="@layout/new_app_widget"
android:updatePeriodMillis="86400000"
android:previewImage="@drawable/new_appwidget_preview"

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 22
national License
Example app widget provider info (2)

android:resizeMode="horizontal|vertical"
android:widgetCategory="home_screen"
android:configure=
"Com.example.android.widgettest
.MyAppWidgetConfigureActivity">
</appwidget-provider>

See AppWidgetProviderInfo for more information


This work is licensed under a
Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 23
national License
Minimum initial size

● Home screen provides grid cells (varies by device)


● App widget stretches both horizontally and vertically to
occupy grid cells based on android:resizeMode attribute
● Rule for how many dp fit into a grid cell:
○ 70 × grid_size − 30
○ grid_size is the number of cells for the widget

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 24
national License
Minimum initial size table

# of columns or rows minWidth or minHeight

1 40 dp
2 110 dp
3 180 dp

4 250 dp

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 25
national License
Widget examples

4X1 2X2 3X2 3X3


This work is licensed under a
Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 26
national License
Defining the
app widget
layout
Defining the XML layout for the
app widget UI

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 27
national License
Design the app widget layout
● Keep small and display limited info
● See Widgets and App Widget Design Guidelines
● Example:
Layout for 1x2 weather widget shows ImageView,
TextView, and Button inside a LinearLayout

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 28
national License
App widget margins
App widgets need extra space around edges—API 14 and
newer adds space for you
○ Android Studio creates resources for pre-14 and newer versions
○ widget_margin defined in default dimens.xml and new dimens.xml
(v14) files
○ android:padding attribute added:
android:padding="@dimen/widget_margin"

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 29
national License
Remote views
● App widget layouts are based on RemoteViews
● View hierarchy displayed in different process than app but
with same permissions
● Supports only subset of layouts and views (no custom
views)

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 30
national License
App widget updates app
Each time app widget updates your app it does the following:
● Creates a RemoteViews object from the layout
● Updates the views in the layout with data
● Passes remote view to app widget manager to display

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 31
national License
Layouts supported by RemoteViews

● FrameLayout
● LinearLayout
● RelativeLayout
● GridLayout

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 32
national License
Views supported by RemoteViews
● TextView, ListView
● Button, ImageButton, ImageView
● AnalogClock, Chronometer, ProgressBar
● ViewFlipper, GridView, StackView,
AdapterViewFlipper
● ViewStub—invisible, zero-sized View to lazily inflate
layout resources at runtime This work is licensed under a
Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 33
national License
Creating the
provider
Implementing the app widget-
provider class

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 34
national License
Create app widget-provider class
1. Extend AppWidgetProvider
2. Override onUpdate() to construct layout and manage
updates
3. Optional: Implement additional widget actions
4. Declare app widget provider as broadcast receiver in
AndroidManifest.xml

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 35
national License
Sample app widget-provider class
Android Studio template code supports multiple app widgets
public class NewAppWidget extends AppWidgetProvider {
@Override
public void onUpdate(Context context,
AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
// Update the app widget
}
}
}
This work is licensed under a
Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 36
national License
Other app widget-provider methods
● onDeleted(): Called when app widget instances are
deleted
● onEnabled(): Called when app widget is instantiated
● onDisabled(): Called when last app widget instance is
deleted

See AppWidgetProvider for details

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 37
national License
Declare provider in Android manifest
Android Studio adds <receiver> element
<receiver android:name="NewAppWidgetProvider" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="@xml/example_appwidget_info" />
</receiver>

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 38
national License
Key parts of Android manifest entry

● name in <receiver> is class name for widget provider


● <intent-filter> declares APPWIDGET_UPDATE to receive
broadcast intents from app widget manager
● <meta-data> specifies location of widget provider-info file

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 39
national License
App widget
updates and
actions
Using onUpdate() and attaching
actions with pending intents

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 40
national License
Implement app widget updates
1. Implement onUpdate() to receive updated data
○ Called when user adds app widget
○ Called every time app widget receives update broadcast intent

2. Set up app widget in onUpdate()


○ Create app widget layout
○ Define event handlers for views
○ Start services
3. Use onUpdate() to update app widget
This work is licensed under a
Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 41
national License
Example: Implement onUpdate()

@Override
public void onUpdate(Context context,
AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// Multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
// Construct the RemoteViews object
// ...

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 42
national License
Example: App widget setup
// ...
// Construct the RemoteViews object
RemoteViews views = new RemoteViews(
context.getPackageName(), R.layout.new_app_widget2);
// Update a text view to display the app widget ID
views.setTextViewText(R.id.appwidget_id,
String.format("%s",appWidgetId));
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
This work is licensed under a
Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 43
national License
Updating the app widget
onUpdate() loop iterates over array of widget IDs
● App widget may have multiple instances (configurations)
● All active widget instances are identified by internal ID
● onUpdate() is passed array of IDs for widgets that need updating
onUpdate() must:
● Reconstruct app widget layout
● Update app widget data
● Call app widget manager to update widget with current RemoteViews
object
This work is licensed under a
Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 44
national License
Provide app widget actions
● Attach actions to app widget with pending intents
● Use setOnClickPendingIntent() to connect
PendingIntent to one or more views in app widget
● Android delivers intents to your app (or any other app)
● Add click-event handlers to onUpdate()

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 45
national License
Sample app widget action (1)

public void onUpdate(Context context,


AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// ...
// Create a new explicit intent object
Intent intent = new Intent(context, MainActivity.class);
// Wrap intent in pending intent that starts new activity
// ...

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 46
national License
Sample app widget action (2)
// ...
PendingIntent configPendingIntent =
PendingIntent.getActivity(context, 0, intent, 0);
// Attach the pending intent to a view in the layout file
// for the widget (appwidget_layout is the entire widget)
views.setOnClickPendingIntent(
R.id.appwidget_layout, configPendingIntent);
// ...
}

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 47
national License
Using a
configuration
activity
Let the user configure the app
widget settings

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 48
national License
Let user configure settings
Calendar widget
● Add app widget configuration settings

activity to your app


● Configuration activity
launches when user first adds
app widget to home screen

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 49
national License
Add configuration activity to your app
When adding app widget select Configuration Screen option

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 50
national License
Android manifest entry
Activity declared in Android manifest with intent filter that
accepts ACTION_APPWIDGET_CONFIGURE

<activity android:name=".ExampleAppWidgetConfigure">
<intent-filter>
<action
android:name=
"android.appwidget.action.APPWIDGET_CONFIGURE"/>
</intent-filter>
</activity>
This work is licensed under a
Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 51
national License
Automatic widget-provider entry
Configuration activity is also declared in provider-info XML file
using android:configure attribute

<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:configure=
"com.example.android.ExampleAppWidgetConfigure"
... >
</appwidget-provider>

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 52
national License
Implement configuration activity

1. Get app widget ID from intent extras


2. Set default activity result
3. Get widget configuration data and store for later access
(Example: shared preferences)

4. Request app widget update


5. Create new intent to close activity
This work is licensed under a
Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 53
national License
Get app widget ID
In onCreate() get app widget ID from intent extras with key
AppWidgetManager.EXTRA_APPWIDGET_ID

Intent intent = getIntent();


Bundle extras = intent.getExtras();
if (extras != null) {
mAppWidgetId = extras.getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
}
This work is licensed under a
Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 54
national License
Set default result
In onCreate() set default activity result to RESULT_CANCELED

// This causes the widget host to cancel


// the widget placement if the user presses back button.
setResult(RESULT_CANCELED);

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 55
national License
Request app widget update
Use click handler to request app widget update

AppWidgetManager appWidgetManager =
AppWidgetManager.getInstance(this);
// Create RemoteViews object with the widget layout resource
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.example_appwidget);
// Update app widget with widget ID and new remote view:
appWidgetManager.updateAppWidget(mAppWidgetId, views);

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 56
national License
Create new intent to close activity
Create new intent with widget ID as intent extra
○ Use key AppWidgetManager.EXTRA_APPWIDGET_ID
○ Set result to RESULT_OK and call finish()

Intent resultValue = new Intent();


resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
mAppWidgetId);
setResult(RESULT_OK, resultValue);
finish();

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 57
national License
What's next?

● Concept chapter: 2.1 App widgets


● Practical: 2.1 Building app widgets

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 58
national License
END

This work is licensed under a


Advanced Android Development App widgets Creative Commons Attribution 4.0 Inter 59
national License

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy