Widget in Android example and Tutorial


Introduction
              Widget in Android are small applications that are embedded into other applications like Home screen in Android. An application component that is able to hold other App Widgets is called an App Widget host.
A widget runs as part of the process of its host, i.e., home screen and users can access them often to see important updates without opening the actual application.
               Creating android app widget is quite simple, and this is explained clearly in this tutorial. Lets see how to open messaging app while clicking an widget icon in the home screen, this is going to be our android widget example. Now lets go ahead.., also take a look at the project structure for better understanding..

Add Widget Project Structure

Step 1 : Adding the AppWidgetProviderInfo
               AppWidgetProviderInfo is nothing but a XML file containing the properties of widget like height,width etc., One of the important property is android:updatePeriodMillis,  which defines how often the widget is updated in milliseconds. Below is our AppWidgetProviderInfo file. Place the file under res/xml/mywidget.xml

mywidget.xml

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

Step 2 : Create App Widget Layout
                 Layout files defines the widget layout. For our android widget example, we are going to display a message icon as shown below. Include the sms_icon.png file in corresponding drawable folders.

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: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" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/sms_icon" />

</RelativeLayout>

Step 3 : Implement AppWidgetProvider class
              Before we get into the actual code of android widget, let me explain some of the classes and methods used here,

Pending Intent
                It  is a token that you give to a foreign application which allows the foreign application to use your application’s permissions to execute a predefined piece of code. In our android widget example, foreign application is nothing but Home Screen AppWidgetManager and the code to be executed is the Intent that will open messaging app.
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("sms:"));
PendingIntent pending = PendingIntent.getActivity(context, 0,intent, 0);

RemoteViews
               Widget use RemoteViews to create their user interface. A RemoteView can be executed by another process with the same permissions as the original application. 
RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.activity_main);

Finally, we need to update our widget with remoteViews
appWidgetManager.updateAppWidget(currentWidgetId, views);

To summarize, create a java class(nothing but our MainActivity.java file) and extend AppWidgetProvider. In the onUpdate() method of the widget, write the respective code of the widget, where we need to declare Intent to invoke messaging app  and use Pending Intent to perform respective action.

MainActivity.java

import android.net.Uri;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;

public class MainActivity extends AppWidgetProvider {

public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
for (int i = 0; i < appWidgetIds.length; i++) {
int currentWidgetId = appWidgetIds[i];
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("sms:"));
PendingIntent pending = PendingIntent.getActivity(context, 0,
intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.activity_main);
views.setOnClickPendingIntent(R.id.imageView1, pending);
appWidgetManager.updateAppWidget(currentWidgetId, views);
}
}
}

Step 4 :Include AppWidgetProvider permission AndroidManifest file

We need to declare AppWidgetProvider class in  AndroidManiest.xml
        <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>

AndroidManifest.xml

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <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>

Now run your application and go to Widgets screen you should be able to see our Android widget app as shown below: Hope this tutorial provides a clean understanding on android widget.


Now add this your home screen and open the widget, 




Source Code of this application




Reactions:

0 comments :

Post a Comment