miércoles, 19 de septiembre de 2012

Crear Widget

Cuando creamos una app nos puede interesar darle al usuario la posibilidad de añadir un widget en el escritorio como, por ejemplo, Twitter o Foursquare.

Para ello podemos usar el siguiente código. En ello podemos ver, cómo:

1.- Se crea la clase Widget que usa AppWidgetProvider.
2.- Se implementa el método onUpdate que se llama al añadir el Widget en el escritorio. El método onReceive para capturar los eventos que se producen (por ejemplo, pulsado de un botón).
3.- Se gestiona el AndroidManifest.xml
4.- Se crea la interfaz gestora del widget (el gestor). widgetproviderinfo.xml
5.- En widgetproviderinfo.xml podemos ver los campos android:minResizeWidth,
    android:minResizeHeight y android:resizeMode que nos permiten cambiar el tamaño de los widgets. 

AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.blogwidgetexample"
    android:installLocation="internalOnly"
    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" >
        <receiver android:name=".BlogWidgetExample" >
            <intent-filter>
             <!-- Se usa para gestionar los eventos de los botones-->
                <action android:name="com.example.blogwidgetexample.ACTION_WIDGET_SHOW" />
                <action android:name="com.example.blogwidgetexample.ACTION_WIDGET_HIDDEN" />
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widgetproviderinfo" />
        </receiver>
    </application>
</manifest>

Creamos en res/xml
widgetproviderinfo.xml
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:initialLayout="@layout/activity_blog_widget_example"
    android:minHeight="130dp"
    android:minWidth="170dp"
    android:minResizeWidth="30dp"
    android:minResizeHeight="30dp"
    android:resizeMode="horizontal|vertical" />

BlogWidgetExample.java
package com.example.blogwidgetexample;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

public class BlogWidgetExample extends AppWidgetProvider {
public static final String WIDGETTAG = "WidgetMood";
// our actions for our buttons
public static String ACTION_WIDGET_HIDDEN = "ActionReceiverHidden";
public static String ACTION_WIDGET_SHOW = "ActionReceiverShow";

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);

RemoteViews remoteViews;

remoteViews = new RemoteViews(context.getPackageName(),
R.layout.activity_blog_widget_example);
remoteViews.setTextViewText(R.id.clicked, "Button not clicked");

// Button hidden
Intent active = new Intent(context, BlogWidgetExample.class);
active.setAction(ACTION_WIDGET_HIDDEN);
PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context,
0, active, 0);
remoteViews.setOnClickPendingIntent(R.id.button_hidden,
actionPendingIntent);

// Button show
active = new Intent(context, BlogWidgetExample.class);
active.setAction(ACTION_WIDGET_SHOW);
actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
remoteViews.setOnClickPendingIntent(R.id.button_show,
actionPendingIntent);

appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}

@Override
public void onReceive(Context context, Intent intent) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.activity_blog_widget_example);

if (intent.getAction().equals(ACTION_WIDGET_HIDDEN)) {
Log.i("onReceive", ACTION_WIDGET_HIDDEN);
Toast.makeText(context, ACTION_WIDGET_HIDDEN, Toast.LENGTH_SHORT)
.show();
remoteViews.setTextViewText(R.id.clicked, ACTION_WIDGET_HIDDEN);

} else if (intent.getAction().equals(ACTION_WIDGET_SHOW)) {
Log.i("onReceive", ACTION_WIDGET_SHOW);
Toast.makeText(context, ACTION_WIDGET_SHOW, Toast.LENGTH_SHORT)
.show();
remoteViews.setTextViewText(R.id.clicked, ACTION_WIDGET_SHOW);

}
ComponentName cn = new ComponentName(context, BlogWidgetExample.class);
AppWidgetManager.getInstance(context).updateAppWidget(cn, remoteViews);
super.onReceive(context, intent);

}
}

activity_blog_widget_example.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/white" >
    <TextView
        android:id="@+id/clicked"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dip"
        android:padding="@dimen/padding_medium"
        android:text="@string/hello_world"
        android:textColor="@android:color/black"
        tools:context=".BlogWidgetExample" />
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/clicked" >
        <Button
            android:id="@+id/button_hidden"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hidden"
            android:textColor="@android:color/black" />
        <Button
            android:id="@+id/button_show"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Show"
            android:textColor="@android:color/black" />
    </LinearLayout>
</RelativeLayout>


A continuación podemos ver una imagen de nuestro Widget:




It works!
Roger Sala,

1 comentario: