Get data from sent SMS - android

I try to retrieve the data each time the Android sends SMS.
Data form:
destination phone number
delivery time
SMS body
Anyone knows how?

Get sms in sent box.
public List<SmsRep> getOutboxSms()
{
if(null == context)
{
return new ArrayList<SmsRep>();
}
Uri uriSms = Uri.parse("content://sms/sent");
Cursor cursor = context.getContentResolver().query(uriSms, null,null,null,null);
List<SmsRep> outboxSms = cursor2SmsArray(cursor);
if(!cursor.isClosed())
{
cursor.close();
}
return outboxSms;
}
And the method to handle data in sent box:
public static List<SmsRep> cursor2SmsArray(Cursor cursor)
{
if(null == cursor || 0 == cursor.getCount())
{
return new ArrayList<SmsRep>();
}
List<SmsRep> messages = new ArrayList<SmsRep>();
try
{
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
{
SmsRep singleSms = new SmsRep();
singleSms.id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
singleSms.address = cursor.getString(cursor.getColumnIndexOrThrow("address"));
singleSms.timestamp = cursor.getLong(cursor.getColumnIndexOrThrow("date")) / 1000; //### the sent time
singleSms.type = cursor.getInt(cursor.getColumnIndexOrThrow("type"));
singleSms.protocol = cursor.getInt(cursor.getColumnIndexOrThrow("protocol"));
/*
String smsSubject = cursor.getString(cursor.getColumnIndex("subject"));
byte[] subjByts = smsSubject.getBytes("UTF8");
singleSms.subject = new String(subjByts, "UTF8");
*/
String smsBody = cursor.getString(cursor.getColumnIndexOrThrow("body")); //### body
byte[] bodyBytes = smsBody.getBytes("UTF8");
singleSms.body = TextUtils.htmlEncode(new String(bodyBytes, "UTF8")); //escape,handle '='
singleSms.deviceId = deviceId;
//singleSms.body = cursor.getString(cursor.getColumnIndexOrThrow("body"));
messages.add(singleSms);
}
}
catch (Exception e)
{
Log.e(TAG, e.getMessage());
}
finally
{
cursor.close();
}
return messages;
}
Definition of SmsRep:
public class SmsRep
{
static String separator ;
public int id;
public String address;
public long timestamp;
public int type;
public int protocol;
public String subject;
public String body;
public String deviceId;
public SmsRep()
{
// do nothing in ctor
}
}
Is this what you want ?:)

There is nothing in the Android SDK for this, sorry.

We can get notified when you receive a SMS, but there is no way to get notified when a SMS is sent.

Uri uriSMS = Uri.parse("content://sms/sent");
Cursor cur = getActivity().getContentResolver().query(uriSMS , null, null, null, null);
Cursor messagesCursor = getActivity().getContentResolver().query(uriSMS , new String[]{"_id", "address", "body", "person", "date",}, null, null, null);
if(messagesCursor.getCount() > 0) {
try {
while (messagesCursor.moveToNext())
{
int x=messagesCursor.getInt(messagesCursor.getColumnIndex("_id"));
String address=messagesCursor.getString(messagesCursor.getColumnIndex("address"));
String body=messagesCursor.getString(messagesCursor.getColumnIndex("body"));
String person=messagesCursor.getString(messagesCursor.getColumnIndex("person"));
String date_=messagesCursor.getString(messagesCursor.getColumnIndex("date"));
}
}
catch(Exception ex)
{
}
}

Related

Contacts Update to DB Not working with ContentObserver

I am working with an Android application which shows the list of contacts in the phone like Whats-app. I am successful with getting the contacts to the Application database. When I try to update my DB when a contact is newly added/edited/deleted using Content Observer, I mainly face two problems
1. When Calls ,
String contactName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
I am getting wrong name. eg:- I edited Samuel's Contact no but checking the above code getting David's name.
when I try to get contact number by using the code,
contactNumber = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
I am getting error
E/CursorWindow: Failed to read row 0, column -1 from a CursorWindow which has 402 rows, 41 columns.
03-01 17:16:56.546 3660-3660/com.xxxxxxxxx.xxxxx W/System.err: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Please Anybody help me to find the solution.
Here is my Code
public class ContactObserver extends ContentObserver {
Intent i;
private static final String TAG = "ObserverReceiver";
private Context context;
BaseActivity mBaseActivity;
public ContactObserver(Handler handler, BaseActivity context) {
super(handler);
this.mBaseActivity = context;
this.context = context;
}
public ContactObserver() {
super(null);
}
#Override
public boolean deliverSelfNotifications() {
return true;
}
#Override
public void onChange(boolean selfChange, Uri uri) {
super.onChange(selfChange, uri);
if (!selfChange) {
try {
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
Log.d(TAG, "Observer has been started..");
// Contacts Cursor
final Cursor cur = context.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
// Check which contact is added or updated
if (cur != null) {
while (cur.moveToNext()) {
// Get contact added/updated timestamp but CONTACT_LAST_UPDATED_TIMESTAMP
// Get new/updated contact detail here
final String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
final String contactName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String contactNumber = null;
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
try {
contactNumber = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
} catch (Exception e) {
e.printStackTrace();
}
}
String finalContactNumber = contactNumber;
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
List<Contacts> sContacts = ContactDatabase
.getDatabase(context)
.contactsDao()
.getBySystemid(id);
Log.i("Contacts1+", new Gson().toJson(sContacts));
if (sContacts.size() > 0) {
for (Contacts mContacts : sContacts) {
String phone = finalContactNumber;
if (phone == null) {
phone = mContacts.getPhone();
}
Log.i("Contacts1+", contactName + " : " + phone);
if (phone != null && phone.length() > 0) {
phone = phone.replace(" ", "");
}
while (String.valueOf(phone.charAt(0)).equals("0")) {
String num = "";
for (int i = 1; i < phone.length(); i++) {
num = num + phone.charAt(i);
}
phone = num;
}
if (phone.length() == 10) {
phone = getSharedPreference(AppConstants.SharedKey.COUNTRY_CODE) + phone;
}
if ((mContacts.getName() != contactName || mContacts.getPhone() != phone)) {
mContacts.setName(contactName);
if (!mContacts.getPhone().equalsIgnoreCase(phone)) {
mContacts.setPhone(phone);
mContacts.setIslisted("false");
}
if (mContacts.getPhone().equalsIgnoreCase(phone) || mContacts.getName().equalsIgnoreCase(contactName)) {
ContactDatabase.getDatabase(context)
.contactsDao()
.update(mContacts);
cur.close();
}
}
}
} else {
Contacts mContacts = new Contacts();
String contactNumber = null;
try {
contactNumber = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (contactNumber != null && contactNumber.length() > 0) {
contactNumber = contactNumber.replace(" ", "");
contactNumber = contactNumber.replace("-", "");
}
while (String.valueOf(contactNumber.charAt(0)).equals("0")) {
String num = "";
for (int i = 1; i < contactNumber.length(); i++) {
num = num + contactNumber.charAt(i);
}
contactNumber = num;
}
if (contactNumber.length() == 10) {
contactNumber = getSharedPreference(AppConstants.SharedKey.COUNTRY_CODE) + contactNumber;
}
String contactName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
mContacts.setPhone(contactNumber);
mContacts.setName(contactName);
mContacts.setSystemid(id);
mContacts.setIslisted("false");
List<Contacts> cContacts = ContactDatabase
.getDatabase(context)
.contactsDao()
.getbyPhone(contactNumber);
if (cContacts.size() == 0) {
ContactDatabase.getDatabase(context)
.contactsDao()
.insert(mContacts);
}
} catch (Exception e) {
e.printStackTrace();
}
}
i = new Intent(context, ContactSynchService.class);
context.startService(i);
cur.close();
}
});
thread.start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public String getSharedPreference(String key) {
SharedPreferences prefs = mBaseActivity.getSharedPreferences(AppConstants.SHARED_KEY, MODE_PRIVATE);
return prefs.getString(key, "DEFAULT");
}
}
I tried these links, but none of them could give a solution.
ContentObserver for contact update manually
ContentObserver not working in android
Android: ContentObserver not working in android 4.3
Any help will be appreciated. Thanks in Advance

Unable to fetch SMS which having text in address

I am trying to fetch SMS's which start with TM-,ID-, AX-, AD- but I am getting sms's only which having number.
I am not able to receive any sms which will have text in address.
Here is my code :
Uri uriSms = Uri.parse("content://sms/inbox");
String[] projection = new String[]{"_id", "address", "date", "body", "person", "type"};
m_SMSCursor =context.getContentResolver().query(uriSms, projection, null,null,null);
if(m_SMSCursor.moveToFirst())
{
// Read each row from cursor and store it into the database
do {
// Extract fields from cursor
final String number = m_SMSCursor.getString(1);
final long date = m_SMSCursor.getLong(2);
final String body = m_SMSCursor.getString(3);
final String person = m_SMSCursor.getString(4);
final int type = m_SMSCursor.getInt(5);
try {
// Insert call log into database
long l;
new Thread(new Runnable() {
#Override
public void run() {
// create object for CallLogAdapter
SMSDataAdapter objSmsDataAdapter = new SMSDataAdapter(
context);
// open the database
objSmsDataAdapter = objSmsDataAdapter.Open();
try {
boolean isVMPresent = number.startsWith("VM-");
boolean isLMPresent = number.startsWith("LM-");
boolean isTMPresent = number.startsWith("TM-");
boolean isVKPresent = number.startsWith("VK-");
boolean isIXPresent = number.startsWith("IX-");
boolean isADPresent = number.startsWith("AD-");
boolean isAXPresent = number.startsWith("AX-");
boolean isBWPresent = number.startsWith("BW-");
boolean isIDPresent = number.startsWith("ID-");
boolean isIMPresent = number.startsWith("IM-");
Log.i(TAG, "Number1 : " + number + " body1 : " + body + " peron : " + person + " type : " + type);
if (isVMPresent || isLMPresent || isTMPresent || isVKPresent || isIXPresent || isADPresent || isAXPresent || isBWPresent || isIDPresent || isIMPresent) {
long lNumberOfEntry = objSmsDataAdapter.Insert(number, body, date, DATA_NOT_ANALYZED);
}
} catch (SQLException e1) {
} finally {
// Close the database
objSmsDataAdapter.Close();
}
}
}).start();
} catch (SQLException e) {
return FAILURE;
}
} while (m_SMSCursor.moveToNext());
}
But I am able to fetch all sms except which having text in address. I am able fetch sms's which having number in address.
Please give me hint or reference.
Use this method to get all data in a list first and then access the number by smsList.getNumber()
List<SMSData> smsList = new ArrayList<SMSData>();
Uri uri = Uri.parse("content://sms/inbox");
Cursor c= getContentResolver().query(uri, null, null ,null,null);
startManagingCursor(c);
// Read the sms data and store it in the list
if(c.moveToFirst()) {
for(int i=0; i < c.getCount(); i++) {
SMSData sms = new SMSData();
sms.setBody(c.getString(c.getColumnIndexOrThrow("body")).toString());
sms.setNumber(c.getString(c.getColumnIndexOrThrow("address")).toString());
smsList.add(sms);
c.moveToNext();
}
}
c.close();
SMSData:
public class SMSData {
// Number from witch the sms was send
private String number;
// SMS text body
private String body;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}

Cannot get sent sms (text messages) from device

I would like to get all the sent sms (text messages) from a device.
I can get all of them from the inbox with:
public List<SMS> getAllInboxSMS(Context ctx) {
List<SMS> inboxSMSList = new ArrayList<>();
try {
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor c = ctx.getContentResolver().query(uriSms, new String[]{"_id", "thread_id", "address", "person", "date", "body"}, "read=0", null, null);
if (c != null && c.moveToFirst()) {
do {
inboxSMSList.add(new SMS(c));
} while (c.moveToNext());
}
} catch (Exception e) {
Log.e("getAllInboxSMS", e.toString());
}
Log.i("inbox", "size: " + inboxSMSList.size());
Log.i("inbox", inboxSMSList.toString());
return inboxSMSList;
}
However if I modify
Uri.parse("content://sms/inbox");
to
Uri.parse("content://sms/sent");
The returned list size is 0.
I tried to set the app as default sms app but it doesn't work in that way either.
I work on Lollipop (Android 5).
Please help if you can.
To read all messages for inbox or sent programmatically in Android use following function.
public List<Sms> getAllSms(String folderName) {
List<Sms> lstSms = new ArrayList<Sms>();
Sms objSms = new Sms();
Uri message = Uri.parse("content://sms/"+folderName);
ContentResolver cr = mActivity.getContentResolver();
Cursor c = cr.query(message, null, null, null, null);
mActivity.startManagingCursor(c);
int totalSMS = c.getCount();
if (c.moveToFirst()) {
for (int i = 0; i < totalSMS; i++) {
objSms = new Sms();
objSms.setId(c.getString(c.getColumnIndexOrThrow("_id")));
objSms.setAddress(c.getString(c
.getColumnIndexOrThrow("address")));
objSms.setMsg(c.getString(c.getColumnIndexOrThrow("body")));
objSms.setReadState(c.getString(c.getColumnIndex("read")));
objSms.setTime(c.getString(c.getColumnIndexOrThrow("date")));
lstSms.add(objSms);
c.moveToNext();
}
}
// else {
// throw new RuntimeException("You have no SMS in " + folderName);
// }
c.close();
return lstSms;}
Call above function to get all messages from inbox or send folder.
getAllSms("inbox"); // Get all sms from inbox
getAllSms("sent"); // Get all sms from sent
To get all sms from inbox or sent folder use following function
public List<Sms> getAllSms() {
List<Sms> lstSms = new ArrayList<Sms>();
Sms objSms = new Sms();
Uri message = Uri.parse("content://sms/");
ContentResolver cr = mActivity.getContentResolver();
Cursor c = cr.query(message, null, null, null, null);
mActivity.startManagingCursor(c);
int totalSMS = c.getCount();
if (c.moveToFirst()) {
for (int i = 0; i < totalSMS; i++) {
objSms = new Sms();
objSms.setId(c.getString(c.getColumnIndexOrThrow("_id")));
objSms.setAddress(c.getString(c
.getColumnIndexOrThrow("address")));
objSms.setMsg(c.getString(c.getColumnIndexOrThrow("body")));
objSms.setReadState(c.getString(c.getColumnIndex("read")));
objSms.setTime(c.getString(c.getColumnIndexOrThrow("date")));
if (c.getString(c.getColumnIndexOrThrow("type")).contains("1")) {
objSms.setFolderName("inbox");
} else {
objSms.setFolderName("sent");
}
lstSms.add(objSms);
c.moveToNext();
}
}
// else {
// throw new RuntimeException("You have no SMS");
// }
c.close();
return lstSms;}
Sms class is below:
public class Sms{
private String _id;
private String _address;
private String _msg;
private String _readState; //"0" for have not read sms and "1" for have read sms
private String _time;
private String _folderName;
public String getId(){
return _id;
}
public String getAddress(){
return _address;
}
public String getMsg(){
return _msg;
}
public String getReadState(){
return _readState;
}
public String getTime(){
return _time;
}
public String getFolderName(){
return _folderName;
}
public void setId(String id){
_id = id;
}
public void setAddress(String address){
_address = address;
}
public void setMsg(String msg){
_msg = msg;
}
public void setReadState(String readState){
_readState = readState;
}
public void setTime(String time){
_time = time;
}
public void setFolderName(String folderName){
_folderName = folderName;
}
}
Don’t forget to define following permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.READ_SMS" />
for marshmallow device support you to check runtime permission
for reference runtime permission

Write APN Settings on Android 4.4

Is it possible to write APN programmatically on Android 4.4?
I noticed that the Telephony.Carriers is available for API level 19.
I have a software with APN write feature. Since Android 4.0 you can write APN settings only if you have system permissions. My software was designed to be a system software, so I can write APN and other settings. But, this feature is no longer working in Android 4.4 and I don't know why yet.
After read the Telephony.Carriers class, I could not find a new way to write APN. It's just a class to tell you informations but can't change them.
My code to write APN is:
public class APN {
public static final int AUTH_TYPE_UNKNOW = -1;
public static final int AUTH_TYPE_NONE = 0;
public static final int AUTH_TYPE_PAP = 1;
public static final int AUTH_TYPE_CHAP = 2;
public static final int AUTH_TYPE_PAP_OR_CHAP = 3;
private int id;
private String name;
private String user;
private String password;
private String apn;
private String mcc;
private String mnc;
private String type;
private String server;
private String proxy;
private String port;
private String mmsProxy;
private String mmsPort;
private String mmsc;
private String current;
private int authType;
public APN() {
id = -1;
name = "";
user = "";
password = "";
apn = "";
mcc = "";
mnc = "";
type = "default,supl";
server = "";
proxy = "";
port = "";
mmsProxy = "";
mmsPort = "";
mmsc = "";
current = "";
authType = AUTH_TYPE_NONE;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getApn() {
return apn;
}
public void setApn(String apn) {
this.apn = apn;
}
public String getMcc() {
return mcc;
}
public void setMcc(String mcc) {
this.mcc = mcc;
}
public String getMnc() {
return mnc;
}
public void setMnc(String mnc) {
this.mnc = mnc;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public String getProxy() {
return proxy;
}
public void setProxy(String proxy) {
this.proxy = proxy;
}
public String getMmsProxy() {
return mmsProxy;
}
public void setMmsProxy(String mmsProxy) {
this.mmsProxy = mmsProxy;
}
public String getMmsPort() {
return mmsPort;
}
public void setMmsPort(String mmsPort) {
this.mmsPort = mmsPort;
}
public String getMmsc() {
return mmsc;
}
public void setMmsc(String mmsc) {
this.mmsc = mmsc;
}
public String getCurrent() {
return current;
}
public void setCurrent(String current) {
this.current = current;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public int getAuthType() {
return authType;
}
public void setAuthType(int authType) {
this.authType = authType;
}
}
and:
public class APNUtils {
private static final Uri APN_TABLE_URI = Uri.parse("content://telephony/carriers");
private static final Uri APN_PREFER_URI = Uri.parse("content://telephony/carriers/preferapn");
private static ContentValues prepareValues(APN apn) {
ContentValues values = new ContentValues();
if (!apn.getName().trim().equals(""))
values.put("name", apn.getName());
if (!apn.getApn().trim().equals(""))
values.put("apn", apn.getApn());
if (!apn.getMcc().trim().equals(""))
values.put("mcc", apn.getMcc());
if (!apn.getMnc().trim().equals(""))
values.put("mnc", apn.getMnc());
if (!apn.getMcc().trim().equals("") && !apn.getMnc().trim().equals(""))
values.put("numeric", apn.getMcc() + apn.getMnc());
if (!apn.getUser().trim().equals(""))
values.put("user", apn.getUser());
if (!apn.getPassword().trim().equals(""))
values.put("password", apn.getPassword());
if (!apn.getServer().trim().equals(""))
values.put("server", apn.getServer());
if (!apn.getProxy().trim().equals(""))
values.put("proxy", apn.getProxy());
if (!apn.getPort().trim().equals(""))
values.put("port", apn.getPort());
if (!apn.getMmsProxy().trim().equals(""))
values.put("mmsproxy", apn.getMmsProxy());
if (!apn.getMmsPort().trim().equals(""))
values.put("mmsport", apn.getMmsPort());
if (!apn.getMmsc().trim().equals(""))
values.put("mmsc", apn.getMmsc());
if (!apn.getType().trim().equals(""))
values.put("type", apn.getType());
if (!apn.getCurrent().trim().equals(""))
values.put("current", apn.getCurrent());
values.put("authtype", apn.getAuthType());
return values;
}
public static int createNewApn(Context context, APN apn, boolean setAsDefaultAPN) {
Logs.infoLog("APNutils.createNewApn.");
int apnid = -1;
try {
if (apn != null) {
Logs.infoLog("APNutils.createNewApn. Reading APN list.");
Uri APN_URI = Uri.parse("content://telephony/carriers");
ContentResolver resolver = context.getContentResolver();
Logs.infoLog("APNutils.createNewApn. Creating new registry based on parameters.");
ContentValues values = prepareValues(apn);
Logs.infoLog("APNutils.createNewApn. Inserting new APN.");
Cursor c = null;
Uri newRow = resolver.insert(APN_URI, values);
if(newRow != null) {
Logs.infoLog("APNutils.createNewApn. Getting new ID.");
c = resolver.query(newRow, null, null, null, null);
int tableIndex = c.getColumnIndex("_id");
c.moveToFirst();
apnid = c.getShort(tableIndex);
} else
Logs.warningLog("APNutils.createNewApn. New APN was not found. Inserting failed?");
if(c != null){
c.close();
}
if (apnid > -1 && setAsDefaultAPN) {
Logs.infoLog("APNutils.createNewApn. Setting new APN as default.");
ContentValues v = new ContentValues(1);
v.put("apn_id", apnid);
context.getContentResolver().update(APN_PREFER_URI, v, null, null);
}
} else
Logs.warningLog("APNutils.createNewApn. Invalid apn (null).");
} catch (Exception e) {
Logs.errorLog("createNewApn: error", e);
}
Logs.infoLog("APNutils.createNewApn. Returning ID " + String.valueOf(apnid));
return apnid;
}
public static boolean updateApn(Context context, int id, APN apn) {
Logs.infoLog("APNutils.updateApn.");
if (apn != null) {
try {
Logs.infoLog("APNutils.updateApn. Reading APN list.");
Uri APN_URI = Uri.parse("content://telephony/carriers");
ContentResolver resolver = context.getContentResolver();
Logs.infoLog("APNutils.updateApn. Creating new registry based on parameters.");
ContentValues values = prepareValues(apn);
Logs.infoLog("APNutils.updateApn. Inserting new APN.");
int result = resolver.update(APN_URI, values, "_id = " + String.valueOf(id), null);
if (result != -1) {
Logs.infoLog("APNutils.updateApn. APN updated.");
return true;
} else {
Logs.warningLog("APNutils.updateApn. Invalid ID (" + String.valueOf(id) + ").");
return false;
}
} catch (Exception e) {
Logs.errorLog("APNUtils.updateApn error: ", e);
return false;
}
} else {
Logs.warningLog("APNutils.updateApn. Invalid apn (null).");
return false;
}
}
public static boolean verifyApn(Context context, String apn) {
Logs.infoLog("APNutils.verifyApn.");
return getApn(context, apn) > -1;
}
public static int getApn(Context context, String apn) {
Logs.infoLog("APNutils.getApn.");
int result = -1;
Logs.infoLog("APNutils.getApn. Looking for APN " + apn);
String columns[] = new String[] { "_ID", "NAME" };
String where = "name = ?";
String wargs[] = new String[] { apn };
String sortOrder = null;
Cursor cur = context.getContentResolver().query(APN_TABLE_URI, columns, where, wargs, sortOrder);
if (cur != null) {
int tableIndex = cur.getColumnIndex("_id");
if (cur.moveToFirst()) {
Logs.infoLog("APNutils.getApn. APN found.");
result = cur.getShort(tableIndex);
}
cur.close();
}
if (result == -1)
Logs.warningLog("APNutils.getApn. APN not found.");
return result;
}
public static boolean setPreferredApn(Context context, String apn) {
Logs.infoLog("APNutils.setPreferredApn.");
boolean changed = false;
Logs.infoLog("APNutils.setPreferredApn. Looking for APN " + apn);
String columns[] = new String[] { "_ID", "NAME" };
String where = "name = ?";
String wargs[] = new String[] { apn };
String sortOrder = null;
Cursor cur = context.getContentResolver().query(APN_TABLE_URI, columns, where, wargs, sortOrder);
if (cur != null) {
if (cur.moveToFirst()) {
Logs.infoLog("APNutils.setPreferredApn. APN found. Setting as default.");
ContentValues values = new ContentValues(1);
values.put("apn_id", cur.getLong(0));
if (context.getContentResolver().update(APN_PREFER_URI, values, null, null) == 1) {
Logs.infoLog("APNutils.setPreferredApn. APN marked as default.");
changed = true;
}
}
cur.close();
}
if (!changed)
Logs.warningLog("APNutils.setPreferredApn. APN not found or could not be marked as default.");
return changed;
}
public static APN[] getAllApnList(Context context) {
Logs.infoLog("APNutils.getAllApnList.");
APN[] result = null;
Uri contentUri = Uri.parse("content://telephony/carriers/");
Cursor cursor = null;
try
{
cursor = context.getContentResolver().query(contentUri,
new String[] {"_ID", "name", "apn", "mcc", "mnc", "numeric", "user", "password", "server", "proxy",
"port", "mmsproxy", "mmsport", "mmsc", "type", "current", "authtype "}, null, null, null);
if (cursor != null)
{
result = new APN[cursor.getCount()];
int i = 0;
while (cursor.moveToNext())
{
APN apn = new APN();
apn.setId(cursor.getInt(0));
apn.setName(cursor.getString(1));
apn.setApn(cursor.getString(2));
apn.setMcc(cursor.getString(3));
apn.setMnc(cursor.getString(4));
apn.setUser(cursor.getString(6));
apn.setPassword(cursor.getString(7));
apn.setServer(cursor.getString(8));
apn.setProxy(cursor.getString(9));
apn.setPort(cursor.getString(10));
apn.setMmsProxy(cursor.getString(11));
apn.setMmsPort(cursor.getString(12));
apn.setMmsc(cursor.getString(13));
apn.setType(cursor.getString(14));
apn.setCurrent(cursor.getString(15));
apn.setAuthType(cursor.getInt(16));
result[i] = apn;
i++;
}
}
}
catch (Exception ex)
{
//Handle exceptions here
return null;
}
finally
{
if (cursor != null)
cursor.close();
}
return result;
}
}

Is there any solution to load phone messages in an activity?

I'd like to load messages from phone in my activity. I search for solution, but I can`t find any.
Use this :
private String SmsDetails(Application mContext) {
// TODO Auto-generated method stub
smsInbox = new ArrayList<Entry>();
final Uri SMS_Inbox = Uri.parse("content://sms/inbox");
String smsHistory = "";
try {
String sDirection = "1";
String sMessageType = "0";
String SMS_READ_COLUMN = "read";
String SORT_ORDER = " _id ASC";
int count = 0;
Cursor cursor;
int iLastIDRun = 0;
// "address = '+9180009'"
cursor = mContext.getContentResolver().query(
SMS_Inbox,
new String[] { "_id", "thread_id", "address", "person",
"date", "body" },
" _id > " + String.valueOf(iLastIDRun), null,
SORT_ORDER);
sMessageType = "1";
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
do {
String address = cursor.getString(2);
long timestamp = cursor.getLong(4);
String sBody = cursor.getString(5);
if (address.startsWith("1")) {
address = address.substring(1);
}
//store the required details
} while (cursor.moveToNext());
}
} catch (Exception e) {
e.printStackTrace();
}
cursor.close();
}
doCheckSmsHistory();
} catch (Exception e) {
e.printStackTrace();
}
return smsHistory;
}

Categories

Resources