背景
项目中有时需要在安卓桌面添加widget,方便用户查看或做一些操作.
Demo实现效果图
用于实现一个显示日期的widget
实现步骤
1. 新建widget
2. 选择占用屏幕空间的大小
3. 自动生成的代码文件
4. 主要代码如下:
class TimerService : Service() {
private lateinit var rv: RemoteViews
private lateinit var manager: AppWidgetManager
// 定义定时器
private lateinit var timer: Timer
// 定义格式化日期时间
@SuppressLint("SimpleDateFormat")
private val sdf = SimpleDateFormat("HH : mm-MM / dd E")
override fun onCreate() {
super.onCreate()
timer = Timer()
timer.schedule(object : TimerTask() {
override fun run() {
updateViews()
}
}, 0, 1000)
}
private fun updateViews() {
rv = RemoteViews(packageName, R.layout.time_widget)
val cn = ComponentName(applicationContext, WidgetProvider::class.java)
manager = AppWidgetManager.getInstance(applicationContext)
val str = sdf.format(Date())
val timeStr = str.substring(0, 7)
rv.setTextViewText(R.id.timeTv, timeStr)
manager.updateAppWidget(cn, rv)
}
override fun onDestroy() {
super.onDestroy()
timer.cancel()
}
override fun onBind(arg0: Intent): IBinder? {
return null
}
}
class WidgetProvider : AppWidgetProvider() {
override fun onReceive(context: Context, intent: Intent) {
// 接收开机和启动程序时候的广播时执行
super.onReceive(context, intent)
context.startService(Intent(context, TimerService::class.java))
}
override fun onEnabled(context: Context) {
// Widget添加到屏幕时执行
super.onEnabled(context)
context.startService(Intent(context, TimerService::class.java))
}
override fun onDisabled(context: Context) {
// 最后一次Widget从屏幕移除时执行
super.onDisabled(context)
context.stopService(Intent(context, TimerService::class.java))
}
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.cxyzy.desktopwidgetdemo">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<receiver android:name=".WidgetProvider">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/time_widget_info" />
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".TimerService" />
</application>
</manifest>
5. 运行安装app后,在手机上添加桌面控件
##6. FAQ
一定要保持app是运行的,否则widget就不会更新了.