Problem: Fetch Inbox SMS programatically
Description:
In this tutorial, I just have fetched SMS from the Inbox and displayed inside the ListView. SMS is fetched inside the ArrayList and then using this arraylist, I have created ArrayAdapter. Now just set this adapter to the ListView, that’s it.
Now, We can fetch the SMS from Inbox by making query to SMS content resolver by using:
Uri uriSms = Uri.parse("content://sms/inbox"); Cursor cursor = getContentResolver().query(uriSms, new String[]{"_id", "address", "date", "body"},null,null,null);</pre>
Note: Don’t forget to add READ_SMS permission inside the AndroidManifest.xml file:
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
Solution:
SMSInboxActivity.java
package com.pareshmayani.smsinbox; import java.util.ArrayList; import android.app.Activity; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; /** * @author Paresh N. Mayani * (w): https://technotalkative.com/ */ public class SMSInboxActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ListView lViewSMS = (ListView) findViewById(R.id.listViewSMS); if(fetchInbox()!=null) { ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, fetchInbox()); lViewSMS.setAdapter(adapter); } } public ArrayList fetchInbox() { ArrayList sms = new ArrayList(); Uri uriSms = Uri.parse("content://sms/inbox"); Cursor cursor = getContentResolver().query(uriSms, new String[]{"_id", "address", "date", "body"},null,null,null); cursor.moveToFirst(); while (cursor.moveToNext()) { String address = cursor.getString(1); String body = cursor.getString(3); System.out.println("======> Mobile number => "+address); System.out.println("=====> SMS Text => "+body); sms.add("Address=> "+address+"n SMS => "+body); } return sms; } }
main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ListView android:id="@+id/listViewSMS" android:layout_width="fill_parent" android:layout_height="fill_parent" > </ListView> </LinearLayout>
Download this Example: Android – Fetch Inbox SMS.