Android widgets what are they

Android Widgets

This article covers a complete tutorial about how to add Android Widgets into your application. Understanding the logic and depth diving into Android Widgets with 4 sample projects. You will learn how to code your widget from scratch to advanced. Afterward, at the end article we are going to see what the common mistakes.

Before getting started, what is an Android Widget?

Widgets are an essential aspect of home screen customization. You can imagine them as “at-a-glance” views of an app’s most important data and functionality that is accessible right from the user’s home screen.

You can also read this article in Chinese(中文) .

So what we are going to achieved?

  • Widget Creation Steps with a basic example (‘Simple Widget’ — Opening a website on widget clicked)
  • Broadcast Widget Example (‘Broadcast Widget’ — Counting clicks on widget)
  • Configurable Widget Example (‘Configurable Widget’ — Getting data before creation and using the data when it’s clicked)
  • Updating Widget by a Service (‘Updating Widget’ — Updating every minute brings random numbers on widget)

Widget Creation Steps :

  1. create layout for the widget.
  2. create XML for defining the widget properties.
  3. create class for the widget actions.
  4. add all these to AndroidManifest.xml file.

With that knowledge, our first example is a widget that will be opening a website on widget clicks.

Step 1: Creating a very simple layout for a widget.

This layout is displayed as a widget on user’s home-screen.

Step 2: create an XML that defines widget properties.

In res folder create a new XML folder.

Quick look for these properties

  • initialLayout: reference for the widget layout(that we already created).
  • minHeight and minWidth: Every 60dp means 1 cell in android home-screen. For this example, the widget takes min 1×1 cell(s).
  • previewImage: The image that will be shown on android’s widget select screen. We can not draw a layout for preview. We have to set an image.
  • resizeMode: The configuration for resizing the widget.
  • updatePeriodMillis: The widget’s update method is called when the specified time is reached in a millisecond.
  • widgetCategory: home_screen or keyguard.

Android Studio has an amazing interface for creating widgets.

Step 3: Create a class for the widget lifecycle.

AppWidgetProvider extends BroadcastReceiver. SimpleAppWidget is indirectly a child of BroadcastReceiver. So our widget class is a receiver class.

Step 4: Adding into AndroidManifest as a receiver.

Yay! You have implemented a widget for your app 🙂

Let’s take it to the next level.

RemoteView

Let’s continue with learning RemoteView.

A class that describes a view hierarchy that can be displayed in another process. The hierarchy is inflated from a layout resource file, and this class provides some basic operations for modifying the content of the inflated hierarchy.

RemoteView supports only these layouts:

RemoteView supports only these views:

If you use another view, RemoteView has no operation for the view.

Let’s add some codes to our widget class.

As we can see there is an override method onUpdate which is called every updatePeriodMillis has reached.

This example is basic and fast dive for the widget.

Understanding Override Methods

Before going to the next example, we need to understand widget classes that override the following methods.

  • onUpdate(): This is called to update the App Widget at intervals defined by the updatePeriodMillis attribute.
  • onAppWidgetOptionsChanged() : This is called when the widget is first placed and also whenever the widget is resized.
  • onDeleted(Context, int[]): This is called every time an App Widget is deleted from the App Widget host.
  • onEnabled(Context): This is called when an instance the App Widget is created for the first time.
  • onDisabled(Context): This is called when the last instance of your App Widget is deleted from the App Widget host.
  • onReceive(Context, Intent): This is called for every broadcast and before each of the above callback methods.

Confused? No problem. Below video shows you when these methods will calls.

Let’s see these fellas in action.

This knowledge gives you full control of on your widget.

Broadcast Widget

We have learned all steps of widget creation. We will not be repeating these steps.

Every click on the widget will send a broadcast and onReceive increases the counter.

In previous example we used .getActivity() , this time we are going to use .getBroadcast() .

BroadcastWidget is our widget class. Let’s see what is inside?

Using static fields with widgets is not recommended. But I am trying to make the example as simple as possible. You can use SharedPreferences instead of static fields.

Читайте также:  Веселая ферма 4pda android

Here is the result.

You can send whatever you want with broadcast and you can catch the broadcast wherever you want.

Configurable Widgets

Some widgets can be configurable at creation. In this example, we are getting a link from the user and whenever it’s clicked we open this link on the browser.

Create ConfigureActivity for user configuration.

The Basic layout for activity.

In activity’s onCreate method, the first thing we do is setting setResult(RESULT_CANCELED) . Why? Android triggers the configure activity that belongs to your widget and awaits result data. If the user did not configure as we expected, let’s say she pressed back button without entering a data, we don’t need to create a widget.

The last thing we do is modify the XML of the widget. With that modification, the Android Operating System will know this widget has configuration activity. So before creating the widget, it will trigger the activity.

As you notice we didn’t talk about widget class yet. We do not need to add any code for widget class because all actions done by ConfigurableWidgetConfigureActivity . But we have to create anyway.

Here is the result.

Updated By a Service Widget Example

This project will generate random numbers in every minute and displays it on a widget. First of all, we need a service to generate random numbers.

And we have to add this to AndroidManifest.

Service does not start by itself. We need to start the service(in every minute for this example).

But why we do not just use ‘ updatePeriodMillis ’?

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. If you don’t update more than once per hour, this probably won’t cause significant problems for the battery life. If, however, you need to update more frequently and/or you do not need to update while the device is asleep, then you can instead perform updates based on an alarm that will not wake the device. To do so, set an alarm with an Intent that your AppWidgetProvider receives, using the AlarmManager . Set the alarm type to either ELAPSED_REALTIME or RTC , which will only deliver the alarm when the device is awake. Then set updatePeriodMillis to zero ( «0» ).

In Previous examples, we used .getActivity() and .getBroadcast() methods. This time we are going to use .getService() method.

The minimum interval time is 60000 millis for AlarmManager. If you need to call your service less than 60 sec with an alarm manager, there are some workarounds like this. But I have to warn you, this action drains the battery and makes users delete your app.

Here is the result. I cropped the video to not keep you wait 2 minutes.

Common questions / mistakes about Widgets

Question:

Programmatically update widget from activity or service

Answer:

Simple, you have to reach your widgets. Afterwards send broadcast that has information about your widgets. See the code below,

Question:

Every widget instances not doing their job? or doing same job?

Answer:

PendingIntent operations(.getActivity, .getBroadcast etc.) need a parameter requestCode for identification.

You have to set the requestCode with your appW idgetId. With that way, your pending intent becomes unique. Every instance of your widget will use their PendingIntent.

More about Widgets

How the material design should be on widget?

Read further? Helpful links

If you made it at this far, personally thank you for reading. Here is the promised Github link includes whole projects in this article. And feel free for pull requests.

To help others to reach the article don’t forget to recommend 💚 . It means a lot to me.

Источник

15 best Android Widgets for your home screen

You may notice a distinct lack of clock widgets on this list. We have a whole separate list for the best clock widgets here!

1Weather

Price: Free / $1.99

1Weather is arguably one of the best weather apps available. Its Android widgets aren’t half bad either. It invokes the old style “flip clock and weather” style that used to adorn HTC Sense devices and it’s configurable. Clicking on the clock portion takes you to your alarm app. Clicking on the weather portion takes you to 1Weather’s main interface. There are also weather-only widgets that deliver a good amount of information. It’s free to use. All the paid version does is remove ads. AccuWeather is another good weather app with a decent widget if you 1Weather isn’t doing it for you.

Battery Widget Reborn

Price: Free / $3.49

Battery Widget Reborn among the best Android widgets for battery meters. It provides a single, circular battery gauge widget. You can change the color and size to match your theme and home screen layout. The app itself also comes with battery information, shortcuts to things like WiFi and Bluetooth settings, and it even gives you charts to show more detailed battery activity. It’s nothing overly complicated. However, in an era where smartphone makers still don’t always let you enable the percentage in the status bar, apps like Battery Widget Reborn are still useful.

Читайте также:  Web desktop android app

Calendar Widget by Home Agenda

Price: $1.99

Calendar Widget by Home Agenda is an excellent calendar widget for your mobile phone. You can theme the widgets to your liking. There is an option to download and install themes by other people as well. Some other options include a weather function, hiding various events, hiding declined events, and even changing the colors of certain calendar labels. It works best with Google Calendar. Recent updates also added way better performance improvements. The app runs for $1.99 but has no additional ads or in-app purchases.

Calendar Widget: Month and Agenda

Price: Free / Up to $3.49

Calendar Widget: Month and Agenda are two Android widgets from Candl Apps. The first one is a fairly standard and minimal calendar widget. It includes over 90 themes, a minimal layout, support for Google Calendar, and it shows your various upcoming engagements. It looks and feels pretty good, although power users may need something a little more powerful. Calendar Widget: Agenda is much like the other Calendar Widget app, but with more options. You can create widgets specifically for your agenda as well as any other upcoming events you might have. Both widgets are free to use with a limited number of themes. You can buy more as in-app purchases.

Chronus Information Widgets

Price: Free / $2.99

Chronus Information Widgets is a fairly decent set of widgets for your home screen. It includes predominately clock and weather widgets with some news widgets and some other stuff as well. Most of the widgets are fairly customizable and can work with most home screens. There is also Wear OS support if you need that. The pro version adds some little extras like Google Fit support and support for Reddit in the news widgets. It’s a serviceable option that should work well for most people.

Google Keep Notes

Price: Free

Google Keep Notes is a simple and effective note taking application. With it, you can make text notes, list notes, and even voice notes. It also gives you the option to share notes with others for collaboration. There are a bunch of extra little hidden features throughout the app as well. It also comes with a simple set of Android widgets that gives you the ability to create notes quickly. They range in size from simple to more complex depending on your needs. That’s essentially all you need when it comes widgets for note taking apps. It’s completely free to use. You can also access notes on Google Drive using any web browser.

IFTTT

Price: Free

IFTTT is one of the most powerful apps out there. You use it to create automated tasks that your phone completes on its own. One of its many features is a button widget that activates a command when pressed. For instance, you can use it to turn your Hue lights on or off, automatically text someone that you’re on your way home, or pretty much whatever you want. There’s a bit of a learning curve, but it’s a fun way to automate a lot of tedious tasks. The widget itself is rather simple. However, it’s easily one of the most versatile Android widgets out there.

KWGT Kustom Widget Maker

Price: Free / $4.49

KWGT is one of a few make-your-own Android widgets. It employs a WYSIWYG editor. That makes it a bit easier than one would think. You can have it do a variety of things and make it look almost however you want. It also includes support for Zooper, Tasker, and other apps. Some of the things you can have it display include system info (CPU speed, network stats, etc), time, battery, date, countdowns, traffic info, next alarm, location, and more. It’s fairly powerful, but it’s more work than you’d get with most widgets. It is, to our knowledge, one of the very few custom widget apps still in active development. Zooper is another option, but it doesn’t get updates anymore. Buzz Widget is no longer available as of February 2019. That basically leaves KWGT and UCCW as the top dogs. This app is also free via Google Play Pass if you use it.

Overdrop

Price: Free

Ovedrop is one of the newer Android widgets on the list. It’s technically just a weather app, but it has some surprisingly decent widgets for the home screen. That includes a forecast widget with up to five days, a card style layout that includes the date and battery percentage, and your basic current forecast weather widget. It utilizes Dark Sky as its weather provider and has some basic weather app features as well. The app itself has a dark mode that we quite like and the UI is lovely. There isn’t a lot wrong with this one to be honest, and it’s a great option if you want some good-looking weather widgets.

Читайте также:  Dead cells андроид гайды

Tasker

Price: $2.99

Tasker is one of the most powerful apps ever made. It’s also one of the most complex and complicated. You can use this to make your phone do pretty much whatever you want. The downside is that it’s going to take you a while to get there. It includes over 200 actions on its own with tons of plugins that add additional functionality. A lot of other apps also have Tasker support to add to the number of things it can do. Once you make whatever it is you’re going to make, it doesn’t take long from there to turn it into a widget. That makes this one of the most powerful Android widgets you can get. This one is also free with Google Play Pass if you use the service.

TickTick

Price: Free / $27.99 per year

TickTick is one of the best to-do list apps on mobile. It has a simple UI, plenty of organization and customization options, and most of its features are completely free. It employs a list style with simple controls. You can use it for remembering your work tasks or your grocery list. You can even share lists with friends or family for collaboration. It also includes reminders (up to two per task) for free, unlike many to-do list apps. TickTick is flexible like that. The app also comes with a bunch of widget options. That includes a minimal, but functional calendar widget and widgets specifically for your to-do lists. You can also sort tasks for things like date due. The $27.99 per year version subscription isn’t necessary unless you really need more than two reminders per event.

Time Until

Price: Free / Up to $2.99

Time Until is a fun little app with some decent little widgets. It’s a countdown timer app. You use it for things like holidays, birthdays, special events, or whatever you would need a countdown for. You can set it down to the second, minute, hour, day, week, or month. It even takes working days into account. The widgets are minimal, but effective. You can choose the background from your own images if you want to or just use a solid color. They also come in different sizes for your convenience. It’s not the most popular use of a widget, but Time Until is easily one of the best countdown timer widgets we’ve seen.

Todoist

Price: Free / $28.99 per year

Todoist has some of the most gorgeous widgets of any to-do list app. The whole app looks really good, actually. The developers do a great job incorporating bright colors, full Material Design, and it’s still relatively easy to use. The free version comes with most of the basic features, including tasks, due dates, and some organizational features. Going premium adds things like reminders and other power user features. In terms of looks and Android widgets, this one is as good as it gets in the genre. Widgets are like the app. By that, we mean they’re colorful, easy to use, and powerful. We also quite appreciate the cross-platform capabilities of Todoist. It and TickTick are easily the top two best to-do list apps and as it turns out, they both have really good widgets.

Price: Free / $4.99

UCCW is the second excellent make-your-own-widget app on this list along with KWGT. It was an abandoned project for a while, but started getting updates again. It’s not better than ever. The app is a WYSIWYG (what you see is what you get) editor. You create your widget, add-in functions, and then add it to the home screen. You can also download and import other people’s widget designs. There is even an option to export your designs as an APK file and upload it to Google Play if you want to. It takes a bit of work to get everything just right, but it’s an excellent choice once you get everything the way you want.

YoWindow Weather

Price: Free / $9.99

YoWindow Weather is one of the best weather apps hands down. However, it also comes with some decent widgets. Your options include a 14-day forecast, a clock and weather widget, a weekly weather forecast, and a widget specifically for today’s weather. It’s not as customizable as some, but the weather app is top notch and the widgets definitely work most of the time. The weather information is solid, but you really use this app to look at it because it looks really good.

If we missed any of the best Android widgets, tell us about them in the comments! To see all of our most recent app lists, click here!

Источник

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