Kotlin Service实现消息推送通知过程

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Kotlin Service实现消息推送通知过程

go2coding   2022-12-05 我要评论

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

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

Service 的使用也非常的简单,简单的建立和绑定,就能完成Service的动作。

建立Service

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

建立一个

    internal class MyBinder(private val service: NotificationService) : Binder() {
        fun getService() : NotificationService{
            return service
        }
    }

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
    }

这里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)
        }
    }

通过上面的代码,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)
    }

当我们发送的通知消息被点击以后,会回到我们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)

我们需要和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)
    }

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

小结

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们