android桌面控件開發

創建

直接根據前一篇的快捷創建
備註:有些機型的
android:minWidth
android:minHeight,
必須設置,不然會顯示不出來,現在遇到魅族是這種情況

做一個桌面數字時鐘

佈局就不說了
爲了跳過創建widget時要先打開的activity,直接在activity的onCreate中startService,開啓服務,在onCreate的最後finish()掉自己。
在service的onCreate()中

		val timer = Timer()
        timer.schedule(object : TimerTask() {
            override fun run() {
                handler.sendEmptyMessage(0x123)
            }
        }, 0, 1000)

創建handler接收每秒一次的message,在裏面設置相應的邏輯

    private val handler = @SuppressLint("HandlerLeak")
    object : android.os.Handler() {
        override fun handleMessage(msg: Message?) {
            if (msg?.what == 0x123) {
               time = "yyyy/MM/dd><><HH:mm:ss"
                val remoteViews =
                    RemoteViews([email protected], R.layout.weather_widget)
                val format = SimpleDateFormat(time, Locale.getDefault())
                val s = format.format(Date().time).split("><><")
                remoteViews.setTextViewText(R.id.widget_time_one, s[1])
                remoteViews.setTextViewText(R.id.widget_time_two, s[0])
                val componentName = ComponentName(applicationContext, WeatherWidget::class.java)
                val appWidgetManager = AppWidgetManager.getInstance(this@TimesService)
                appWidgetManager.updateAppWidget(componentName, remoteViews)
            }
        }
    }

ps:可以根據這種方法設計自己需要的桌面控件

開發中的補充

1、由於SharedPreferences不能在不同進程中進行通訊,所以一些簡單的數據我都是直接通過多次startService,創建intent來傳遞數據,在onStartCommand中寫獲取數據後的操作;
2、應用打開獲取網絡數據的時候,控件也需要獲取到相應的數據,並更改顯示,有這方面需求的話,可以直接在需要獲取到網絡數據後直接獲取val remoteViews = RemoteViews(mContext?.packageName, R.layout.weather_widget),並設置相應的顯示變化;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章