Android Widget - AndroidAuthority
Android Widget - AndroidAuthority
Android Widget - AndroidAuthority
HowtocodeasimpleAndroidwidget|AndroidAuthority
NEWS (HTTP://WWW.ANDROIDAUTHORITY.COM/NEWS/)
author/obaroogbo/)
by Obaro Ogbo
https://www.facebook.com/sharer.php?
app_id=598473026880919&u=http://www.androidauthority.com/create
https://twitter.com/intent/tweet?
url=http://www.androidauthority.com/create
608975/&t=How+to+code+a+simple+Android+widget)
https://plus.google.com/share?
url=http://www.androidauthority.com/create
608975/&text=How+to+code+a+simple+Android+widget)
608975/)
http://www.androidauthority.com/createsimpleandroidwidget608975/
1/12
1/19/2017
HowtocodeasimpleAndroidwidget|AndroidAuthority
App widgets can be thought of as a small window or controller for an Android app that can be
embedded in another application (like the homescreen). They can be very useful, allowing users
to view or control an appwithout actually launching it. For example, skipping tracks with a
music player widget, orviewing weather information. The great thing about widgets is that they
can be updated automatically (after a time period), or in response to user action.
In this developer tutorial, we are going to create a simple Android widget, that updates
automatically every 30 minutes, or in response to the user tappingthe update button on the
widget. Our widget generates and displays a random number on every update (whether
automatic or due to user interaction).
(http://cdn03.androidauthority.net/wp-
content/uploads/2015/05/simple-android-widget-sample.png)
2/12
1/19/2017
HowtocodeasimpleAndroidwidget|AndroidAuthority
1. Design the widget layout. At the very least, you will need one layout le describing your
widget layout. However, you can also provide additional layout les for
5. Extend AppWidgetProvider. This class provides methods that are called during a widget
lifecycle.
6. Provide the AppWidgetProviderInfo metadata. Essential information about the widget,
XML
http://www.androidauthority.com/createsimpleandroidwidget608975/
SELECT ALL
3/12
1/19/2017
HowtocodeasimpleAndroidwidget|AndroidAuthority
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="@dimen/widget_margin"
android:background="#55000000">
<ImageView
android:id="@+id/imageView"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:src="@drawable/aa"/>
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="000"
android:textSize="@dimen/abc_text_size_large_material"
android:textStyle="bold"/>
<Button
android:id="@+id/actionButton"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Refresh"/>
</LinearLayout>
Note android:padding in the above code snippet. From Android 4.0, app widgets automatically
get a padding between the widget frame and the widget bounds. Pre-4.0 devices however do
not provide the automatic padding for widgets. To build a widget that has margins for earlier
versions, but no additional margins for 4.0 and above, create two dimension resources
res/values/dimens.xml and res/values-v14/dimens.xml to provide dierent values for widget
margin, and set your targetSdkVersion to 14.
res/values/dimens.xml
XML
http://www.androidauthority.com/createsimpleandroidwidget608975/
SELECT ALL
4/12
1/19/2017
HowtocodeasimpleAndroidwidget|AndroidAuthority
<resources>
<dimen name="widget_margin">8dp</dimen>
</resources>
res/values-v14/dimes.xml
XML
SELECT ALL
<resources>
<dimen name="widget_margin">0dp</dimen>
</resources>
Extending AppWidgetProvider
Now extend AppWidgetProvider, by creating theclass SimpleWidgetProvider.
AppWidgetProvider has methods that are called when the app widget is updated, deleted,
enabled and disabled among others. For our implementation, we only override onUpdate(),
because it is the method called whenever the widget is added to a host.
JAVA
http://www.androidauthority.com/createsimpleandroidwidget608975/
SELECT ALL
5/12
1/19/2017
HowtocodeasimpleAndroidwidget|AndroidAuthority
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
final int count = appWidgetIds.length;
for (int i = 0; i < count; i++) {
int widgetId = appWidgetIds[i];
String number = String.format("%03d", (new Random().nextInt(900) + 100));
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.simple_widget);
remoteViews.setTextViewText(R.id.textView, number);
Intent intent = new Intent(context, SimpleWidgetProvider.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.actionButton, pendingIntent);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}
}
In the onUpdate() method above, we iterate through all of our widgets (in case the user has
placed multiple widgets), get a RemoteViews object, update the RemoteViews textview with a
new random number between 100 and 999, and then specify the action that should occur
when the Button is tapped.
To request a manual update when the update button is clicked, we use a PendingIntent. The
action for the Intent is set to AppWidgetManager.ACTION_APPWIDGET_UPDATE. This is the
same action sent by the system when the widget needs to be updated automatically. We also
indicate the widgets that should be updated (all of the app widgets) by calling
SELECT ALL
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds).
http://www.androidauthority.com/createsimpleandroidwidget608975/
6/12
1/19/2017
HowtocodeasimpleAndroidwidget|AndroidAuthority
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
Finally, we request the AppWidgetManager object to update the app widget, giving it the
current widgetId and the current RemoteViews object.
XML
SELECT ALL
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="120dp"
android:minHeight="60dp"
android:updatePeriodMillis="1800000"
android:initialLayout="@layout/simple_widget"
android:resizeMode="horizontal|vertical"
android:widgetCategory="home_screen|keyguard"
android:previewImage="@drawable/preview">
</appwidget-provider>
Most of the attributes have pretty self explanatory names. minWidth and minHeight specify the
minimum width and height the widget can have. updatePeriodMillis species the update
frequency in milliseconds for the widget. Note that frequent updates will signicantly aect
users battery. Take note of the widgetCategory attribute. This species if your widget can be
available on the lock screen as well as on the home screen. All widgets are available on the
home screen by default, and if not specied. Android 4.2 included the keyguard option,
indicating that the widget can be added to the lock screen.
If your widget is displayed on a lock screen, you might want to show dierent data, or a
dierent layout. To detect if the widget is on a lock screen, you request the widget options using
AppWidgetManagers getWidgetOptions(int widgetId) method. This method returns a bundle,
which can be queried for the AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY int.
This will either be a WIDGET_CATEGORY_HOME_SCREEN or WIDGET_CATEGORY_KEYGUARD.
http://www.androidauthority.com/createsimpleandroidwidget608975/
7/12
1/19/2017
HowtocodeasimpleAndroidwidget|AndroidAuthority
The sample code below checks for the AppWidgetHost, and displays a dierent layout for each
host type.
SELECT ALL
JAVA
AppWidgetManager appWidgetManager;
int widgetId;
Bundle myOptions = appWidgetManager.getAppWidgetOptions (widgetId);
XML
http://www.androidauthority.com/createsimpleandroidwidget608975/
8/12
1/19/2017
HowtocodeasimpleAndroidwidget|AndroidAuthority
(http://cdn02.androidauthority.net/wp-
content/uploads/2015/05/simple-android-widget-complete.gif)
Tappingon the update button should automatically update all your widgets. Can you modify
your code to only update the widget that was tapped? How about updating only one random
widget on tap? Have fun with this, but remember that a widget that updates frequently will be a
drain on the battery.
As usual, the complete code is available for modication and reuse to your hearts content on
github (https://github.com/obaro/SimpleAndroidWidget).
top developer news, tips & links once a week in your inbox:
Email:
http://www.androidauthority.com/createsimpleandroidwidget608975/
9/12
1/19/2017
HowtocodeasimpleAndroidwidget|AndroidAuthority
Subscribe
PS. No spam, ever. Your email address will only ever be used for Android Dev Weekly.
NEWS (HTTP://WWW.ANDROIDAUTHORITY.COM/NEWS/)
DEALS
80
%
http://www.androidauthority.com/createsimpleandroidwidget608975/
88
%
(https://deals.androidauthority.com/sales/brain
(https://deals.androidauthority.com/sales/pwyw
(https://deals.androidauthority.com/sa
fmlifetimesubscription?
learntocode2017googlego?
alllifitimesubscription?
utm_source=androidauthority&utm_campaign=03&utm_medium=widget)
utm_source=androidauthority&utm_campaign=04&utm_medium=widget)
utm_source=androidauthority&utm_c
10/12
-8
8%
HowtocodeasimpleAndroidwidget|AndroidAuthority
-8
0%
1/19/2017
$39
$35
$39
SHOW 7 COMMENTS
http://www.androidauthority.com/createsimpleandroidwidget608975/
11/12
1/19/2017
HowtocodeasimpleAndroidwidget|AndroidAuthority
http://www.androidauthority.com/createsimpleandroidwidget608975/
12/12