• Kotlin 开发Android app(十七):用Service推送消息通知


    四大组件,就剩下最后一个Service ,他比较重要,相当于后台服务,基本上大部分的app,都会有一两个这样的服务Service

    Service用处非常的多,可以根据后台的特性来决定Service的用法。

    在这里插入图片描述
    Service 的使用也非常的简单,简单的建立和绑定,就能完成Service的动作。

    建立Service

    这里我们创建一个Service,用它来发送消息服务,这里从服务的建立和用Binder 来绑定服务,这样可以建立起ServiceActivity之间的通讯问题。

    建立一个

        internal class MyBinder(private val service: NotificationService) : Binder() {
    
            fun getService() : NotificationService{
                return service
            }
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    MyBinder 是我们的中间人,我们需要通过它来找到真正的Service

    NotificationService 如下:

    class NotificationService : Service() {
    
        private lateinit var mNotification: Notification
        private val mNotificationId: Int = 1000
    
        private var mBinder = MyBinder(this@NotificationService)
    
    
    
        companion object {
    
            const val CHANNEL_ID = "com.kotlin.kotlin_start_ch18.CHANNEL_ID"
            const val CHANNEL_NAME = "Sample Notification"
        }
    
    
        override fun onBind(intent: Intent): IBinder {
            return mBinder
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    这里NotificationService 是一个空的,什么任务也没有,为他加一个简单的任务,就是消息推送通知。

     @SuppressLint("NewApi")
        private fun createChannel() {
    
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    
                // Create the NotificationChannel, but only on API 26+ because
                // the NotificationChannel class is new and not in the support library
    
                val context = this.applicationContext
                val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    
                val importance = NotificationManager.IMPORTANCE_HIGH
                val notificationChannel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance)
                notificationChannel.enableVibration(true)
                notificationChannel.setShowBadge(true)
                notificationChannel.enableLights(true)
                notificationChannel.lightColor = Color.parseColor("#e8334a")
                notificationChannel.description = getString(R.string.notification_channel_description)
                notificationChannel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
                notificationManager.createNotificationChannel(notificationChannel)
            }
    
        }
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    通过上面的代码,NotificationService 就有了自己的事情做了,可以通过notifyMessage()

        public fun notifyMessage(){
            //Create Channel
            createChannel()
    
    
    
    
            val context = this.applicationContext
            var notificationManager: NotificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            val notifyIntent = Intent(this, ResultActivity::class.java)
    
            val title = "Sample Notification"
            val message =
                "You have received a sample notification. This notification will take you to the details page."
    
            notifyIntent.putExtra("title", title)
            notifyIntent.putExtra("message", message)
            notifyIntent.putExtra("notification", true)
    
            notifyIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    
    
    
            val pendingIntent =
                PendingIntent.getActivity(context, 0, notifyIntent, PendingIntent.FLAG_IMMUTABLE)
            val res = this.resources
            val uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    
    
                mNotification = Notification.Builder(this, CHANNEL_ID)
                    // Set the intent that will fire when the user taps the notification
                    .setContentIntent(pendingIntent)
                    .setSmallIcon(R.drawable.ic_stat_name)
                    .setLargeIcon(BitmapFactory.decodeResource(res, R.mipmap.ic_launcher))
                    .setAutoCancel(true)
                    .setContentTitle(title)
                    .setStyle(
                        Notification.BigTextStyle()
                            .bigText(message)
                    )
                    .setContentText(message).build()
            } else {
    
                mNotification = Notification.Builder(this)
                    // Set the intent that will fire when the user taps the notification
                    .setContentIntent(pendingIntent)
                    .setSmallIcon(R.drawable.ic_stat_name)
                    .setLargeIcon(BitmapFactory.decodeResource(res, R.mipmap.ic_launcher))
                    .setAutoCancel(true)
                    .setPriority(Notification.PRIORITY_MAX)
                    .setContentTitle(title)
                    .setStyle(
                        Notification.BigTextStyle()
                            .bigText(message)
                    )
                    .setSound(uri)
                    .setContentText(message).build()
    
            }
    
    
    
            notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            // mNotificationId is a unique int for each notification that you must define
            notificationManager.notify(mNotificationId, mNotification)
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69

    当我们发送的通知消息被点击以后,会回到我们appResultActivity 中,只要在程序中把ResultActivity 实现为自己的逻辑,就能调整到ResultActivity 页面中。

    绑定服务

    启动服务可以有两种方法,一种是直接启动,一种还要进行相应的绑定。

    val service = Intent(this@MainActivity, NotificationService::class.java)
                service.putExtra("reason", intent.getStringExtra("reason"))
                service.putExtra("timestamp", intent.getLongExtra("timestamp", 0))
    
                service.data = Uri.parse("custom://" + System.currentTimeMillis())
                startService(service)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    我们需要和Service 进行通讯,所以我们采用绑定的方式。

        private fun bindService() {
            connection = object : ServiceConnection {
                override fun onServiceConnected(name: ComponentName, service: IBinder) {
                    binder = service as NotificationService.MyBinder
                }
    
                override fun onServiceDisconnected(name: ComponentName) {}
            }
    
            val intent = Intent(this, NotificationService::class.java)
            startService(intent)
            bindService(intent, connection as ServiceConnection, Context.BIND_AUTO_CREATE)
    
    
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    如上,我们可以通过服务,发送通知消息了。

    在这里插入图片描述

    小结

    四大组件,我们已经一个一个的进行了简单的介绍,你会慢慢的了解到安卓开发中主要的组件形式和使用的方法,后面还会慢慢的安卓的其他的特性进行介绍。这四大组件非常的重要,可以在其他的demo中注意这四个组件的用法,对开发程序会有很大的帮助。

  • 相关阅读:
    MindSpore:无法观看官网线上课程视频
    mysql 启动报错 Can t change dir to xxx, No such file or directory 配置错误或挂载导致
    使用Redux-Toolkit,由“object is not extensible”引发的思考及解决方案
    【分布式】分布式锁解决方案介绍、DBMS级别乐观、悲观、redis的SETNX实现分布式锁
    helm使用
    【StreamSets】StreamSets 表达式语言篇
    C++11之lambda表达式理解与使用
    Maven jar 的查找及依赖版本确定
    Java获取当前时区时间LocalDateTime与System.currentTimeMillis
    【算法训练-二叉树 四】【对称与翻转】对称二叉树、翻转二叉树
  • 原文地址:https://blog.csdn.net/weixin_40425640/article/details/128021512