Android-通知欄上的RemoteView


Android-通知欄上的RemoteView

學習自

《Android開發藝術探索》
https://developer.android.google.cn/reference/android/widget/RemoteViews

RemoteView漫談

什么是RemoteView?先找官方文檔

以下內容來自於RemoteViews類的官方文檔
A class that describes a view hierarchy that can be displayed in another process. The hierarchy is inflated from a layout resource file, and this class provides some basic operations for modifying the content of the inflated hierarchy.
該類描述了一個能夠被顯示在其他進程中的View。該View的層次結構來自資源文件,並且此類提供了一下基礎的操作來幫助修改View的內容。

從上面的官方文檔中我們了解到,遠程View之所以被稱作為遠程View,是因為他們運行在另一個進程中當然遠了😂 。 RemoteView在開發中主要會作用於兩個方面 通知欄 桌面小部件 。因為View是存在於另一個進程中的所以我們不能夠像直接操作View的那樣來操作RemoteView,為了幫助我們操作RemoteView呢,Google為我們提供了 RemoteViews 類來幫助我們操作RemoteView。

這篇文章先來學習通知欄上的RemoteView,在下面的文章中我們會學習桌面小部件。

Notification與RemoteView

在通知欄上的RemoteView是依托於通知的(-_-||)。通過RemoteView我們可以實現自定義的通知樣式。下面是一個系統默認樣式的通知。

fun send(view: View) {
    var intent = Intent(this, MainActivity::class.java)
    var pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
    var notification = Notification.Builder(this).apply {
        setTicker("Hello world")
        setSmallIcon(R.mipmap.ic_launcher)
        setContentTitle("This is a title")
        setContentText("Content......")
        setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher))
        setContentIntent(pendingIntent)
    }.build()
    var manager = this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    manager.notify(1, notification)
}

我想上面的發送通知的代碼大家一定很熟悉,但是有有時候系統默認的通知並不能滿足我們的需要,往往我們需要自定義通知的樣式。這時候就需要RemoteView了。

下面是一個RemoteView模仿通知欄播放音樂的控制器的Demo,在實際的開發中還需要用到前台任務,這里就是簡單模仿一下當不得真。

image.png | left | 373x95

發送通知的代碼。

fun send2(view: View) {
    var intent = Intent(this, MainActivity::class.java)
    var pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)

    var builder = Notification.Builder(this)
    builder.setSmallIcon(R.mipmap.ic_launcher)
    builder.setAutoCancel(false)

    var remoteViews = RemoteViews(packageName, R.layout.music_remote)
    remoteViews.setTextViewText(R.id.singNameTV, "牽絲戲")
    //設置View的點擊事件,視具體情況可以開啟Activity/發送通知/開啟服務等
    //這里直接模擬一下,無所謂什么了
    remoteViews.setOnClickPendingIntent(R.id.previousIV, pendingIntent)
    remoteViews.setOnClickPendingIntent(R.id.pauseIV, pendingIntent)
    remoteViews.setOnClickPendingIntent(R.id.nextIV, pendingIntent)

    builder.setCustomContentView(remoteViews)

    var manager = this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    manager.notify(1, builder.build())
}

總結

通知欄的RemoteView的內榮比較少也比較簡單就沒做過多的介紹,通知欄的RemoteView的用途相當廣泛: 播放音樂,安全類的軟件的快速操作等。在下一章的內容呢,將會學習另一種RemoteView---桌面小部件。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM