先来看看效果.(代码是在GitHub上下载下来的)
https://github.com/cstew/AppWidget.git
运行效果如下.
但是需要注意的是.要想显示AppWidget你得在桌面长按住。这样会弹出一个选项框.
选择Widget然后添加你的应用名.
1.首先你得要添加显示的ui.xml
注意要添加的文件路径。看xml的话大概能的看得出来了.
2.要设置一个广播来通知显示.Intet-filter里是UPDATE那么更新的时候就会发送到该广播,
3.监听AppWidgetProvider
下面有一大堆代码.但这里用到的主要只是点是RemoteView与PendingIntent.
因为AppWidget跟应用的线程不一样.所以为了在其他线程里绘制UI所以需要使用到
RemoteView
public class
AdvancedWidgetAppProvider extends AppWidgetProvider {
private static final String SWITCH_ACTION_FAR = "com.bignerdranch.android.widgetapp.AdvancedWidgetAppProvider.switchActionFar";
private static final String SWITCH_ACTION_CLOSE = "com.bignerdranch.android.widgetapp.AdvancedWidgetAppProvider.switchActionClose";
@Override
public void onReceive(Context context, Intent intent) {
String action =
intent.getAction();
if (SWITCH_ACTION_FAR.equals(action)
|| SWITCH_ACTION_CLOSE.equals(action)) {
AppWidgetManager
manager = AppWidgetManager.getInstance(context);
int appWidgetId =
intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
RemoteViews
views = new
RemoteViews(context.getPackageName(), R.layout.widget_advanced_layout);
boolean isFar = SWITCH_ACTION_FAR.equals(action);
views.setImageViewResource(R.id.widget_image, isFar?
R.drawable.brian_the_human : R.drawable.brian_up_close);
manager.partiallyUpdateAppWidget(appWidgetId,
views);
}
super.onReceive(context,
intent);
}
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int n = appWidgetIds.length;
for (int i = 0; i < n; i++) {
int appWidgetId =
appWidgetIds[i];
RemoteViews views = new
RemoteViews(context.getPackageName(), R.layout.widget_advanced_layout);
views.setOnClickPendingIntent(R.id.widget_far_button,
generatePendingIntent(context, SWITCH_ACTION_FAR, appWidgetId));
views.setOnClickPendingIntent(R.id.widget_close_button,
generatePendingIntent(context, SWITCH_ACTION_CLOSE, appWidgetId));
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
private PendingIntent
generatePendingIntent(Context context, String action, int appWidgetId) {
Intent switchIntent
= new
Intent(context, AdvancedWidgetAppProvider.class);
switchIntent.setAction(action);
switchIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
return PendingIntent.getBroadcast(context,
0, switchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
没有评论:
发表评论