Android Service 的一个细节

Service 的一个细节

这篇文章对 Service 的使用过程中的一个细节整理一下。

首先,开发者大多知道的是:

从 Android 5(API 21)开始,对于 Service 的启动(bind 方式,start 方式),google 官方文档提出建议使用 Intent 显示启动 Service,即明确设置 Service 的子类型。在 manifest 文件中的 <service> 标签不再设置 <intent-filter> 标签。

这是出于性能和安全性的考虑。

  • Service 的隐式启动需要依赖系统解析和匹配,这样可能导致解析并匹配到相同的 action。这样在使用过程中,系统会弹出对话框提示用户作选择。这样的体验不利于 app 的使用,也可能导致异常的结果。更有可能被恶意 app 匹配到并截胡数据,从而对 app 造成安全风险。

  • 性能上,显示设置 Service 子类型可以快速地,精确地启动实现类。无需经过系统的匹配过程。

简单示例

kotlin 复制代码
// 启动代码
private val _servConn = object : ServiceConnection {
    override fun onServiceConnected(
        name: ComponentName?,
        service: IBinder?
    ) {
        Log.d("VM", "onServiceConnected: name=$name, service=$service")
    }

    override fun onServiceDisconnected(name: ComponentName?) {
        Log.i("VM", "onServiceDisconnected: name=$name")
    }
}

fun bindService(context: Context) {
    val intent = Intent().apply {
        setAction("com.sanren1024.action.access")
        setClass(context, Class.forName("com.sanren1024.remote.MyService"))
    }
    val result = context.bindService(intent, _servConn, Context.BIND_AUTO_CREATE)
    Log.d("VM", "bindService: Bind_Result=$result")
}

// MyService.kt
class MyService : Service() {
    override fun onCreate() {
        super.onCreate()
        Log.i("MyService", "onCreate")
    }

    override fun onBind(intent: Intent): IBinder? {
        Log.i("MyService", "onBind=$intent")
        return null
    }
}

// manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />

    <application>
        <service
            android:name=".MyService"
            android:enabled="true"
            android:process=":serv_process"
            android:foregroundServiceType="connectedDevice|dataSync"
            android:exported="false"/>
    </application>
</manifest>

上述代码中,

  1. bindService 方法显示启动 MyService
  2. manifest 文件中不设置 <intent-filter>
  3. ServiceonBind 方法返回 null

执行上述程序,在 log 信息的结果

复制代码
D VM: bindService: Bind_Result=true
I MyService: onCreate
I MyService: onBind=Intent { act=com.sanren1024.action.access cmp=com.sanren1024.tools/com.sanren1024.remote.MyService }
  1. bindService 的执行结果是 true,找到了正确的 service。
  2. onBind 方法正确执行。
  3. ServiceConnection 的回调实现方法没有被调用。------ 有意思的地方

为何 service 绑定成功了,但 ServiceConnection 的回调实现不被调用呢? ===> 问题原因就在 Service#onBind(Intent) 回调方法中,由于返回值是 null,导致 client 想要取得 server 端的 binder 引用失败。

这个过程与网络请求过程建立连接类似:

client 向 server 发送建立连接请求,请求发送成功(bindService 返回 true),等待进一步结果。但最后等待超时,无响应结果。

在 server 端定义一个 aidl 接口且作实现。在 Service 子类型的 onBind(Intent) 中匹配 Intent 的 action,返回 aidl 接口实现类。

kotlin 复制代码
override fun onBind(intent: Intent): IBinder? {
    Log.i("MyService", "onBind=$intent")
    when (intent.action) {
        "com.sanren1024.action.access" -> {
            return AccessServletImpl()
        }
    }
    return null
}

再次执行上述程序,在 log 信息中 ServiceConnnection 的回调实现的 log 信息正确打印了。

相关推荐
安卓蓝牙Vincent3 小时前
《Android BLE ScanSettings 完全解析:从参数到实战》
android
江上清风山间明月3 小时前
LOCAL_STATIC_ANDROID_LIBRARIES的作用
android·静态库·static_android
三少爷的鞋4 小时前
Android 中 `runBlocking` 其实只有一种使用场景
android
应用市场6 小时前
PHP microtime()函数精度问题深度解析与解决方案
android·开发语言·php
沐怡旸7 小时前
【Android】Dalvik 对比 ART
android·面试
消失的旧时光-19438 小时前
Android NDK 完全学习指南:从入门到精通
android
消失的旧时光-19438 小时前
Kotlin 协程实践:深入理解 SupervisorJob、CoroutineScope、Dispatcher 与取消机制
android·开发语言·kotlin
2501_915921438 小时前
iOS 26 描述文件管理与开发环境配置 多工具协作的实战指南
android·macos·ios·小程序·uni-app·cocoa·iphone
2501_915909068 小时前
iOS 抓包实战 从原理到复现、定位与真机取证全流程
android·ios·小程序·https·uni-app·iphone·webview