I’m new to android. I can’t seem to find pertinent forum posts.
What has me stumped is that allocateDirect() does create the backing byte[] in Android 4.2 emulator.
More specifically, I allocate a ByteBuffer, and call buffer.put(byte[]) several times to write the contents of the ByteBuffer. I then want to hand off the backing byte[] for compression. It’s accessing the backing byte[] that throws the UnsupportedOperationException.
Here’s the resulting buffer contents just after writing when running the Android 2.2 emulator:

Here’s the resulting buffer contents just after writing when running the Android 4.2 emulator:

The difference seems to be in whether bufferRef.block is created (it’s created when the ByteBuffer is allocated in the Android 4.2 emulator). I would prefer to always use a direct ByteBuffer. As a workaround, I check to see whether I have access to the backing byte[], and if not, re-allocate using ByteBuffer.allocate(size).
ByteBuffer buf;
try {
buf = ByteBuffer.allocateDirect(this.maxBufferSize);
if(!buf.hasArray()) { //some API levels either don't expose or create the backing byte[]
buf = null;
buf = ByteBuffer.allocate(this.maxBufferSize);
}
} catch (Exception e) {
return false;
}
So, my question is, is there a way to guarantee a direct byte buffer will always have a backing byte[] (assuming enough memory)? Or do I have to live with this workaround?
Environment:
ADT Build: v21.0.0-519525
Android 2.2 emulator config:
Updated AVD ‘AVD_for_Galaxy_Nexus_by_Google’ based on Android 2.2, ARM (armeabi) processor,
[2012-12-20 10:09:34 – SDK Manager] with the following hardware config:
[2012-12-20 10:09:34 – SDK Manager] hw.sdCard=no
[2012-12-20 10:09:34 – SDK Manager] hw.device.manufacturer=Google
[2012-12-20 10:09:34 – SDK Manager] hw.mainKeys=no
[2012-12-20 10:09:34 – SDK Manager] hw.lcd.density=320
[2012-12-20 10:09:34 – SDK Manager] hw.accelerometer=yes
[2012-12-20 10:09:34 – SDK Manager] hw.dPad=no
[2012-12-20 10:09:34 – SDK Manager] hw.device.hash=-708107041
[2012-12-20 10:09:34 – SDK Manager] hw.trackBall=no
[2012-12-20 10:09:34 – SDK Manager] hw.device.name=Galaxy Nexus
[2012-12-20 10:09:34 – SDK Manager] hw.camera.back=none
[2012-12-20 10:09:34 – SDK Manager] hw.sensors.proximity=yes
[2012-12-20 10:09:34 – SDK Manager] hw.battery=yes
[2012-12-20 10:09:34 – SDK Manager] disk.dataPartition.size=200M
[2012-12-20 10:09:34 – SDK Manager] hw.audioInput=yes
[2012-12-20 10:09:34 – SDK Manager] hw.sensors.orientation=yes
[2012-12-20 10:09:34 – SDK Manager] hw.camera.front=none
[2012-12-20 10:09:34 – SDK Manager] hw.gps=yes
[2012-12-20 10:09:34 – SDK Manager] skin.dynamic=no
[2012-12-20 10:09:34 – SDK Manager] hw.keyboard=yes
[2012-12-20 10:09:34 – SDK Manager] vm.heapSize=64
[2012-12-20 10:09:34 – SDK Manager] hw.ramSize=512
There is no byte buffer for Android 2.2. The buffer is optional. It was implemented in later releases.