android - 什么是 Android Binder "Transaction?"

标签 android transactions android-service ipc android-binder

在从单个 APK 运行的两个 Android 进程之间发送消息时,我收到了 TransactionTooLargeException。每条消息仅包含少量数据,much smaller than the 1 mb total (as specified in the docs) .

我创建了一个测试应用程序(下面的代码)来解决这个问题,并注意到三件事:

  1. 如果每条消息超过 200 kb,我会得到一个 android.os.TransactionTooLargeException

  2. 如果每条消息小于 200kb,我会得到一个 android.os.DeadObjectException

  3. 添加一个 Thread.sleep(1) 似乎已经解决了这个问题。我无法通过 Thread.sleep

  4. 获得任何异常

Looking through the Android C++ code ,似乎 transaction 因未知原因失败并被解释为这些异常之一

问题

  1. 什么是“交易”?
  2. 什么定义了交易中发生的事情?是在给定时间内发生了一定数量的事件吗?或者只是事件的最大数量/规模?
  3. 有没有办法“刷新”交易或等待交易完成?
  4. 避免这些错误的正确方法是什么? (注意:将其分解成更小的部分只会引发不同的异常)


代码

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.example.boundservicestest"
          xmlns:android="http://schemas.android.com/apk/res/android">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <service android:name=".BoundService" android:process=":separate"/>
    </application>

</manifest>

MainActivity.kt

class MainActivity : AppCompatActivity() {

    private lateinit var sendDataButton: Button
    private val myServiceConnection: MyServiceConnection = MyServiceConnection(this)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        myServiceConnection.bind()

        sendDataButton = findViewById(R.id.sendDataButton)

        val maxTransactionSize = 1_000_000 // i.e. 1 mb ish
        // Number of messages
        val n = 10
        // Size of each message
        val bundleSize = maxTransactionSize / n

        sendDataButton.setOnClickListener {
            (1..n).forEach { i ->
                val bundle = Bundle().apply {
                    putByteArray("array", ByteArray(bundleSize))
                }
                myServiceConnection.sendMessage(i, bundle)
                // uncommenting this line stops the exception from being thrown
//                Thread.sleep(1)
            }
        }
    }
}

MyServiceConnection.kt

class MyServiceConnection(private val context: Context) : ServiceConnection {
    private var service: Messenger? = null

    fun bind() {
        val intent = Intent(context, BoundService::class.java)
        context.bindService(intent, this, Context.BIND_AUTO_CREATE)
    }

    override fun onServiceConnected(name: ComponentName, service: IBinder) {
        val newService = Messenger(service)
        this.service = newService
    }

    override fun onServiceDisconnected(name: ComponentName?) {
        service = null
    }

    fun sendMessage(what: Int, extras: Bundle? = null) {
        val message = Message.obtain(null, what)
        message.data = extras
        service?.send(message)
    }
}

BoundService.kt

internal class BoundService : Service() {
    private val serviceMessenger = Messenger(object : Handler() {
        override fun handleMessage(message: Message) {
            Log.i("BoundService", "New Message: ${message.what}")
        }
    })

    override fun onBind(intent: Intent?): IBinder {
        Log.i("BoundService", "On Bind")
        return serviceMessenger.binder
    }
}

build.gradle*

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.boundservicestest"
        minSdkVersion 19
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:27.1.1'
}

堆栈跟踪

07-19 09:57:43.919 11492-11492/com.example.boundservicestest E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.boundservicestest, PID: 11492
    java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:448)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 
     Caused by: android.os.DeadObjectException: Transaction failed on small parcel; remote process probably died
        at android.os.BinderProxy.transactNative(Native Method)
        at android.os.BinderProxy.transact(Binder.java:764)
        at android.os.IMessenger$Stub$Proxy.send(IMessenger.java:89)
        at android.os.Messenger.send(Messenger.java:57)
        at com.example.boundservicestest.MyServiceConnection.sendMessage(MyServiceConnection.kt:32)
        at com.example.boundservicestest.MainActivity$onCreate$1.onClick(MainActivity.kt:30)
        at android.view.View.performClick(View.java:6294)
        at android.view.View$PerformClick.run(View.java:24770)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 

最佳答案

1) 什么是“交易”?

当客户端进程调用服务器进程时(在我们的例子中是 service?.send(message)),它会传输一个代表调用方法的代码以及编码数据 (Parcels) .此调用称为事务。客户端 Binder 对象调用 transact() 而服务器 Binder 对象在 onTransact() 方法中接收此调用。检查ThisThis .

2) 什么定义了交易中的内容?是在给定时间内发生了一定数量的事件吗?或者只是事件的最大数量/规模?

一般来说,它由 Binder 协议(protocol)决定。它们使用代理(由客户端)和 stub (由服务)。代理接受您的高级 Java/C++ 方法调用(请求)并将它们转换为包裹(编码)并将事务提交给 Binder 内核驱动程序和 block 。另一方面, stub (在服务进程中)监听 Binder 内核驱动程序并在收到回调后将 Parcels 解码为服务可以理解的丰富数据类型/对象。

在 Android Binder 框架的情况下,通过 transact() 发送的数据是 Parcel (这意味着我们可以发送Parcel对象支持的所有类型的数据。),存储在Binder事务缓冲区中。Binder事务缓冲区有一个有限的固定大小,目前是1Mb,由进程所有正在进行的事务共享。因此,如果每条消息超过 200 kb,则 5 个或更少的运行事务将导致超出限制并抛出 TransactionTooLargeException。因此,当有许多事务正在进行时,即使大多数单个事务的大小适中,也会抛出此异常。如果 Activity 使用在执行请求的过程中终止的另一个进程中运行的服务,该 Activity 将看到 DeadObjectException 异常。在 Android 中终止进程的原因有很多。检查this blog了解更多信息。

3) 有没有办法“刷新”交易或等待交易完成?

默认情况下,对 transact() 的调用会阻塞客户端线程(在 process1 中运行),直到 onTransact() 完成其在远程线程中的执行(在 process1 中运行) process2). 所以事务API在Android中本质上是同步的。如果你不想阻止 transact() 调用,那么你可以传递 IBinder.FLAG_ONEWAY标志(标记为 transact(int, Parcel, Parcel, int) )立即返回而不等待任何返回值。您必须为此实现自定义 IBinder 实现。

4) 避免这些错误的正确方法是什么? (注意:将其分解成更小的部分只会引发不同的异常)

  1. 限制一次交易的数量。进行真正必要的交易(一次所有正在进行的交易的消息大小必须小于 1MB)。
  2. 确保运行其他 Android 组件的进程(应用程序进程除外)必须在其中运行。

Note:- Android support Parcel to send data between different processes. A Parcel can contain both flattened data that will be unflattened on the other side of the IPC (using the various methods here for writing specific types, or the general Parcelable interface), and references to live IBinder objects that will result in the other side receiving a proxy IBinder connected with the original IBinder in the Parcel.

将服务与 Activity 绑定(bind)的正确方法是在 Activity onStart() 上绑定(bind)服务并在 onStop() 中解除绑定(bind),这是 Activity 的可见生命周期。

在您的情况下,在 MyServiceConnection 类中添加方法:-

有趣的解绑定(bind)(){ context.unbindService(这个) }

在你的 Activity 类中:-

override fun onStart() {
        super.onStart()
        myServiceConnection.bind()
    }

    override fun onStop() {
        super.onStop()
        myServiceConnection.unBind()
    }

希望对您有所帮助。

关于android - 什么是 Android Binder "Transaction?",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51425189/

相关文章:

php - 如何判断一笔交易是成功还是失败?

android - 在我的测试用例中启动服务时未调用 onStartCommand()

android - 我是否应该添加 slf4j 依赖项来实现 Sentry.io?

java - 我想知道是否从节点中删除了具有特定 ID 的项目

android - 允许除一个 child 以外的所有 child 读写

android - 在 android 中获取 GPS 服务

android - 在应用程序最小化时打开/关闭手电筒

android - Android App 中最用户友好的布局选项

.net - 为什么 NHibernate 会自动截断而不是在保存时抛出异常?

spring - 如何记录 Spring 事务内容