View widget in android

How to create widgets in android

Aug 26, 2017 · 12 min read

This article will guide you through the complete process of widget creation. We will do this in steps:

  1. Introduction to widgets
  2. Create a widget of 1*1 dimension: we will add the basic files to the project that is needed to create a widget.
  3. Add the click listener: we will see here that how the click listener works and how it is different from the normal click listener.
  4. Adding multiple widgets for your app: We will see how to different widgets to the widget provider.
  5. Update the Data/UI for widget: We will detect the size of the widget and then accordingly change the data/UI for the widget.
  6. Handling adapters for widget: We will see how to add Gridview/Listview/Stackview on the widget.

I have created a sample project to guide you through this tutorial for creating the widget. you can take the pull from here.

tashariko/widget_sample

widget_sample — tutorial to how to create a widget

Here i have created branches for all the steps required. I think this project is going to be sufficient to get the idea on how to create a widget in android. ok then, let’s get started.

Introduction to widgets

Widget is the part of our android application, which stays outside the app. It operates in a different process than our application. These are treated as a separate app that works on homescreen. So instead of using normal Views that we use in our application, android uses Remote Views. Remote views seems just like any other xml views that we use in app creation, but with minor changes.

For example, this is the layout file for our widget, for now it just shows an image.

Although they seems similar to normal views they have some limitations on what they can support. They normally support all the popular basic views, but views like constraint layout and recycler views are not supported, to see the full list of supported views you can refer to :

App Widgets | Android Developers

App Widgets are miniature application views that can be embedded in other applications (such as the Home screen) and…

Now, to access the views in java file we use findViewById(). But here we have methods like setTextViewText() to add text to the textview.

Now lets start with adding a widget to our homescreen.

Create a widget of 1*1 dimension

We are going to place a widget on the homescreen, for now it will show a icon there. This icon will be of 1*1 dimension.

Switch to branch step_1-basic_widget_creation.

At first we need to add a file at res/xml. i am calling this file sample_widget_info.xml. It consist of “ appwidget-provider” which gives the basic information regarding our widget. It is as follows:

  • According to the above image, to create a widget of 1*1 dimension we need the minWidth and minHeight of 40dp respectively.
  • initialLayout attribute decides which view to use initially when we add the widget to the homescreen.
  • preview_image attribute decides what icon/image to show in the widget selector. Here as our selection of dimension, the icon is shows as 1*1 widget.
  • resizeMode attribute defines if we want the widget to be able to expand horizontally or vertically.
  • updatePeriodMillis attribute defines when time interval to update the widget. the minimum time we can give is 30 minutes i.e. 1800000.
  • widgetCategory attribute defines where to put the widget homescreen or keyboard.

Now we have to tell android that we have added the widget for our app and we do this by defining a receiver in the manifest file. This receiver will extend AppWidgetProvider , here that file is SampleAppWidgetProvider.

We will add this receiver in the manifest file.

Here we added the action to detect:

  • An new instance of Your AppWidget added to Home Screen from AppWidget Chooser( from AppWidget provider) is added.
  • When requested update interval having lapsed which you have provided in AppWidget info file using android:updatePeriodMillis attribute.
  • When device reboot

The meta-data points to the info file we created for our widget.

Now if all has gone correctly, after installing the app, you can see the widget option in the widget provider in your mobile. just drag it on the homescreen and you can see it.

Add the click listener

Now we want to open an activity when we click on that widget. Here the click implementation is a little different than the normal click listener. We are using pending intent to open an activity here. Pending intent is used here because by this we can declare an Intent and and execute it on the click of the widget, same as we use it for notifications.

To learn more about Pending Intent go to:

Читайте также:  Настройка беспроводной клавиатуры для андроид

PendingIntent | Android Developers

By giving a PendingIntent to another application, you are granting it the right to perform the operation you have…

Now switch to the branch step_2-widget_click_implementation.

For implement the click, we are now going to use file SampleAppWidgetProvider. Here we are only going to use onUpdate() method. This method get called whenever there is a chance that the widget gets updated (not the widgets dimensions or options, more on this later).

It provides following parameters:

  • Context : To provide us the context. gets information about installed AppWidget providers and other AppWidget related state.
  • AppWidgetManager : Gives information about installed AppWidgets providers and other AppWidget related state.
  • int[] : This is an array of appWidgetIds, these ids represents all the AppWidgets that are available on the homescreen for our app.

Now, we are going to add a for loop in onUpdate() method to access all the widgets that are available on the homescreen for our app.

Here updateAppWidget() method will handle the Remote Views work. For now we only want to open an activity nothing more. so our updateAppWidget() method will look like this:

Here we did 3 things:

  • Created a pending intent to open MainActivity.
  • Constructed a Remote View and added the click listener via the method setOnClickPendingIntent().
  • Instruct the widget to update the widget, we will call this method everytime we update the widget.

All is done, now try it yourself, now if you click on the icon in the app widget, then you can open an activity.

Ok, now lets go a step further, and we will add 2 images in the widget and we will open different activities on each click. If you have issue regarding that, switch the branch to

Switch to the branch step_2-widget_multi_click_implementation

Adding multiple widgets for your app

We added a single widget to home screen, now what if you want one widget to open an activity like we did before and another widget to show the list on homescreen. Suppose you need these 2 widgets,

Now for this you need 2 types of views.

There are two ways to do it.

  • We can use one xml file and one AppWidgetProvider and detect the change in dimension when you increase or decrease the size and refresh the view to show the new view and handle accordingly. But in this case in the Widget provider you will only see one widget with the dimension you define in the info file sample_widget_info.xml.
  • We can use 2 xml file and 2 AppWidgetProvider for these 2 widgets. The plus point here is that we will be seeing 2 widgets in the Widget Provider but here we cant change the size of the 2 widgets below the minimum dimensions we provide. Here we will try this step and we will look into the first one afterwards.

Switch to the branch step_3-multiple_widget.

Lets create a second info file white_sample_widget_info.xml, second AppWidgetProvider file SampleWhiteAppWidgetProvider.java and second layout file layout_widget_white_simple.xml. If you have any problem then refer to the code in the above mentioned branch.

Now we will implement the first method to show multiple view in single widget.

Switch to the branch step_3-multiple_view_single_widget

Here we have 2 views but one AppWidgetProvider.

Now this method is a little tricky one, as mentioned above in step 3 the onUpdate() method don’t get called when you change the dimension of the widget, instead onAppWidgetOptionsChanged() methods gets called. So instead of calling the update method to get the Remote View, we are going to use a service which will notify that the view is updated and via that we w will refresh the widget. The service is going to be an Intent Service WidgetUpdateService.java.

This service is triggered from 2 places, from onUpdate() method and from onAppWidgetOptionsChanged(). Now we are going to create a Remote View object from that service, We did this because we want to detect the change in dimensions of the widget and it cant be done from onUpdate() method. So the 2 methods in our SampleAppWidgetProvider.java will look like this:

In startActionUpdateAppWidgets() method we are starting the service as

We will handle ACTION_UPDATE_APP_WIDGETS action in onHandleIntent() method. Here we are going to get an instance of AppWidgetManager and via this we are going to call the update method updateAppAllWidget() of SampleAppWidgetProvider.java class to get the Remote View. We will do this as:

And the updateAppAllWidget() now handles the updation of all the widgets on the screen(the work we were doing in onUpdate() is done here). It looks like this:

Now we want to detect the change in dimension of the widget, we do this as:

As you can see, to get the width we use the method getAppWidgetOptions (). This method can be used to any other option also. So to get the minimum width of the widget i used the code:

So we are providing the updateAppWidget() remote view according to our need. By the table I mentioned above for dimensions, I put the check of widget width less than 300 to occupy minimum of 4 blocks of homescreen. If width is less than 300, i want to show the smaller layout else the larger view of the widget.

One thing to notice, I used 300 as my mark if I want the size of the widget less than 4*1. It came from that table only, but to remember it easily I use multiple of 100. For most cases this will work.

Update the Data/UI for widget

It will be going to be same as above with minor changes, just to make this this updating concept clear.

Switch to the branch step_4-update_view_by_height.

Suppose you want to show a text at the top of widget if the height of the widget is increased. If height of the widget is greater than 100, we will show the text.

Here we use the PendingIntent flag FLAG_UPDATE_CURRENT because we wanted to update the current state of the MainActivity.

Читайте также:  Есть ли модемы для андроид

Handling adapters for widget

These are all simple views we used to show on the widget, what if we want to show a Collection View(listview or a gridview or a stackview).StackView is the image view we see for some apps. eg. Android Authority app) All uses the same concept so i am going to use a listview here.

As normal Listview for widget, we need the adapter here, but the normal adapter will not work here, instead we are going to start a service which will trigger the adapter and handle our listview.

Switch to the branch step_5-widget_list_view.

Few things to notice here:

  • we will use setRemoteAdapter() method to attach the adapter to our ListView. You can see this in our WidgetProvider.
  • It will start the RemoteViewsService service which trigger, the RemoteViewsService.RemoteViewsFactory. Its an interface for an adapter between a remote collection view, in our case for ListView. You can see this in ListViewWidgetService.
  • We are detecting the change in the size of the widget in onAppWidgetOptionsChanged() and if width is greater than 300 we are starting the service.

In the service we are creating the data and saving it in sharedprefs. You can handle data however you want to handle. After that same process, get the instance of AppWidgetManager and call updateAllAppWidget().

Now in the adapter class AppWidgetListView. Mainly there are 2 important methods, getCount() to get the size of the list to show and getViewAt() to get the remote view of the specific position.

Now, we have to implement the click on the list item to do a task, here we are opening the activity with some data. In remoteView the click works differently on collection views. Implementing the click to each of the item is an expensive task, so we implement the click to the complete list view in the AppWidgetProvider.

Then we add the extra data for our click in the adapter we created in getViewAt. It is done by fillInIntent.

So after implementing the click, our getViewAt() method looks like this:

Now if you run the app, you can see the complete work with the click on the list item.

Источник

Android (Home screen) Widgets — Tutorial

Developing Android Widgets. This article describes how to create home screen widgets in Android.

1. Prerequisites

The following description assume that you already have experience in building standard Android application. Please see https://www.vogella.com/tutorials/Android/article.html — Android Tutorial. It also partly uses Android services. You find an introduction into Android Services in https://www.vogella.com/tutorials/AndroidServices/article.html — Android Service Tutorial.

2. Android Widgets

2.1. Overview about AppWidgets

2.2. Home screen widgets

Home screen widgets are broadcast receivers which provide interactive components. They are primarily used on the Android home screen. They typically display some kind of data and allow the user to perform actions with them. For example, a widget can display a short summary of new emails and if the user selects an email, it could start the email application with the selected email.

To avoid confusion with views (which are also called widgets), this text uses the term home screen widgets, if it speaks about widgets.

A widget runs as part of the process of its host. This requires that the widget preserves the permissions of their application.

Widget use RemoteViews to create their user interface. A RemoteView can be executed by another process with the same permissions as the original application. This way the widget runs with the permissions of its defining application.

The user interface for a Widget is defined by a broadcast receiver. This receiver inflates its layout into an object of type RemoteViews . This object is delivered to Android, which hands it over the home screen application.

2.3. Steps to create a Widget

To create a widget, you:

Define a layout file

Create an XML file ( AppWidgetProviderInfo ) which describes the properties of the widget, e.g. size or the fixed update frequency.

Create a BroadcastReceiver which is used to build the user interface of the widget.

Enter the Widget configuration in the AndroidManifest.xml file.

Optional you can specify a configuration activity which is called once a new instance of the widget is added to the widget host.

2.4. Widget size

Before Android 3.1 a widget always took a fixed amount of cells on the home screen. A cell is usually used to display the icon of one application. As a calculation rule you should define the size of the widget with the formula: ((Number of columns / rows) * 74) — 2 . These are device independent pixels and the -2 is used to avoid rounding errors.

As of Android 3.1 a widget can be flexible in size, e.g., the user can make it larger or smaller. To enable this for widget, you can use the android:resizeMode=»horizontal|vertical» attribute in the XML configuration file for the widget.

3. Creating the Broadcast receiver for the widget

3.1. Create and configure widget

To register a widget, you create a broadcast receiver with an intent filter for the android.appwidget.action.APPWIDGET_UPDATE action.

The receiver can get a label and icon assigned. These are used in the list of available widgets in the Android launcher.

You also specify the meta-data for the widget via the android:name=»android.appwidget.provider attribute. The configuration file referred by this metadata contains the configuration settings for the widget. It contains, for example, the update interface, the size and the initial layout of the widget.

3.2. Available views and layouts

A widget is restricted in the View classes it can use. As layouts you can use the FrameLayout , LinearLayout and RelativeLayout classes. As views you can use AnalogClock , Button , Chromometer , ImageButton , ImageView , ProgressBar and TextView .

As of Android 3.0 more views are available: GridView , ListView , StackView , ViewFlipper and AdapterViewFlipper . These adapter views require that you define a collection view widget which is described later in this tutorial.

The only interaction that is possible with the views of a widget is via an OnClickListener event. This OnClickListener can be registered on a widget and is triggered by the user.

Читайте также:  Bluetooth клавиатура для android с трекпадом

3.3. AppWidgetProvider

Your BroadcastReceiver implementation typically extends the AppWidgetProvider class.

The AppWidgetProvider class implements the onReceive() method, extracts the required information and calls the following widget life cycle methods.

As you can add several instances of a widget to the home screen, you have life cycle methods which are called only for the first instance added / removed to the home screen and others which are called for every instance of your widget.

Table 1. Life cycle method

Called the first time an instance of your widget is added to the home screen.

Called once the last instance of your widget is removed from the home screen.

Called for every update of the widget. Contains the ids of appWidgetIds for which an update is needed. Note that this may be all of the AppWidget instances for this provider, or just a subset of them, as stated in the method’s JavaDoc. For example, if more than one widget is added to the home screen, only the last one changes (until reinstall).

Widget instance is removed from the home screen.

3.4. Receiver and asynchronous processing

A widget has the same runtime restrictions as a normal broadcast receiver, i.e., it has only 5 seconds to finish its processing.

A receive (widget) should therefore perform time consuming operations in a service and perform the update of the widgets from the service.

4. Widget updates

A widget gets its data on a periodic timetable. There are two methods to update a widget, one is based on an XML configuration file and the other is based on the Android AlarmManager service.

In the widget configuration file you can specify a fixed update interval. The system will wake up after this time interval and call your broadcast receiver to update the widget. The smallest update interval is 1800000 milliseconds (30 minutes).

The AlarmManager allows you to be more resource efficient and to have a higher frequency of updates. To use this approach, you define a service and schedule this service via the AlarmManager regularly. This service updates the widget.

Please note that a higher update frequency will wake up the phone from the energy safe mode. As a result your widget consumes more energy.

5. Exercise: widget with fixed update interval

5.1. Target

In the following tutorial you create a widget which displays a random number. This random number is updated every 30 minutes. You also register an OnClickListener so that the widgets updates once the user clicks on it.

The resulting widget will look like the following.

5.2. Create project and widget implementation

Create a new Android project called de.vogella.android.widget.example with an activity in the package de.vogella.android.widget.example .

Create a new file myshape.xml in the /res/drawable_ folder. This file defines the drawable used as background in the widget.

Define the following widget_layout.xml file under the res/layout_ folder.

Create a new resource file called widget_info.xml via right click on the res folder and by selecting New Android resource file .

Create the following receiver class which is called during updates.

Open the AndroidManifest.xml and register your widget similar to the following listing.

This attribute specifies that the AppWidgetProvider accepts the ACTION_APPWIDGET_UPDATE broadcast and specifies the metadata for the widget.

5.3. Validate

Deploy your application on your Android device. Once your application has been deployed use the Android launcher to install your new widget on the home screen and test it.

6. Collection View Widgets

Collection view widgets add support for the usage of the ListView , StackView and GridView classes in widgets.

For collection view widgets you need two layout files, one for the widget and one for each item in the widget collection.

The widget items are filled by an instance of the RemoteViewsFactory factory class.

This factory class is provided by an Android service which extends the RemoteViewsService class. This service requires the android.permission.BIND_REMOTEVIEWS permission.

To connect your views with the service, you use your onUpdate() method in your widget implementation.

You define an intent pointing to the service and use the setRemoteAdapter method on the RemoteViews class.

7. Enabling a app widget for the lock Screen

Since Android 4.2, it is possible to add home screen app widgets to the lock screen of an Android device. To enable your widget for the look screen you need to add keyguard category in the android:widgetCategory attribute in the AppWidgetProviderInfo XML file. The following code shows an example.

In this example you declare a widget to support both — the home and the lock screens. If you recompile and launch your application now, you will be able to add the widget to the lock screen already.

You can also detect a widget category at runtime. For this, in the AppWidgetProvider.onUpdate() method, you can check for the category option of a widget with the following code.

Using this technique you can decide at runtime whether the widgets your application provides, will look differently, when they are hosted on the lock screen.

Similarly to how you used the android:initialLayout attribute for defining an initial layout for home screen widgets, you can use a new android:initialKeyguardLayout attribute for the lock screen in the AppWidgetProviderInfo XML file. This layout will appear immediately after a widget is added and will be replaced by the real layout once the widget is initialized.

8. Exercise: Update widget via a service

The following will demonstrate the usage of a service to update the widget.

Create the following UpdateWidgetService class in your project.

Add this class as a Service to your AndroidManifest.xml file.

Change MyWidgetProvider to the following. It will now only construct the service and start it.

Once called, this service will update all widgets. You can click on one of the widgets to update all widgets.

Источник

Оцените статью
Method Description