Android App Widget with Configuration Activity

October 12, 2012
By

Configuration activity is an activity which will be launched automatically by the widget host at the time of widget creation. This activity facilitates users to do the available settings for the widget.

The configuration activity of the widget should be specified in the widget meta data file (see the file :  res/xml/widget_info.xml)  using android:configure attribute.

In this article, we will create an app widget with a configuration activity to change its background color. In the configuration activity, the color is picked up by AmbilWarna color picker library which we have discussed in the article titled “Android Color Picker application using AmbilWarna Color Picker Library” .

This application is developed in Eclipse (4.2.0) with ADT plugin (20.0.3) and Android SDK (R20.0.3).


1. Setup AmbilWarna color picker library in Eclipse IDE

Please see the article titled “Setting up AmbilWarna Library for Color Picker in Android“, for setting up the AmbilWarna library for Eclipse 4.2.0


2. Create an Android application project namely “AppWidgetClockConfiguration”

Create a new Android application project namely "AppWidgetClockConfiguration"

Figure 1 : Create a new Android application project namely "AppWidgetClockConfiguration"


3. Design application launcher icon

Design Application launcher icon

Figure 2 : Design Application launcher icon


4. Create a blank activity to define the class MainActivity

Create a blank activity

Figure 3 : Create a blank activity


5. Enter MainActivity details

Enter MainActivity Details

Figure 4 : Enter MainActivity Details


6. Delete Android’s backward support library from this project

By default Eclipse ( 4.2.0) adds Android Support Library to  Android application project. For this application, we don’t need to use this support library. So the library file libs/android-support-v4.jar may be removed manually via ProjectExplorer by simply right click on the file and then clicking the menu item “delete”.


7. Add AmbilWarna Color Picker library to this project

  • Open Project Explorer
  • Right click the project
  • Open Properties
  • Select “Android” tab from the Properties Window
  • Then the given below screen will be appeared
  • Using Add button, add the AmbilWarna library to this project
Add AmbilWarna Color Picker library to this project

Figure 5 : Add AmbilWarna Color Picker library to this project


8. Update the file res/values/strings.xml


<resources>
    <string name="app_name">AppWidgetClockConfiguration</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">Widget Demo</string>
    <string name="str_btn_set_color">Set Color</string>
    <string name="str_tv_widget">Android Widget Configuration Activity Demo</string>
</resources>


9. Update the layout of the MainActivity in the file 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" >

    <TextView
        android:id="@+id/tv_widget"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/str_tv_widget" />
</RelativeLayout>

10. Create a new file res/values/dimens.xml to define the margin of the widget for pre Android 4.0 ( API Level 14 ) versions


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="widget_margin">8dp</dimen>
</resources>


11. Create a new file res/values-v14/dimens.xml to define the margin of the widget for Android 4.0 ( API Level 14 ) and its above versions


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="widget_margin">0dp</dimen>
</resources>


12. Create a layout for the widget in the file res/layout/widget_layout.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:padding="@dimen/widget_margin" >

    <AnalogClock
        android:id="@+id/widget_aclock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

</RelativeLayout>


13. Create a layout for the configuration activity in the file res/layout/configuration_activity.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" >

    <Button
        android:id="@+id/btn_set_color"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/str_btn_set_color" />

</RelativeLayout>


14. Define a class which extends AppWidgetProvider class to interface with the app widget in the file src/in/wptrafficanalyzer/appwidgetclockconfiguration/AnalogClockWidgetProvider.java


package in.wptrafficanalyzer.appwidgetclockconfiguration;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;

public class AnalogClockWidgetProvider extends AppWidgetProvider {

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {
        // Unused
    }
}


15. Define a configuration activity class in the file src/in/wptrafficanalyzer/appwidgetclockconfiguration/WidgetConfigurationActivity.java


package in.wptrafficanalyzer.appwidgetclockconfiguration;

import yuku.ambilwarna.AmbilWarnaDialog;
import yuku.ambilwarna.AmbilWarnaDialog.OnAmbilWarnaListener;
import android.app.Activity;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RemoteViews;

public class WidgetConfigurationActivity extends Activity{
    private int mAppWidgetId = 0 ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.configuration_activity);

        // Gettng the reference to the "Set Color" button
        Button btnSetColor = (Button) findViewById(R.id.btn_set_color);

        // Defining a click event listener for the button "Set Color"
        OnClickListener setColorClickedListener  = new OnClickListener() {

            @Override
            public void onClick(View v) {
                colorPicker();
            }
        };

        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {

            mAppWidgetId = extras.getInt(
                    AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
        }

        // Setting the click listener on the "Set Color" button
        btnSetColor.setOnClickListener(setColorClickedListener);
    }

    public void colorPicker() {

        //      initialColor is the initially-selected color to be shown in the rectangle on the left of the arrow.
        //      for example, 0xff000000 is black, 0xff0000ff is blue. Please be aware of the initial 0xff which is the alpha.
        AmbilWarnaDialog dialog = new AmbilWarnaDialog(this, 0xff0000ff, new OnAmbilWarnaListener() {

            // Executes, when user click Cancel button
            @Override
            public void onCancel(AmbilWarnaDialog dialog){
            }

            // Executes, when user click OK button
            @Override
            public void onOk(AmbilWarnaDialog dialog, int color) {
                // Create an Intent to launch WidgetConfigurationActivity screen
                Intent intent = new Intent(getBaseContext(), WidgetConfigurationActivity.class);

                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);

                // This is needed to make this intent different from its previous intents
                intent.setData(Uri.parse("tel:/"+ (int)System.currentTimeMillis()));

                // Creating a pending intent, which will be invoked when the user
                // clicks on the widget
                PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0,
                                                intent, PendingIntent.FLAG_UPDATE_CURRENT);

                // Getting an instance of WidgetManager
                AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getBaseContext());

                // Instantiating the class RemoteViews with widget_layout
                RemoteViews views = new RemoteViews(getBaseContext().getPackageName(), R.layout.widget_layout);

                // Setting the background color of the widget
                views.setInt(R.id.widget_aclock, "setBackgroundColor", color);

                //  Attach an on-click listener to the clock
                views.setOnClickPendingIntent(R.id.widget_aclock, pendingIntent);

                // Tell the AppWidgetManager to perform an update on the app widget
                appWidgetManager.updateAppWidget(mAppWidgetId, views);

                // Return RESULT_OK from this activity
                Intent resultValue = new Intent();
                resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
                setResult(RESULT_OK, resultValue);
                finish();
            }
        });
        dialog.show();
    }
}


16. Define meta data for the app widget in the file res/xml/widget_info.xml


<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="294dp"
    android:minHeight="72dp"
    android:initialLayout="@layout/widget_layout"
    android:updatePeriodMillis="0"
    android:configure="in.wptrafficanalyzer.appwidgetclockconfiguration.WidgetConfigurationActivity"
    android:resizeMode="horizontal|vertical">
</appwidget-provider>


17. Update the file AndroidManifest.xml


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.appwidgetclockconfiguration"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".WidgetConfigurationActivity">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>
            </intent-filter>
        </activity>

        <receiver android:name="AnalogClockWidgetProvider" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
            <meta-data android:name="android.appwidget.provider"
                android:resource="@xml/widget_info" />
        </receiver>
    </application>

</manifest>


18. Run the application

Choosing the Widget

Figure 6 : Choosing the Widget

Configuration Activity is automatically opened while creating the widget in the Home Screen

Figure 7 : Configuration Activity is automatically opened while creating the widget in the Home Screen

On clicking the "Set Color" button, AmbilWarna Color Picker Dialog is opened

Figure 8 : On clicking the "Set Color" button of configuration activity screen ( see figure 7 ) , AmbilWarna Color Picker Dialog is opened

The Widget is added to the Home Screen

Figure 9 : The Widget is added to the Home Screen


19. Download


20. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner