Android 桌面小組件使用

来源:https://www.cnblogs.com/stars-one/p/18073082
-Advertisement-
Play Games

原文: Android 桌面小組件使用-Stars-One的雜貨小窩 藉助公司上的幾個項目,算是學習了Android桌面小組件的用法,記下踩坑記錄 基本步驟 1.創建小組件佈局 這裡需要註意的事,小組件佈局里不能使用自定義View,只能使用原生的組件,比如說LinearLayout,TextView ...


原文: Android 桌面小組件使用-Stars-One的雜貨小窩

藉助公司上的幾個項目,算是學習了Android桌面小組件的用法,記下踩坑記錄

基本步驟

1.創建小組件佈局

這裡需要註意的事,小組件佈局里不能使用自定義View,只能使用原生的組件,比如說LinearLayout,TextView,連約束佈局都不能使用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white"
    android:orientation="vertical"
    android:padding="16dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tvDate"
            style="@style/textStyle14"
            android:textColor="#313131"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="2023-12-10" />

        <ImageView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <TextView
            android:id="@+id/tvTime"
            android:textColor="#313131"
            style="@style/textStyle14"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="12:10" />

    </LinearLayout>

    <LinearLayout
        android:layout_marginTop="16dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/result_clean"/>

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="0dp"
            android:layout_marginStart="9dp"
            android:gravity="center_vertical"
            android:layout_height="match_parent"
            android:layout_weight="1" >
            <TextView
                style="@style/textStyle14"
                android:textColor="#313131"
                android:textStyle="bold"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="125.4MB"/>
            <TextView
                style="@style/textStyle14"
                android:textColor="#313131"
                android:textStyle="bold"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Junk"/>
        </LinearLayout>

        <TextView
            android:layout_gravity="center_vertical"
            android:id="@+id/tvClean"
            android:textColor="#313131"
            style="@style/textStyle14"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Clean" />

    </LinearLayout>

</LinearLayout>

2.創建provider

import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.widget.RemoteViews
import android.widget.RemoteViews.RemoteView
import ten.jou.recover.R

class CleaningWidget : AppWidgetProvider() {
    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray
    ) {
        appWidgetIds.forEach {
			//如果小組件佈局中使用不支持的組件,這裡創建RemoteViews時候,IDE會報紅提示!
            val remoteView = RemoteViews(context.packageName, R.layout.widget_layout)
			//綁定數據
			remoteView.setTextViewText(R.id.tv1,"hello world")
            appWidgetManager.updateAppWidget(it, remoteView)
        }

    }
}

AppWidgetProvider本質就是一個廣播接收器,所以在清單文件需要聲明(見步驟4)

這裡先補充下,RemoteViews對於TextView,ImageView等View,有設置文本,字體顏色,圖片等相關方法,但並不是所有方法都支持,綁定數據的時候需要註意下小組件是否支持!

3.創建xml屬性聲明

在xml文件夾里新建widget_info.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:targetCellWidth="4"
    android:targetCellHeight="2"
    android:minWidth="250dp"
    android:minHeight="110dp"
    android:updatePeriodMillis="0"
    android:initialLayout="@layout/widget_layout"
    tools:targetApi="s">
</appwidget-provider>

Android12版本以上新增的2個屬性,聲明組件是4*2大小

  • targetCellWidth
  • targetCellHeight

4.清單文件聲明

<receiver
	android:name=".view.CleaningWidget"
	android:enabled="true"
	android:exported="true">
	<intent-filter>
		<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
	</intent-filter>
	<meta-data
		android:name="android.appwidget.provider"
		android:resource="@xml/widget_info" />
</receiver>

5.代碼添加小組件

官方說Android12不允許直接通過代碼添加小組件,只能讓用戶手動去桌面拖動添加,但是我手頭的三星系統卻是支持的(也是Android12),具體還沒有細究...

而官方文檔上的寫的例子如下:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
	val context = this@DesktopWidgetActivity

	val appWidgetManager: AppWidgetManager =
		context.getSystemService(AppWidgetManager::class.java)
	val myProvider = ComponentName(context, CleaningWidget::class.java)

	//判斷啟動器是否支持小組件pin
	val successCallback = if (appWidgetManager.isRequestPinAppWidgetSupported) {
		// Create the PendingIntent object only if your app needs to be notified
		// that the user allowed the widget to be pinned. Note that, if the pinning
		// operation fails, your app isn't notified.
		Intent(context, CleaningWidget::class.java).let { intent ->
			// Configure the intent so that your app's broadcast receiver gets
			// the callback successfully. This callback receives the ID of the
			// newly-pinned widget (EXTRA_APPWIDGET_ID).
			//適配android12的
			val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
				PendingIntent.FLAG_MUTABLE
			} else {
				PendingIntent.FLAG_UPDATE_CURRENT
			}
			PendingIntent.getBroadcast(
				context,
				0,
				intent,
				flags
			)
		}
	} else {
		null
	}

	appWidgetManager.requestPinAppWidget(myProvider, null, successCallback)
}

這裡提下,上面的設置flags方法

val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
	PendingIntent.FLAG_MUTABLE
} else {
	PendingIntent.FLAG_UPDATE_CURRENT
}

有個新項目的targetSdk為34(即Android14),如果使用上面的代碼會出現下麵崩潰錯誤提示

Targeting U+ (version 34 and above) disallows creating or retrieving a PendingIntent with FLAG_MUTABLE, an implicit Intent within and without FLAG_NO_CREATE and FLAG_ALLOW_UNSAFE_IMPLICIT_INTENT for security reasons. To retrieve an already existing PendingIntent, use FLAG_NO_CREATE, however, to create a new PendingIntent with an implicit Intent use FLAG_IMMUTABLE.

實際上提示已經告訴我們怎麼去改代碼了,我這裡把PendingIntent.FLAG_MUTABLE改為FLAG_IMMUTABLE就不會出現了上述的崩潰問題

應該是Android14添加的限制:

  • 如果Intent不傳數據,必須使用PendingIntent.FLAG_IMMUTABLE
  • 如果是需要傳遞數據,則還是需要使用PendingIntent.FLAG_MUTABLE

定時刷新小組件UI

首先,我們得知道,如何主動去更新數據:

val context = it.context
val appWidgetManager: AppWidgetManager = context.getSystemService(AppWidgetManager::class.java)
val myProvider = ComponentName(context, CleaningWidget::class.java)
val remoview = CleaningWidget.getRemoteViewTest(context)

//更新某類組件
appWidgetManager.updateAppWidget(myProvider,remoview)
//更新具體某個組件id
appWidgetManager.updateAppWidget(widgetId,remoview)

getRemoteViewTest方法就是創建一個remoteview,然後調用remoteview相關方法設置文本之類的進行數據填充,代碼就略過不寫了,詳見上述基本步驟2

上面的方法我們註意到updateAppWidget可以傳不同的參數,一般我們用的第二個方法,指定更新某個組件

但這裡又是需要我們傳一個組件id,所以就是在步驟2的時候,我們根據需要需要存儲下widgetId比較好,一般存入資料庫,或者使用SharePreference也可

然後,就是對於定時的情況和對應方案:

  1. 如果是間隔多長更新一次,可以使用開一個服務,在服務中開啟協程進行
  2. 如果是單純的時間文本更新,可以使用TextClock組件,比如說 12:21這種
  3. 小組件的xml中預設可以設置定時更新時長,不過最短只能需要15分鐘
  4. 可以使用鬧鐘服務AlarmManager來實現定時,不過此用法需要結合pendingintent和廣播接收器使用,最終要在廣播接收器里調用更新數據方法
  5. JobScheduler來實現定時更新,似乎受系統省電策略影響,適用於不太精確的定時事件(官方文檔上推薦這個)
  6. WorkManager來實現定時更新(實際上算是JobScheduler升級版),似乎受系統省電策略影響,適用於不太精確的定時事件

應該是除了第一種方法,其他都是可以在應用被殺死的情況進行更新小組件UI

小組件播放動畫

progressbar實現

幀動畫不手動調用anim.start()方法是不會播放的,然後在網上看到一篇文章,使用了progressbar來實現,步驟如下:

在drawable文件夾準備幀動畫文件

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false" android:visible="true">
    <item android:drawable="@drawable/cat_1" android:duration="100" />
    <item android:drawable="@drawable/cat_2" android:duration="100" />
    <item android:drawable="@drawable/cat_3" android:duration="100" />
    <item android:drawable="@drawable/cat_4" android:duration="100" />
</animation-list>
<ProgressBar
	android:indeterminateDrawable="@drawable/cat_animdrawable"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"/>

indeterminateDrawable設置為上面的幀動畫文件即可

layoutanim實現

主要是利用viewgroup的初次顯示的時候,會展示當前view的添加動畫效果,從而實現比較簡單的動畫效果,如平移,縮放等

可以看實現的敲木魚一文Android-桌面小組件RemoteViews播放木魚動畫 - 掘金

使用ViewFlipper

ViewFlipper主要是輪播使用的

裡面可放幾個元素,之後通過設置autoStart為true,則保證自動輪播

flipInterval屬性則是每個元素的間隔時間(幀動畫的時間),單位為ms

不過在remoteview中使用的話,缺點就是裡面的元素數目只能固定死

否則只能通過定義不同layout文件(如3個元素則是某個layout,4個元素則是某個layout,然後根據選擇來創建remoteview)

<ViewFlipper
        android:id="@+id/viewFlipper"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_margin="4dp"
        android:autoStart="true"
        android:flipInterval="800">

        <ImageView
            android:id="@+id/vf_img_1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="fitXY"
            android:src="@drawable/peace_talisman_1" />

        <ImageView
            android:id="@+id/vf_img_2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="fitXY"
            android:src="@drawable/peace_talisman_2" />
    </ViewFlipper>

補充

獲取當前桌面的組件id列表

//獲得當前桌面已添加的組件的id列表(可能用戶添加了多個)
val context = it.context
val appWidgetManager: AppWidgetManager = context.getSystemService(AppWidgetManager::class.java)
val myProvider = ComponentName(context, CleaningWidget::class.java)

val info =appWidgetManager.getAppWidgetIds(myProvider)
toast(info.size.toString())

參考


提問之前,請先看提問須知 點擊右側圖標發起提問 聯繫我 或者加入QQ群一起學習 Stars-One安卓學習交流群 TornadoFx學習交流群:1071184701
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 本文分享自華為雲社區《GaussDB資料庫的索引管理》,作者: Gauss松鼠會小助手2。 一、引言 GaussDB資料庫是華為公司傾力打造的自研企業級分散式關係型資料庫,索引的設計和管理對於提高查詢性能至關重要。下麵將通過實際例子深入研究GaussDB資料庫的索引管理。 二、GaussDB資料庫中 ...
  • adminpack 提供了大量支持功能,pgAdmin 和其他管理工具可以使用這些功能提供額外功能,例如遠程管理伺服器日誌文件。預設情況下,只有資料庫超級用戶才能使用所有這些功能,但其他用戶也可以使用 GRANT 命令使用這些功能。 我們先來看一下他支持的函數,可以通過 \dx+ adminpack ...
  • 在我們講解這個案例前,我們先來瞭解/預熱一下SQL Server的兩個概念:鍵查找(key lookup)和RID查找(RID lookup),通常,當查詢優化器使用非聚集索引進行查找時,如果所選擇的列或查詢條件中的列只部分包含在使用的非聚集索引和聚集索引中時,就需要一個查找(lookup)來檢索其 ...
  • 支持事務安全表(ACID),支持行鎖定和外鍵; MySQL事務的ACID特性是確保數據準確性和可靠性的基本原則,包括**原子性(Atomicity)、一致性(Consistency)、隔離性(Isolation)和持久性(Durability)**。具體如下: 1. **原子性(Atomicity) ...
  • 在MySQL 8.0中,可以通過創建自定義哈希函數來處理VARCHAR類型的欄位,以便用作分區鍵。下麵是一個簡單的示例,演示如何在MySQL8.0中創建自定義哈希函數來處理VARCHAR類型的欄位 分區後的表效果 方法一,自定義哈希函數,失敗而告終 創建自定義哈希函數: DELIMITER // C ...
  • 對於資料庫表中的大類,小類我們基本一直在使用id ,parentid的方式,今天發現了一種更清晰,更完美的解決方式。 SQL Server 2008版本之後的新類型HierarchyID 不知道大家有沒有瞭解, 該類型作為取代id, parentid的一種解決方案,讓人非常驚喜。 官方給的案例淺顯易 ...
  • 正處於企業指標建設過程中的你,是否經常遇到這樣的問題: • 各個部門獨立建設信息系統,由此產生的指標定義和計算方式各異,導致管理層無法快速準確地掌握整體業務運行狀況 • 缺乏對指標的統一管理和規範,產生重覆的指標計算工作,導致數據計算資源被過度消耗,增加運維成本和數據處理壓力 • 不知道指標體系建設 ...
  • GreatSQL里也能用上RocksDB引擎 1. 前言 RocksDB 是基於Facebook 開源的一種支持事務的、高度可壓縮、高性能的MyRocks存儲引擎,特別適用於高度壓縮和大容量的數據。以下是一些關鍵特點: 高性能: LSM 樹結構使得RocksDB在寫入密集型負載下表現卓越。它能夠處理 ...
一周排行
    -Advertisement-
    Play Games
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...
  • 目錄前言PostgreSql安裝測試額外Nuget安裝Person.cs模擬運行Navicate連postgresql解決方案Garnet為什麼要選擇Garnet而不是RedisRedis不再開源Windows版的Redis是由微軟維護的Windows Redis版本老舊,後續可能不再更新Garne ...
  • C#TMS系統代碼-聯表報表學習 領導被裁了之後很快就有人上任了,幾乎是無縫銜接,很難讓我不想到這早就決定好了。我的職責沒有任何變化。感受下來這個系統封裝程度很高,我只要會調用方法就行。這個系統交付之後不會有太多問題,更多應該是做小需求,有大的開發任務應該也是第二期的事,嗯?怎麼感覺我變成運維了?而 ...
  • 我在隨筆《EAV模型(實體-屬性-值)的設計和低代碼的處理方案(1)》中介紹了一些基本的EAV模型設計知識和基於Winform場景下低代碼(或者說無代碼)的一些實現思路,在本篇隨筆中,我們來分析一下這種針對通用業務,且只需定義就能構建業務模塊存儲和界面的解決方案,其中的數據查詢處理的操作。 ...
  • 對某個遠程伺服器啟用和設置NTP服務(Windows系統) 打開註冊表 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer 將 Enabled 的值設置為 1,這將啟用NTP伺服器功 ...
  • title: Django信號與擴展:深入理解與實踐 date: 2024/5/15 22:40:52 updated: 2024/5/15 22:40:52 categories: 後端開發 tags: Django 信號 松耦合 觀察者 擴展 安全 性能 第一部分:Django信號基礎 Djan ...
  • 使用xadmin2遇到的問題&解決 環境配置: 使用的模塊版本: 關聯的包 Django 3.2.15 mysqlclient 2.2.4 xadmin 2.0.1 django-crispy-forms >= 1.6.0 django-import-export >= 0.5.1 django-r ...
  • 今天我打算整點兒不一樣的內容,通過之前學習的TransformerMap和LazyMap鏈,想搞點不一樣的,所以我關註了另外一條鏈DefaultedMap鏈,主要調用鏈為: 調用鏈詳細描述: ObjectInputStream.readObject() DefaultedMap.readObject ...
  • 後端應用級開發者該如何擁抱 AI GC?就是在這樣的一個大的浪潮下,我們的傳統的應用級開發者。我們該如何選擇職業或者是如何去快速轉型,跟上這樣的一個行業的一個浪潮? 0 AI金字塔模型 越往上它的整個難度就是職業機會也好,或者說是整個的這個運作也好,它的難度會越大,然後越往下機會就會越多,所以這是一 ...
  • @Autowired是Spring框架提供的註解,@Resource是Java EE 5規範提供的註解。 @Autowired預設按照類型自動裝配,而@Resource預設按照名稱自動裝配。 @Autowired支持@Qualifier註解來指定裝配哪一個具有相同類型的bean,而@Resourc... ...