一、需求
桌面插件每秒更新信息
二、实现
1.首先创建App Widget
2.修改桌面布局代码
new_app_widget.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/Widget.GeoApplication.AppWidget.Container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:theme="@style/Theme.GeoApplication.AppWidgetContainer">
<TextView
android:id="@+id/appwidget_text"
style="@style/Widget.GeoApplication.AppWidget.InnerView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="8dp"
android:contentDescription="@string/appwidget_text"
android:text="@string/appwidget_text"
android:textSize="24sp"
android:textStyle="bold|italic" />
<ImageView
android:id="@+id/appwidget_image"
style="@style/Widget.GeoApplication.AppWidget.InnerView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="8dp"
android:src="@drawable/ic_launcher_foreground"
android:contentDescription="@string/appwidget_text"
android:text="@string/appwidget_text"
android:textSize="24sp"
android:textStyle="bold|italic" />
RelativeLayout>
3.桌面插件被创建的时候,使用Alarm定时器刷新。
在onUpdate 方法中
NewAppWidge.kt
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) {
// There may be multiple widgets active, so update all of them
//使用Alarm定时更新界面数据
val alarm = context?.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE)
val pendingIntentTwo =
PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val triggerAtTime = SystemClock.elapsedRealtime() + (10 * 1000)
val interval = 10 * 1000L
alarm.setRepeating(AlarmManager.RTC, triggerAtTime, interval, pendingIntentTwo)
for (appWidgetId in appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId)
}
}
在onReceive方法中
override fun onReceive(context: Context?, intent: Intent?) {
super.onReceive(context, intent)
//获取桌面控件的视图
context?.let {
val ids = AppWidgetManager.getInstance(context).getAppWidgetIds(
ComponentName(
context,
NewAppWidget::class.java
)
)
onUpdate(context, AppWidgetManager.getInstance(context),ids)
}
}
这时候调用插件就可以更新了