widget入门
widget就是android桌面小空间.
开发流程大概是:
1.在manifest中注册监听widget更新:
<receiver android:name="com.widget.WidgetProvider" android:label="@string/app_name" > <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_confige" />//配置信息 </receiver>
2.在res/下新建xml文件夹,在其下新建配置文件,名称为widget_confige(任意命)配置信息如下:
<?xml version="1.0" encoding="utf-8"?> <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:initialLayout="@layout/widget_layout" android:minHeight="72dp" android:minWidth="72dp" android:updatePeriodMillis="3000" > </appwidget-provider>
3.新建类继承appwidgetProvider类,重写onupdate方法:
package com.widget; import java.util.Calendar; import com.example.widgetdemo.R; 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.widget.RemoteViews; //主要继承这个类appwidgetProvider //onupdate方法 public class WidgetProvider extends AppWidgetProvider { private String[] Months = { "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月" }; @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub super.onReceive(context, intent); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // TODO Auto-generated method stub RemoteViews updateViews = buildUpdate(context); appWidgetManager.updateAppWidget(appWidgetIds, updateViews); super.onUpdate(context, appWidgetManager, appWidgetIds); } private RemoteViews buildUpdate(Context context) { RemoteViews updateViews = null; Calendar calendar = Calendar.getInstance(); String months = Months[calendar.get(Calendar.MONTH)]; //获取widget布局 updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout); //为布局空间设置内容 updateViews.setTextViewText(R.id.Month, months); updateViews.setTextViewText(R.id.Date, String.valueOf(calendar.get(Calendar.DATE))); //点击控件跳转到指定activity Intent i = new Intent(); i.setComponent(new ComponentName("com.example.widgetdemo", "com.example.widgetdemo.MainActivity")); i.setAction(Intent.ACTION_MAIN); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); i.addCategory(Intent.CATEGORY_LAUNCHER); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i, 0); updateViews.setOnClickPendingIntent(R.id.bt, pendingIntent); return updateViews; } }
相关推荐
Nostalgiachild 2020-11-13
韩伟佳 2020-10-09
wuleihenbang 2020-09-16
zzqLivecn 2020-07-09
chenjinlong 2020-06-10
yinbaoshiguang 2020-06-09
sgafdsg 2020-06-04
ustcrding 2020-06-03
chenjinlong 2020-06-03
AndroidGA 2020-06-01
安辉 2020-05-27
绿豆饼 2020-05-26
CNETNews 2020-05-26
xilove0 2020-05-12
绿豆饼 2020-05-12
ChainDestiny 2020-05-07
doomvsjing 2020-05-07
hqulyc 2020-05-05
lyccsu 2020-04-30