Android Widgtets Tutorial

Advertisements


A widget is a small gadget or control of your android application placed on the home screen. Widgets can be very handy as they allow you to put your favourite applications on your homescreen in order to quickly access them. You have probably seen some common widgets , such as music widget , weather widget , clock widget e.t.c

Widgets could be of many types such as information widgets, collection widgets, control widgets and hybrid widgets. Android provides us a complete framework to develop our own widgets.

Widget - XML file

In order to create an application widget , first thing you need is AppWidgetProviderInfo object, which you will define in a seperate widget XML file. In order to do that, right click on your project and create a new folder called xml. Now right click on the newly created folder and create a new XML file. The resource type of the XML file should be set to AppWidgetProvider. In the xml file, define some properties which are as follows:

<appwidget-provider 
   xmlns:android="http://schemas.android.com/apk/res/android" 
   android:minWidth="146dp" 
   android:updatePeriodMillis="0" 
   android:minHeight="146dp" 
   android:initialLayout="@layout/activity_main">
</appwidget-provider>

Widget - Layout file

Now you have to define the layout of your widget in your default XML file. You can drag components to generate auto xml.

Widget - Java file

After defining layout , now create a new JAVA file or use existing one , and extend it with AppWidgetProvider class and override its update method as follows.

In the update method , you have to define the object of two classes which are PendingIntent and RemoteViews. Its syntax is:

PendingIntent pending = PendingIntent.getActivity(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.activity_main);

In the end you have to call an update method updateAppWidget() of the AppWidgetManager class. Its syntax is:

appWidgetManager.updateAppWidget(currentWidgetId,views);		

A part from the updateAppWidget method , there are other methods defined in this class to manipulate widgets. They are as follows:

Sr.NoMethod & Description
1onDeleted(Context context, int[] appWidgetIds)
This is called when an instance of AppWidgetProvider is deleted.
2onDisabled(Context context)
This is called when the last instance of AppWidgetProvider is deleted
3onEnabled(Context context)
This is called when an instance of AppWidgetProvider is created.
4onReceive(Context context, Intent intent)
It is used to dispatch calls to the various methods of the class

Widget - Manifest file

You also have to declare the AppWidgetProvider class in your manifest file as follows:

<receiver android:name="ExampleAppWidgetProvider" >
   <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>

Example

Here is an example demonstrating the use of appliction Widget. It creates a basic widget applications that will open this current website in the browser.

To experiment with this example , you need to run this on an actual device on which intenet is running.

StepsDescription
1You will use Eclipse IDE to create an Android application and name it as Widget under a package com.example.widget. While creating this project, make sure you Target SDK and Compile With at the latest version of Android SDK to use higher levels of APIs.
2Modify src/MainActivity.java file to add widget code.
3Modify the res/layout/activity_main to add respective XML components
4Create a new folder and xml file under res/xml/mywidget.xml to add respective XML components
5Modify the res/values/string.xml to add necessary string components
6Modify the AndroidManifest.xml to add the necessary permissions
7Run the application and choose a running android device and install the application on it and verify the results.

Following is the content of the modifed main activity file src/om.example.widget/MainActivity.java.

package com.example.widget;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.webkit.WebView.FindListener;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.Toast;

public class MainActivity extends AppWidgetProvider{

   @Override
   public void onUpdate(Context context, AppWidgetManager appWidgetManager,
   int[] appWidgetIds) {
      for(int i=0; i<appWidgetIds.length; i++){
      int currentWidgetId = appWidgetIds[i];
      String url = "http://www.tutorialspoint.com";
      Intent intent = new Intent(Intent.ACTION_VIEW);
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      intent.setData(Uri.parse(url));
      PendingIntent pending = PendingIntent.getActivity(context, 0,
      intent, 0);
      RemoteViews views = new RemoteViews(context.getPackageName(),
      R.layout.activity_main);
      views.setOnClickPendingIntent(R.id.button1, pending);
      appWidgetManager.updateAppWidget(currentWidgetId,views);
      Toast.makeText(context, "widget added", Toast.LENGTH_SHORT).show();	
      }
   }	
}

Following is the modified content of the xml res/layout/activity_main.xml.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:gravity="top"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" >

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:layout_alignParentTop="true"
      android:text="@string/website"
      android:textAppearance="?android:attr/textAppearanceMedium" />

   <Button
      android:id="@+id/button1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignLeft="@+id/textView1"
      android:layout_below="@+id/textView1"
      android:layout_marginLeft="18dp"
      android:text="@string/app_name" />

</RelativeLayout>

Following is the content of the res/xml/mywidget.xml.

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider 
   xmlns:android="http://schemas.android.com/apk/res/android" 
   android:minWidth="146dp" 
   android:updatePeriodMillis="0" 
   android:minHeight="146dp" 
   android:initialLayout="@layout/activity_main">
</appwidget-provider>

Following is the content of the res/values/string.xml.

<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">Widget</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="website">TutorialsPoint.com</string>

</resources>

Following is the content of AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.widget"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
      android:minSdkVersion="10"
      android:targetSdkVersion="17" />
   <uses-permission android:name="android.permission.INTERNET"/>

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
         <receiver android:name="MainActivity" >
            <intent-filter>
               <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
            <meta-data android:name="android.appwidget.provider"
               android:resource="@xml/mywidget" />
         </receiver>
   </application>
</manifest>

Let's try to run your Widget application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Eclipse, open one of your project's activity files and click Run Eclipse Run Icon icon from the toolbar. Before starting your application, Eclipse will display following window to select an option where you want to run your Android application.

Anroid Widget Tutorial

Select your mobile device as an option and then check your mobile device which will display your default screen:

Go to your widget section and add your created widget to the dsktop or homescreen. It would look something like this:

Anroid Widget Tutorial

Now just tap on the widget button that appears , to launch the browser. But before that please make sure that you are connected to the internet. After pressing the button , the following screen would appear:

Anroid Widget Tutorial

Note. By just changing the url in the java file , your widget will open your desired website in the browser.



Advertisements
Advertisements