AppWidget使用方法
阅读原文时间:2023年07月08日阅读:2

手机桌面小组件

public class AppWidget extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Log.d("MyAppWidgetProvider", "调用了onUpdate方法");
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.remoteview);
remoteViews.setImageViewResource(R.id.image, R.drawable.ic2);
remoteViews.setTextViewText(R.id.text, "我是桌面小组件");
remoteViews.setOnClickPendingIntent(R.id.image, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);//用updateAppWidget来更新remoteViews的状态
}

}

定义一个类继承AppWidgetProvider重写onupdate方法

<ImageView  
    android:id="@+id/image"  
    android:layout\_width="match\_parent"  
    android:layout\_height="200dp" />  
<TextView  
    android:id="@+id/text"  
    android:layout\_width="match\_parent"  
    android:layout\_height="wrap\_content" />

自定义布局文件remoteView

xml文件appwidget

配置文件声明appwidget,运行后手机添加桌面小组件,点击图片会进入Pendingintent的activity

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器