Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Getting MMS from an Android Device programmatically

    • 0
    • 2
    • 0
    • 2
    • 0
    • 0
    • 0
    • 0
    • 2.08k
    Comment on it

    To get MMS conversation from an Android device, use the following code:

    ContentResolver contentResolver = getActivity().getContentResolver(); 
    Uri uri = Uri.parse("content://mms");
    Cursor cursor = contentResolver.query(uri, null, "thread_id IS NOT NULL) GROUP BY (thread_id", null, null);
    

    We can get threadId of a particular MMS conversation as follows:

    int threadId =  cursor.getInt(1)
    

    By using this thread_id, we can get MMS snippets for a particular MMS conversation as follows:

    ContentResolver contentResolver = getActivity().getContentResolver();
        String[] projection = new String[] { "_id","thread_id","date", "m_type" };  
        Uri uri = Uri.parse("content://mms");
        Cursor cursor1 = contentResolver.query(uri, projection, "thread_id=?", new String[]{threadId}, null);
    

    After getting MMS, we will us the following code to extract the details of MMS:

    if(cursor != null)
        {
            StringBuilder smsBuilder = new StringBuilder();
            while(cursor1.moveToNext())
            {
                String body = null;
                Bitmap bitmap = null;
                // implementation of this method is below
                String address = getANumber(cursor.getInt(cursor1.getColumnIndex ("_id")));
                String name = null;
                String photoUri = null;
                String date = new SimpleDateFormat("MM/dd/yyyy", Locale.getDefault()).format(new Date(cursor1.getLong(cursor.getColumnIndex("date"))*1000));
                ServerUrl.sendLog("dateString: "+date);
                if (address.length() > 0) {
    
                    // implementation of this method is below
                    String[] contactData = getContactByNumber(address);
                    if (contactData != null) {
                        name = contactData[0];
                        if (contactData[1] != null)
                            photoUri = contactData[1];
                    }
                } else
                    address = null;
                int int_Type = cursor1.getInt(cursor1.getColumnIndexOrThrow("m_type"));
    
                // Get details of MMS(content of MMS)
                String selectionPart = new String ("mid = '" + cursor1.getString(0) + "'");
                Cursor curPart = getActivity().getContentResolver (). query (Uri.parse ("content://mms/part"), null, selectionPart, null, null);
    
                while(curPart.moveToNext())
                {
                    if(curPart.getString(3).equals("image/jpeg"))
                    {
                        // implementation of this method is below
                        bitmap = getMmsImage(curPart.getString(0));
                    }
                    else if ("text/plain".equals(curPart.getString(3))) {
                        String data = curPart.getString(curPart.getColumnIndex("_data"));
    
                        if (data != null) {
                            // implementation of this method below
                            body = getMmsText(curPart.getString(0));
                        } else {
                            body = curPart.getString(curPart.getColumnIndex("text"));
                        }
                    }
    
                }
    
                curPart.close();
                tempSMS.setMessageBody(body);
                tempSMS.setBitmap(bitmap);
                smsBuilder.append("[ ");  
    
                smsBuilder.append(address + ", ");  
                smsBuilder.append(date + ", ");  
                smsBuilder.append(name + ", ");  
                smsBuilder.append(photoUri+ ", ");  
                smsBuilder.append(bitmap + ", ");  
                smsBuilder.append(int_Type + ", ");  
                smsBuilder.append(body);  
                smsBuilder.append(" ]\n\n"); 
                smsList.add(tempSMS);
            }
            cursor1.close();
            ServerUrl.sendLog(smsBuilder.toString());
        }
    

    Get sender number by contact id:

    /**
     * Get Sender number
     * 
     * @param id
     * @return
     */
    private String getANumber(int id) {
        String add = "";
        final String[] projection = new String[] {"address","contact_id","charset","type"};
        Uri.Builder builder = Uri.parse("content://mms").buildUpon();
        builder.appendPath(String.valueOf(id)).appendPath("addr");
    
        Cursor cursor = activity.getContentResolver().query(
                builder.build(),
                projection,
                null,
                null, null);
    
        if (cursor.moveToFirst()) {
    
            add = cursor.getString(cursor.getColumnIndex("address"));
        }
    
        return add;
    }
    

    Get contact details by contact number:

    /**
     * Get Contact Name by Contact Number
     * @param number
     * @return 
     */
    private String[] getContactByNumber(final String number) {
        String[] data = new String[2];
    
        try {
    
            Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
                    Uri.encode(number));
    
            Cursor cur = activity.getContentResolver().query(uri,
                    new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID },
                    null, null, null);
    
            if (cur.moveToFirst()) {
                int nameIdx = cur.getColumnIndex(PhoneLookup.DISPLAY_NAME);
                data[0] = cur.getString(nameIdx);
    
                String contactId = cur.getString(cur
                        .getColumnIndex(PhoneLookup._ID));
    
                String photoUri = getContactPhotoUri(Long.parseLong(contactId));
    
                if (photoUri != null)
                    data[1] = photoUri;
                else
                    data[1] = null;
    
                cur.close();
                return data;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    
    }
    
    /**
     * Get contact photo URI from contact Id
     * @param contactId
     * @return imagePath
     */
    private String getContactPhotoUri(long contactId) {
    
        Uri photoUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,
                contactId);
    
        String imagePath = null ;
        if(photoUri != null)
        {
            imagePath = photoUri.toString() ;
        }
        return imagePath;
    
    }
    

    Get MMS image part content:

    /**
     * Get MMS image part
     * 
     * @param _id
     * @return
     */
    private String getMmsImage(String _id) {
        Uri partURI = Uri.parse("content://mms/part/" + _id);
        InputStream is = null;
        try {
    
            return partURI.toString();
        } catch (OutOfMemoryError e) 
        {
            e.printStackTrace();
        }
        finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();}
            }
        }
    
        return null;
    }
    

    Get MMS text part content:

    /**
     * Get MMS text content
     * 
     * @param id
     * @return
     */
    private String getMmsText(String id) {
        Uri partURI = Uri.parse("content://mms/part/" + id);
        InputStream is = null;
        StringBuilder sb = new StringBuilder();
        try {
            is = activity.getContentResolver().openInputStream(partURI);
            if (is != null) {
                InputStreamReader isr = new InputStreamReader(is, "UTF-8");
                BufferedReader reader = new BufferedReader(isr);
                String temp = reader.readLine();
                while (temp != null) {
                    sb.append(temp);
                    temp = reader.readLine();
                }
            }
        } catch (IOException e) {}
        finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {}
            }
        }
        return sb.toString();
    }
    

    Required permissions in AndroidManifest.xml:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    

    Please share the experiences you had while getting MMS from an Android device as this will help other people who read the post.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: