FileDescriptor's actual system file descriptor (as int) in Android

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/

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

Asked by: Anna598 | Posted: 25-01-2022

Answer 1

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.

Answered by: Sophia140 | Posted: 26-02-2022

Similar questions

Still can't find your answer? Check out these communities...

Android Google Support | Android Community | Android Community (Facebook) | Android