广告
返回顶部
首页 > 资讯 > 移动开发 >KotlinService实现消息推送通知过程
  • 430
分享到

KotlinService实现消息推送通知过程

KotlinService消息推送KotlinService推送通知KotlinService 2022-12-08 20:12:38 430人浏览 薄情痞子
摘要

目录建立Service绑定服务小结四大组件,就剩下最后一个Service ,他比较重要,相当于后台服务,基本上大部分的app,都会有一两个这样的服务Service 。 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
        }
    }

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中注意这四个组件的用法,对开发程序会有很大的帮助。

到此这篇关于Kotlin Service实现消息推送通知过程的文章就介绍到这了,更多相关Kotlin Service消息推送内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: KotlinService实现消息推送通知过程

本文链接: https://www.lsjlt.com/news/174285.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作