How to access android MMS resources such as video/audio etc?

别等时光非礼了梦想. 提交于 2019-12-03 09:00:30

I found a fairly simple way to read Video/Audio data from MMS, so i decided to publish this part of my class that provides MMS attachements, for all users that need this.

private static final int RAW_DATA_BLOCK_SIZE = 16384; //Set the block size used to write a ByteArrayOutputStream to byte[]
public static final int ERROR_IO_EXCEPTION = 1;
public static final int ERROR_FILE_NOT_FOUND = 2;



public static byte[] LoadRaw(Context context, Uri uri, int Error){
    InputStream inputStream = null;
    byte[] ret = new byte[0];

    //Open inputStream from the specified URI
    try {
        inputStream = context.getContentResolver().openInputStream(uri);

        //Try read from the InputStream
        if(inputStream!=null)
            ret = InputStreamToByteArray(inputStream);

    } 
    catch (FileNotFoundException e1) {
        Error = ERROR_FILE_NOT_FOUND;
    } 
    catch (IOException e) {
        Error = ERROR_IO_EXCEPTION;
    }
    finally{
        if (inputStream != null) {
            try {
                inputStream.close();
            } 
            catch (IOException e) {
                //Problem on closing stream. 
                //The return state does not change. 
                Error = ERROR_IO_EXCEPTION;
            }
        }
    }


    //Return
    return ret;
}


//Create a byte array from an open inputStream. Read blocks of RAW_DATA_BLOCK_SIZE byte
private static byte[] InputStreamToByteArray(InputStream inputStream) throws IOException{
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int nRead;
    byte[] data = new byte[RAW_DATA_BLOCK_SIZE];

    while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
      buffer.write(data, 0, nRead);
    }
    buffer.flush();
    return buffer.toByteArray();
}

In this way you can extract "Raw" data such as Audio/Video/Images from MMS by passing:

  1. the context where you need to use this function
  2. the URI of the MMS part that contains data you want to extract (for ex. "content://mms/part/2")
  3. the byref param that returns an eventual error code thrown by the procedure.

Once you have your byte[], you can create an empty File and then use a FileOutputStream to write the byte[] into it. If the file path\extension is correct and if your app has all the right permissions, you'll be able to store your data.

PS. This procedure has been tested a few times and it worked, but i don't exclude can be some unmanaged exception cases that may produce error states. IMHO it can be improoved too...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!