将ByteBuffer放入Bundle中

时间:2015-06-11 03:25:44

标签: java android

我正在使用一些我无法控制的代码,而我正在使用的ByteBuffer会传递给本机方法。我无权访问本机代码,但它希望“buf”是ByteBuffer。另请注意,代码实际上没有任何意义,但有很多,所以我将其提炼为问题。

        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();

            if (id == android.R.id.home) {

                Intent i = new Intent(MainListActivity.this, MainActivity.class);
                startActivity(i);
                finish();
            }
            return super.onOptionsItemSelected(item);
        }

这是我的代码:

public class otherClass {
    public final void setParams(Bundle params) {
            final String key = params.keySet()[0];
        Object buf = params.get(key));
        nativeSet(key, buf);
    }

    private native final void nativeSet(key, buf);
}

问题? Bundle中没有putByteBuffer方法。看起来很奇怪有一个get()返回一个对象,但没有泛型put()。

但对我来说更奇怪的是本机代码想要一个ByteBuffer。当它从Java层传递时,它不会有一堆元数据吗?本机层中的代码可以预测元数据并从ByteBuffer中提取吗?

有没有办法在这里可靠地传递ByteBuffer?它可能有点hacky。我想也许我可以弄清楚ByteBuffer对象的位数,转换为整数,并使用putInt()。不知道如何从ByteBuffer对象转到原始数据。

1 个答案:

答案 0 :(得分:0)

假设这应该有效。将字节缓冲区转换为字符串并将其传递到您的包中,如下所示:

byte[] bytes = myBuffer.getBytes( Charset.forName("UTF-8" ));
String byteString = new String( bytes, Charset.forName("UTF-8") );
myBundle.putString("param", byteString);

然后从字符串重构bytebuffer:

byte[] byteArray = byteString.getBytes();
ByteBuffer byteBuffer = ByteBuffer.allocate(byteArray.length + 8);
byteBuffer.put(byteArray);
相关问题