tags:

views:

386

answers:

1

Is there a way to get system file descriptor (socket or file number as int) from Android's FileDescriptor object? I'd like to access file descriptor directly in JNI code without using any Java wrappers.

Edit: I've found getParcelFileDescriptorFD and that FileDescriptor has int field named "descriptor", example usage in media/jni/android_media_MediaPlayer.cpp; func definition is in frameworks/base/core/jni/android_util_Binder.cpp; field itself is in libcore/luni/src/main/java/java/io/FileDescriptor.java (http://3.ly/l8O)

But this is not part of official documented API. Is there a documented "right" way to do that?

A: 

native code in dalvik/libcore/ uses jniGetFDFromFileDescriptor in "java_io_FileDescriptor.c" but you shouldn't call it yourself because it's not stable API. you could copy & paste that code, but you really want to think twice before doing so. using JNI to access implementation details is just begging for your code to be accidentally broken in future!

better choices are:

  1. keep the I/O on the Java side if you can.

  2. if you do have to do I/O on the native side (as in the case of the media player) keep the I/O on the native side: call open(2) or whatever on that side, keep the fd as an int rather than messing with a FileDescriptor object, and if you pass anything back to Java pass the int or your own object (with no intention of it being used for anything except passing back down to your native code).

those two choices work today, and can't be accidentally broken by changes to Android's implementation details that you have no control over.

Elliott Hughes
Thanks for answer, but it doesn't really help me :)I'm perfectly aware using internal implementation details is bad, but I've no other way to do it currently - all I have is FileDescriptor due to how Android works (it comes from ContentResolver). I wish I could do I/O on Java side, but there seems to be no way turn FD into RandomAccessFile or equivalent - I can only make "one-way" InputStream from FD but I need to use seek() in my code (skip() doesn't do the job).I've went with FileDescriptor.descriptor for now (like android_media_MediaPlayer.cpp does) until there's a better way.
maciej
it would be worth filing a bug in Sun's bug database that RandomAccessFile should have a constructor that takes a FileDescriptor, and then filing a bug in Android's bug database referencing the Sun bug.
Elliott Hughes