Write file on sdcard from AudioSystem (C++ code) in Android 5.0.1_r1

704 Views Asked by At

I am trying to write a file in the sdcard of an Android device from AudioSystem.cpp. This is a service in the Android Framework. I am modifying the source code.

I am using the following code:

    int fd = open("/sdcard/file.txt", O_RDWR | O_APPEND | O_CREAT, 0666); 
    if(fd > -1) { 
     __android_log_print(ANDROID_LOG_DEBUG, "gxp18", "Writing to SDCARD");
         write(fd, "1", strlen("1")); 
         write(fd, "\n", 1); 
         close(fd); 
    } 
    else __android_log_print(ANDROID_LOG_DEBUG, "gxp18", "ERROR while writing to SDCARD fd = %d", fd);

By running the code I always get fd = -1

The original code is the following:

status_t AudioSystem::startInput(audio_io_handle_t input,
                                 audio_session_t session)
{
    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();

    if (aps == 0) return PERMISSION_DENIED;
    return aps->startInput(input, session);
}

The modified one is:

status_t AudioSystem::startInput(audio_io_handle_t input,
                                 audio_session_t session)
{
    const sp<IAudioPolicyService>& aps = AudioSystem::get_audio_policy_service();

    /* start */

    int fd = open("/sdcard/file.txt", O_RDWR | O_APPEND | O_CREAT, 0666); 
    if(fd > -1) { 
     __android_log_print(ANDROID_LOG_DEBUG, "gxp18", "Writing to SDCARD");
         write(fd, "1", strlen("1")); 
         write(fd, "\n", 1); 
         close(fd); 
    } 
    else __android_log_print(ANDROID_LOG_DEBUG, "gxp18", "ERROR while writing to SDCARD fd = %d", fd);

    /* end */

    if (aps == 0) return PERMISSION_DENIED;
    return aps->startInput(input, session);
}
1

There are 1 best solutions below

1
EyalBellisha On

Try writing to /storage/emulated/0/file.txt Since JB the storage Dir has changed a bit. I am assuming you're doing so from a system service