widget入门
16lz
2021-12-04
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 = { "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月","九月", "十月", "十一月", "十二月" };@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stubsuper.onReceive(context, intent);}@Overridepublic void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) {// TODO Auto-generated method stubRemoteViews 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)));//点击控件跳转到指定activityIntent 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;}}
更多相关文章
- 10.10笔记,android通知栏兼容性,matches the given name 'android
- Android事件处理
- Android(安卓)中使用自定义字体的方法
- Android(安卓)AlertDialog的基本使用方法
- Android之设置横、竖屏方法
- Android(安卓)SDK下载和更新失败的解决方法
- LayoutInflater.inflate()方法的介绍
- Android之Google Map(一)
- android Aidl 实现进程间通讯