AppWidget的范例
首先在res文件夹下新建一目录,命名为xml。然后在这个目录下新建一个xml文件(如下图):
example_appwidget.xml的内容如下:
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:initialLayout="@layout/appwidget_layout"
android:minHeight="72dp"
android:minWidth="294dp"
android:updatePeriodMillis="86400000" />
然后创建一个类:ExampleAppWidget。ExampleAppWidget.java如下:
package com.kevin.appwidget.test1;
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.widget.RemoteViews;
public class ExampleAppWidget extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
Log.v("tag", "------------------------>onUpdate()");
Intent intent = new Intent(context, AppWidget01Activity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
intent, 0);
RemoteViews view = new RemoteViews(context.getPackageName(),
R.layout.appwidget_layout);
view.setOnClickPendingIntent(R.id.btnStartActivity, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, view);
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
Log.v("tag", "------------------------>onDeleted()");
}
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
Log.v("tag", "------------------------>onEnabled()");
}
@Override
public void onDisabled(Context context) {
super.onDisabled(context);
Log.v("tag", "------------------------>onDisabled()");
}
}
最后配置Manifest.xml文件。如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kevin.appwidget.test1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".AppWidget01Activity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".ExampleAppWidget" >
<intent-filter >
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/example_appwidget" />
</receiver>
</application>
</manifest>
这样就可以看到appwidget的效果了。