【问题标题】:Android native Parcel usageAndroid 原生 Parcel 使用
【发布时间】:2018-04-12 12:17:51
【问题描述】:

我正在尝试使用本机代码的 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 就是如果我按照我写的顺序读取数据,我会得到正确的结果。知道为什么此代码示例会失败吗?

【问题讨论】:

    标签: android c++ native parcel


    【解决方案1】:

    正确用法如下:

    #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;
    }
    

    必须手动设置读取位置。

    【讨论】:

      猜你喜欢
      • 2015-02-21
      • 1970-01-01
      • 2012-03-12
      • 2013-09-28
      • 1970-01-01
      • 2017-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多