首页 > 其他分享 >Service

Service

时间:2024-05-26 14:58:21浏览次数:15  
标签:Service val override intent fun onCreate super

启动和停止

 class MainActivity : AppCompatActivity() { 
 
    override fun onCreate(savedInstanceState: Bundle?) { 
        super.onCreate(savedInstanceState) 
        setContentView(R.layout.activity_main) 
        startServiceBtn.setOnClickListener { 
            val intent = Intent(this, MyService::class.java) 
            startService(intent) // Service 
        } 
        stopServiceBtn.setOnClickListener { 
            val intent = Intent(this, MyService::class.java) 
            stopService(intent) // Service 
        } 
    } 
 
}

类重写的函数

class MyService : Service() {

    override fun onCreate() {
        super.onCreate() // 启动时调用
    }

    override fun onDestroy() {
        super.onDestroy() // 销毁时调用
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return super.onStartCommand(intent, flags, startId) // 调用service时调用
    }
    override fun onBind(intent: Intent): IBinder {
        // 其他组件与service建立连接会调用
    }
}

与Activity通信

MyService.kt

class MyService : Service() {
    private val mBinder = mybinder()
    class mybinder: Binder(){
        fun way(){
            println("way")
        }
    }
    override fun onCreate() {
        super.onCreate() // 启动时调用
    }

    override fun onDestroy() {
        super.onDestroy() // 销毁时调用
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return super.onStartCommand(intent, flags, startId) // 调用service时调用
    }
    override fun onBind(intent: Intent): IBinder {
        return mBinder
    }
}

MainActivity.kt

class MainActivity : AppCompatActivity() {
    lateinit var mybinder: MyService.mybinder
    private val connection = object :ServiceConnection{
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            mybinder = service as MyService.mybinder
            mybinder.way()
            // activity与service成功绑定时调用
        }

        override fun onServiceDisconnected(name: ComponentName?) {
        }

    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        val btn1 : Button = findViewById(R.id.btn1)
        btn1.setOnClickListener {
            val intent = Intent(this,MyService::class.java)
            bindService(intent,connection,Context.BIND_AUTO_CREATE)
            // 通过intent与service绑定
        }

        val btn2:Button = findViewById(R.id.btn2)
        btn2.setOnClickListener {
            unbindService(connection)
        }
    }
}

前台Service

修改myService的onCreate方法:

override fun onCreate() {
        super.onCreate() // 启动时调用
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val channel = NotificationChannel("myservice","前台",NotificationManager.IMPORTANCE_DEFAULT)
        manager.createNotificationChannel(channel)
        val intent = Intent(this,MainActivity::class.java)
        val pi = PendingIntent.getActivity(this,0,intent, PendingIntent.FLAG_IMMUTABLE)
        val notification = NotificationCompat.Builder(this,"myservice")
            .setContentTitle("This is content title")
            .setContentText("This is content text")
            .setContentIntent(pi)
            .build()
        startForeground(1, notification)
    }

IntentService

 class MyIntentService : IntentService("MyIntentService") { 
 
    override fun onHandleIntent(intent: Intent?) { 
        // 子线程逻辑
        Log.d("MyIntentService", "Thread id is ${Thread.currentThread().name}") 
    } 
 
    override fun onDestroy() { 
        super.onDestroy() 
        Log.d("MyIntentService", "onDestroy executed") 
    } 
 
} 

Service可以与应用程序的其他组件(如Activity)进行通信,而IntentService通常用于执行与应用程序交互不直接相关的任务。Service需要手动管理线程和生命周期,而IntentService在单独的工作线程中运行,无需手动管理线程。

标签:Service,val,override,intent,fun,onCreate,super
From: https://blog.csdn.net/qq_64863535/article/details/139059578

相关文章

  • VB6重启服务WINDOWS service
     服务状态State=Running等待服务,直到停止状态State=StopPending,Started=True状态State=StopPending,Started=True状态State=StopPending,Started=True状态State=StopPending,Started=True状态State=StopPending,Started=True状态State=StopPending,Star......
  • Kubernetes Service 之原理与 ClusterIP 和 NodePort 用法
    KubernetesService之原理与ClusterIP和NodePort用法Service定义在Kubernetes中,由于Pod是有生命周期的,如果Pod重启它的IP可能会发生变化以及升级的时候会重建Pod,我们需要Service服务去动态的关联这些Pod的IP和端口,从而使我们前端用户访问不受后端变更......
  • Android14音频进阶之AAOS之CarAudioService如何衔接AudioControl服务(七十四)
    简介:CSDN博客专家,专注Android/Linux系统,分享多mic语音方案、音视频、编解码等技术,与大家一起成长!优质专栏:Audio工程师进阶系列【原创干货持续更新中……】......
  • Mybatis-plus的Service接口
    在有了实体类的基础上,创建UserInfoMapper接口,并继承BaseMapper接口publicinterfaceUserInfoMapperextendsBaseMapper<UserInfo>{}继承IService创建Service接口,并创建对应的实现类publicinterfaceUserInfoServiceextendsIService<UserInfo>{}UserInfo......
  • springcloud和dubbo分别调用controller层和service层是两种微服务架构的最大区别?
    许多讨论微服务架构中springcloud和dubbo区别的文章中,主要强调dubbo只是springcloud的子集,只是服务治理工具,不是完整解决方案。但是看了一下两者,感觉完全无法兼容,理念完全不同啊。springboot开发的典型应用目录如下:分Controller、service接口、Serviceimpl实现、dao等层次。1、s......
  • mapper,service,controller,entity之间的关系
    目录一、学到了二、错误与纠正一、学到了1.mapper(repository):数据访问层,负责与数据库进行交互,执行数据库的操作。定义了各种数据库操作方法的接口,并由ORM框架自动实现主要职能是执行数据库的增删改查,并将数据库操作结果返回给上层的service。2.service:业务逻辑层,处理逻......
  • Ubuntu 22.04 使用self-service-password搭建自主修改密码平台
    Ubuntu系统安装准备正常操作是安装成功系统,安装的时候设置好静态密码。参考官方文档:https://self-service-password.readthedocs.io/en/stable/installation.html根据文档提示安装会报错,网上查了些资料需要按照如下步骤安装依赖。正式安装vi/etc/apt/sources.list.d/ltb-p......
  • skynet.newservice简介:服务的启动
    skynet是一个轻量级的游戏服务器框架。简介在skynet的体系中,服务是一个基础概念。通常,我们使用skynet.newservice来启动一个snlua服务。那么,当我们写下localaddr=skynet.newservice("test")这行代码时,系统是怎么运作的呢?思考一下这些问题:调用skynet.newservice会不会发......
  • ASP.NET Web应用程序创建的webservice接口如何在postman里测试调用
    ASMX中的方法 启动项目浏览器展示的页面如下 点击ReceiveOrder,展示该方法的请求和响应示例 在postman中输入以下信息 选择raw--xml,粘贴浏览器中的SOAP1.1或者SOAP1.2中的请求示例 点击Send按钮发生请求 SOAP1.1以下是SOAP1.1请求和响应示例。所显示的占位......
  • Azure Service Principals ----- Azure 上最好保守的秘密的服务
    一,引言AzureServicePrincipals是AzureActiveDirectory(AAD)中的一种标识,代表应用程序,服务,自动化流程。ServicePrincipals支持各种Azure服务和资源之家的安全通信,为应用程序提供了一种进行身份验证并于AzureAPI交互的方法。在本文中,我们将探讨AzureServ......