Android 原生 Parcel 使用

标签 android c++ native parcel

我正在使用本地代码尝试 Parcel:

#include <stdio.h>
#include <binder/IInterface.h>
#include <binder/Parcel.h>
#include <binder/IBinder.h>
#include <binder/Binder.h>
#include <binder/ProcessState.h>
#include <binder/IPCThreadState.h>
#include <binder/IServiceManager.h>

using namespace android;

int main()
{
  int32_t i = 123, j = 456;

  Parcel data;
  status_t t = data.writeInt32(j);
  if(t == NO_ERROR)
    printf("Status: %d\n", t);
  else if(t == BAD_VALUE)
    printf("Bad Value\n");

  int32_t jj = 0;
  t = data.readInt32(&jj);
  printf("t: %d\n", t);
  printf("ParcelTest: %d\n", jj);

  return 0;
}

要编译此代码,需要 Android 的源代码树。把它放在 external/ParcelTest 下。 Android.mk 是 here 。运行mmma external/ParcelTest进行编译。

程序的输出是:

generic_x86:/ # /system/bin/ParcelTest
Status: 0
t: -61
ParcelTest: 0

Status: 0 表示将值写入 Parcel 成功了。但阅读不会。所以 Parcel 是这样的,如果我按照我写的顺序读取数据,我会得到正确的结果。知道为什么此代码示例会失败吗?

最佳答案

正确的用法如下:

#include <stdio.h>
#include <binder/IInterface.h>
#include <binder/Parcel.h>
#include <binder/IBinder.h>
#include <binder/Binder.h>
#include <binder/ProcessState.h>
#include <binder/IPCThreadState.h>
#include <binder/IServiceManager.h>

using namespace android;

int main()
{
  int32_t i = 123, j = 456;

  Parcel data;
  status_t t = data.writeInt32(j);
  if(t == NO_ERROR)
    printf("Status: %d\n", t);
  else if(t == BAD_VALUE)
    printf("Bad Value\n");

  int32_t jj = 0;
  data.setDataPosition(0);
  t = data.readInt32(&jj);
  printf("t: %d\n", t);
  printf("ParcelTest: %d\n", jj);

  return 0;
}

必须手动设置读取位置。

关于Android 原生 Parcel 使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49796329/

相关文章:

android - Surfaceflinger 测试程序

ide - 如何让 IntellIJ 对项目中的所有主文件使用 JVM 选项?

android - WebGl 支持 android 和 iphone webviews

安卓 : Retrieving data from text field in pop up is throwing errors

android - 用于实例化 ViewModel 的首选 Fragment 生命周期方法

java - JNI native : java. lang.UnsatisfiedLinkError : no HelloWorld in java. 库.path

c++ - 为什么 fstream.fail() 会返回 true 或 false

c++ - 递归函数的内联

authentication - 从服务器自动访问 USB 存储中的文本文件内容

java - 从现有的 Android 项目导入自己的 Android-Studio 项目中的 Java 类