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---桌面小部件。

posted @ 2018-07-20 10:34  鲁迅认识的那只猹  阅读(1680)  评论(0编辑  收藏  举报