Does this Code will Work on Any Device/Android Version since Froyo 2.2 :
public class SmsObserver extends ContentObserver {
private String Name;
private SharedPreferences myPrefs;
public SmsObserver(Handler handler , Context ctx) {
super(handler);
// TODO Auto-generated constructor stub
context = ctx;
initialPos = getLastMsgId();
}
private Context context;
private static int initialPos;
private static final String TAG = "SMSContentObserver";
private static final Uri uriSMS = Uri.parse("content://sms");
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
queryLastSentSMS();
}
public int getLastMsgId() {
Cursor cur = context.getContentResolver().query(uriSMS, null, null, null, null);
cur.moveToFirst();
int lastMsgId = cur.getInt(cur.getColumnIndex("_id"));
Log.i(TAG, "Last sent message id: " + String.valueOf(lastMsgId));
return lastMsgId;
}
protected void queryLastSentSMS() {
new Thread(new Runnable() {
public void run() {
Cursor cur =
context.getContentResolver().query(uriSMS, null, null, null, null);
if (cur.moveToNext()) {
TelephonyManager tm = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
String myDeviceId = tm.getDeviceId();
String myTelephoneNumber = tm.getLine1Number();
Calendar c = Calendar.getInstance();
int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
int hour = c.get(Calendar.HOUR);
int minute = c.get(Calendar.MINUTE);
int seconde = c.get(Calendar.SECOND);
try {
String body = cur.getString(cur.getColumnIndex("body"));
String reformated_body =
Normalizer.normalize(body, Normalizer.Form.NFD).replaceAll(
"[^\\p{ASCII}]", "");
if (initialPos != getLastMsgId()) {
myPrefs = context.getSharedPreferences("Preferences", Context.MODE_WORLD_WRITEABLE);
getDisplayNameFromPhoneNo(cur.getString(cur.getColumnIndex("address")));
final String finalTxt = context.getResources().getString(R.string.txtSMSSent) + " " + Name + " " + cur.getString(cur.getColumnIndex("address")) + " " + context.getResources().getString(R.string.txtSMSMessage) + reformated_body;
Log.i(TAG, "Reformated Body : " + reformated_body);
Log.i("account", myDeviceId);
Log.i("date", day + "-" + month + "-" + year + " "
+ hour + ":" + minute + ":" + seconde);
Log.i("sender", myTelephoneNumber);
Log.i("receiver", cur.getString(cur.getColumnIndex("address")));
Log.i("message", reformated_body);
if(!cur.getString(cur.getColumnIndex("address")).equals(Gever)){
// Then, set initialPos to the current position.
initialPos = getLastMsgId();
}
}} catch (Exception e) {
// Treat exception here
}
}
cur.close();
}
}).start();
}
public void getDisplayNameFromPhoneNo(String phoneNo) {
ContentResolver localContentResolver = context.getContentResolver();
Cursor contactLookupCursor =
localContentResolver.query(
Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNo)),
new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup._ID},
null,
null,
null);
try {
while(contactLookupCursor.moveToNext()){
String contactName = contactLookupCursor.getString(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
String contactId = contactLookupCursor.getString(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup._ID));
Log.d("LOGTAG", "contactMatch name: " + contactName);
Log.d("LOGTAG", "contactMatch id: " + contactId);
Name = contactName;
}
} finally {
contactLookupCursor.close();
}
}
}//End of class SmsObserver
I received One report from someone that say its does not Work , for me , its working fine , so this : "content://sms" is the Same for All Android Version ?
Related
Trying to delete the sent sms from app, when I have tried below code in Lenovo A6000(5.0.2) device
public static void deleteMessage(Context context, String phoneNo, String message) {
try {
Log.d(TAG, "deleteMessage: Deleting SMS from inbox");
Uri uriSms = Uri.parse("content://sms/");
Cursor c = context.getContentResolver().query(uriSms,
new String[]{"_id", "thread_id", "address",
"person", "date", "body"}, null, null, null);
Uri uri = null;
if (c != null && c.moveToFirst()) {
do {
long id = c.getLong(0);
long threadId = c.getLong(1);
String address = c.getString(2);
String body = c.getString(5);
int rowsDeleted = 0;
Log.d(TAG, "Deleting threads: " + threadId);
Log.d(TAG, "deleteMessage: id- "+ id + "" +
" threadId- " + threadId + "" +
" body- " + body + "" +
" rowsDeleted- " + rowsDeleted + "" +
" address- " + address);
if (address.equalsIgnoreCase(phoneNo)
&& body.equalsIgnoreCase(message)) {
ConversationQueryHandler handler = new ConversationQueryHandler(context.getContentResolver(), context);
synchronized (sDeletingThreadsLock) {
Log.v(TAG, "Conversation startDelete sDeletingThreads: " + sDeletingThreads);
if (sDeletingThreads) {
Log.e(TAG, "startDeleteAll already in the middle of a delete", new Exception());
}
sDeletingThreads = true;
uri = ContentUris.withAppendedId(Telephony.Threads.CONTENT_URI, threadId);
String selection = true ? null : "locked=0";
handler.setDeleteToken(0);
handler.startDelete(0, new Long(threadId), uri, selection, null);
}
}
} while (c.moveToNext());
}
} catch (Exception e) {
Log.d(TAG, "deleteMessage: Could not delete SMS from inbox: " + e.getMessage());
}
}
The ConversationQueryHandler sends 1 as a result in case of successful deletion of sms on to onDeletionComplete but this doesn't work in all the devices.
private static Object sDeletingThreadsLock = new Object();
private static boolean sDeletingThreads;
public static class ConversationQueryHandler extends AsyncQueryHandler {
private int mDeleteToken;
private Context mContext;
public ConversationQueryHandler(ContentResolver cr, Context context) {
super(cr);
mContext = context;
}
public void setDeleteToken(int token) {
mDeleteToken = token;
}
/**
* Always call this super method from your overridden onDeleteComplete function.
*/
#Override
protected void onDeleteComplete(int token, Object cookie, int result) {
Log.v(TAG, "Conversation onDeleteComplete token: " + token + " cookie- " + cookie + " result- " + result);
if (token == mDeleteToken) {
// release lock
synchronized (sDeletingThreadsLock) {
sDeletingThreads = false;
sDeletingThreadsLock.notifyAll();
}
}
}
}
I have tested this and found it is failed to delete the sms in all the below devices
Sony Xperia Z1(5.1.1)
Lenovo A200 device (5.1)
Samsung J210F (6.0.1)
As I mentioned earlier I am able to delete sms with the same code in
Lenovo A6000(5.0.2)
Is there a chance I am missing something here, or is this a right way of deleting the sent sms. Thank you for the help in advance.
on sms received , i have saved that sms in my database
now i want to move that sms into inbox
i used this code but it move it as sent by me
please help me to move it as a received sms
ListViewLogItem lm = listArray.get(position);
long datein = Long.parseLong(lm.getInboxTime());
Uri uri = Uri.parse("content://sms/");
ContentValues cv2 = new ContentValues();
cv2.put("address","+"+lm.getNumber());
cv2.put("date", datein);
cv2.put("read", 1);
cv2.put("type", 2);
cv2.put("body", lm.getSms());
getContentResolver().insert(Uri.parse("content://sms/inbox"), cv2);
Change:
cv2.put("type", 2);
To:
cv2.put("type", 1);
Because:
public static final int MESSAGE_TYPE_INBOX = 1;
public static final int MESSAGE_TYPE_SENT = 2;
You can use following method for deleting SMS from Inbox,
private void deleteMessage()
{
Cursor c = getContentResolver().query(SMS_INBOX, null, null, null, null);
//c.moveToFirst();
while (c.moveToNext())
{
System.out.println("Inside if loop");
try
{
String address = c.getString(2);
String MobileNumber = mainmenu.getParameterData().getMobileNumber().trim();
//Log.i( LOGTAG, MobileNumber + "," + address );
Log.i( LOGTAG, c.getString(2) );
if ( address.trim().equals( MobileNumber ) )
{
String pid = c.getString(1);
String uri = "content://sms/conversations/" + pid;
getContentResolver().delete(Uri.parse(uri), null, null);
stopSelf();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Use thisvalues.put("status", SmsManager.STATUS_ON_ICC_UNREAD); . Status can be anything like read/unread/seen. I have keep it as unread.
Look at Message status
values.put("read", true); // As Read
and
values.put("read", false); // As Un Read
public class Message {
final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
#SuppressWarnings("unused")
private ContentResolver resolver;
public Message(ContentResolver ConResolver){
resolver = ConResolver;
}
public String getMessage(int batas) {
Cursor cur = resolver.query(SMS_INBOX, null, null, null,null);
String sms = "Message >> \n";
int hitung = 0;
while (cur.moveToNext()) {
sms += "From :" + cur.getString(2) + " : " + cur.getString(11)+"\n";
if(hitung == batas)
break;
hitung++;
}
return sms;
}
public int getMessageCountUnread(){
Cursor c = resolver.query(SMS_INBOX, null, "read = 0", null, null);
int unreadMessagesCount = c.getCount();
c.deactivate();
return unreadMessagesCount;
}
public String getMessageAll(){
Cursor cur = resolver.query(SMS_INBOX, null, null, null,null);
String sms = "Message >> \n";
while (cur.moveToNext()) {
sms += "From :" + cur.getString(2) + " : " + cur.getString(11)+"\n";
}
return sms;
}
public String getMessageUnread() {
Cursor cur = resolver.query(SMS_INBOX, null, null, null,null);
String sms = "Message >> \n";
int hitung = 0;
while (cur.moveToNext()) {
sms += "From :" + cur.getString(2) + " : " + cur.getString(11)+"\n";
if(hitung == getMessageCountUnread())
break;
hitung++;
}
return sms;
}
public void setMessageStatusRead() {
ContentValues values = new ContentValues();
values.put("read",true);
resolver.update(SMS_INBOX,values, "_id="+SmsMessageId, null);
}
}
I am trying to create a app which will fetch details of Events and Attendeesfrom Calendar app.
I am facing the problems which are"
1). In many of the events Title and their attendees does not match.
2). In many of the events I am getting 0 attendees
(mainly for upcoming events).
Here is my code: (Please let me know the mistake).
public class ReadCalendar {
static Cursor cursor;
public static void readCalendar(Context context) {
ContentResolver contentResolver = context.getContentResolver();
// Fetch a list of all calendars synced with the device, their display names and whether the
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/calendars"),
(new String[] { Calendars._ID, Calendars.NAME}), null, null, null);
HashSet<String> calendarIds = new HashSet<String>();
try
{
System.out.println("Count="+cursor.getCount());
if(cursor.getCount() > 0)
{
System.out.println("the control is just inside of the cursor.count loop");
while (cursor.moveToNext()) {
String _id = cursor.getString(0);
String displayName = cursor.getString(1);
//Boolean selected = !cursor.getString(2).equals("0");
System.out.println("Id: " + _id + " Display Name: " + displayName);
calendarIds.add(_id);
}
}
}
catch(AssertionError ex)
{
ex.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
// For each calendar, display all the events from the previous week to the end of next week.
for (String id : calendarIds) {
Uri.Builder builder = Uri.parse("content://com.android.calendar/instances/when").buildUpon();
//Uri.Builder builder = Uri.parse("content://com.android.calendar/calendars").buildUpon();
long now = new Date().getTime();
ContentUris.appendId(builder, now - DateUtils.DAY_IN_MILLIS * 10000);
ContentUris.appendId(builder, now + DateUtils.DAY_IN_MILLIS * 10000);
Log.e("123", "Calender ID---->>>>>>"+id);
Cursor eventCursor = contentResolver.query(builder.build(),
new String[] { Events.TITLE, "begin", "end", "allDay", Events._ID, Events.CALENDAR_ID}, Events.CALENDAR_ID+"=" + id,
null, "_id ASC");
Log.e("123","eventCursor count====="+eventCursor.getCount());
if(eventCursor.getCount()>0)
{
if(eventCursor.moveToFirst())
{
do
{
Object mbeg_date,beg_date,beg_time,end_date,end_time;
final String title = eventCursor.getString(0);
final Date begin = new Date(eventCursor.getLong(1));
final Date end = new Date(eventCursor.getLong(2));
final Boolean allDay = !eventCursor.getString(3).equals("0");
final String eventId = eventCursor.getString(4);
final String calendarID = eventCursor.getString(5);
Log.e("123", "Event Id----->>>>>"+eventId+"---------calendarId----->>>"+calendarID);
/* System.out.println("Title: " + title + " Begin: " + begin + " End: " + end +
" All Day: " + allDay);
*/
Log.e("123","Title:"+title);
Log.e("123","Begin:"+begin);
Log.e("123","End:"+end);
Log.e("123","All Day:"+allDay);
// Attendees Code
Cursor eventAttendeesCoursor = contentResolver.query(CalendarContract.Attendees.CONTENT_URI, new String []{ Attendees.ATTENDEE_NAME, Attendees.EVENT_ID}, Attendees.EVENT_ID +" = " + eventId, null, null);
Log.e("123", "Count of no of attendees-----"+eventAttendeesCoursor.getCount());
if(eventAttendeesCoursor.getCount()>0)
{
if(eventAttendeesCoursor.moveToFirst())
{
do {
// Log.e("123", "Attendees Name---->>>"+ eventAttendeesCoursor.getString(0));
Log.e("123", "Attendees Event ID---->>>"+ eventAttendeesCoursor.getString(1));
} while(eventAttendeesCoursor.moveToNext());
}
}
}
while(eventCursor.moveToNext());
}
}
break;
}
}
}
I am using below code to get calendar events in my application. It's working fine in Android phones but when I try this code on Android tablet, my application crashes. So I don't know exactly what is the problem and why it is not working on tablets.
public void syncCalander() {
try {
nameValues = new ArrayList<NameValuePair>();
StringBuffer calbuffers;
int cnt = 1;
StringBuffer calbufferimeis = new StringBuffer();
ContentResolver contentResolver = getApplicationContext()
.getContentResolver();
final Cursor cursor = contentResolver.query(
Uri.parse("content://com.android.calendar/calendars"),
(new String[] { "_id", "displayName", "selected" }), null,
null, null);
if (cursor.getCount() == 0) {
} else {
HashSet<String> calendarIds = new HashSet<String>();
CalendarModel calModel = new CalendarModel();
CalendarModel.CALENDERLIST.add(calModel);
int val = cursor.getCount();
Log.i("=============total event============>", "." + val);
while (cursor.moveToNext()) {
final String _id = cursor.getString(0);
final String displayName = cursor.getString(1);
final Boolean selected = !cursor.getString(2).equals("0");
calModel.setCalendarEvent(displayName);
CalendarModel.CALENDERLIST.add(calModel);
Log.i("--------Display Name----------", "" + "Id: " + _id
+ " Display Name: " + displayName + " Selected: "
+ selected);
calendarIds.add(_id);
Log.i("============celenderIDs==========>", "."
+ calendarIds);
}
for (String id : calendarIds) {
Uri.Builder builder = Uri.parse(
"content://com.android.calendar/instances/when")
.buildUpon();
long now = new Date().getTime();
ContentUris.appendId(builder, now
- DateUtils.WEEK_IN_MILLIS);
ContentUris.appendId(builder, now
+ DateUtils.WEEK_IN_MILLIS);
Cursor eventCursor = contentResolver.query(builder.build(),
new String[] { "title", "begin", "end", "allDay" },
"Calendars._id=" + id, null,
"startDay ASC, startMinute ASC");
Log.i("============cursor size===========>", "."
+ eventCursor.getCount());
while (eventCursor.moveToNext()) {
final String title = eventCursor.getString(0);
final Date begin = new Date(eventCursor.getLong(1));
final Date end = new Date(eventCursor.getLong(2));
final Boolean allDay = !eventCursor.getString(3)
.equals("0");
calModel.setCalendarDate(begin.toString());
CalendarModel.CALENDERLIST.add(calModel);
Log.i("-----Title--------", "Title: " + title
+ " Begin: " + begin + " End: " + end
+ " All Day: " + allDay);
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String date = formatter.format(begin);
int callength = CalendarModel.CALENDERLIST.size();
calbuffers = new StringBuffer();
calbuffers.append("{\"Calenderevent\":\"" + title
+ "\"," + "\"Calenderdate\":\"" + date + "\"}");
calbuffers.append(",");
calbufferimeis.append(calbuffers);
}
eventCursor.close();
}
}
cursor.close();
} catch (Exception e) {
}
}
i have use
content://calendar/calendars
instead of
content://com.android.calendar/calendars
for the android tablet applications
I'm trying to implement a ContentObserver for CallLog.Calls content provider. I mean, If I make a call, or receive a call, etc, the observer must notify me that the CallLog.Calls content provider has changed. But the onchange method only returns false, even with the observers registered, and notified. Maybe I'm doing something wrong.
This is my code. It's an Activity.
package com.psyhclo;
public class RatedCalls extends ListActivity {
private static final String LOG_TAG = "RatedCallsObserver";
private Handler handler = new Handler();
private RatedCallsContentObserver callsObserver = null;
private SQLiteDatabase db;
private CallDataHelper dh = null;
StringBuilder sb = new StringBuilder();
OpenHelper openHelper = new OpenHelper(RatedCalls.this);
class RatedCallsContentObserver extends ContentObserver {
public RatedCallsContentObserver(Handler h) {
super(h);
}
public void onChange(boolean selfChange) {
Log.d(LOG_TAG, "RatedCallsContentObserver.onChange( " + selfChange
+ ")");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerContentObservers();
fillList();
}
#Override
public void onStart() {
super.onStart();
registerContentObservers();
}
#Override
public void onStop() {
super.onStop();
unregisterContentObservers();
}
private void fillList() {
Cursor cursor = getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, null, null, null,
android.provider.CallLog.Calls.DATE + " DESC ");
cursor.setNotificationUri(getBaseContext().getContentResolver(),
android.provider.CallLog.Calls.CONTENT_URI);
dh = new CallDataHelper(this);
db = openHelper.getWritableDatabase();
startManagingCursor(cursor);
int numberColumnId = cursor
.getColumnIndex(android.provider.CallLog.Calls.NUMBER);
int durationId = cursor
.getColumnIndex(android.provider.CallLog.Calls.DURATION);
int contactNameId = cursor
.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME);
int dateId = cursor.getColumnIndex(android.provider.CallLog.Calls.DATE);
int numTypeId = cursor
.getColumnIndex(android.provider.CallLog.Calls.CACHED_NUMBER_TYPE);
// int contactIdColumnId =
// cursor.getColumnIndex(android.provider.ContactsContract.RawContacts.CONTACT_ID);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String currTime = hours + ":" + minutes + ":" + seconds;
ArrayList<String> callList = new ArrayList<String>();
if (cursor.moveToFirst()) {
do {
String contactNumber = cursor.getString(numberColumnId);
String contactName = cursor.getString(contactNameId);
String duration = cursor.getString(durationId);
String callDate = DateFormat.getDateInstance().format(dateId);
String numType = cursor.getString(numTypeId);
ContentValues values = new ContentValues();
values.put("contact_id", 1);
values.put("contact_name", contactName);
values.put("number_type", numType);
values.put("contact_number", contactNumber);
values.put("duration", duration);
values.put("date", callDate);
values.put("current_time", currTime);
values.put("cont", 1);
getBaseContext().getContentResolver().notifyChange(
android.provider.CallLog.Calls.CONTENT_URI, null);
this.db.insert(CallDataHelper.TABLE_NAME, null, values);
Toast.makeText(getBaseContext(), "Inserted!", Toast.LENGTH_LONG);
callList.add("Contact Number: " + contactNumber
+ "\nContact Name: " + contactName + "\nDuration: "
+ duration + "\nDate: " + callDate);
} while (cursor.moveToNext());
}
setListAdapter(new ArrayAdapter<String>(this, R.layout.listitem,
callList));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
private void registerContentObservers() {
ContentResolver cr = getContentResolver();
callsObserver = new RatedCallsContentObserver(handler);
cr.registerContentObserver(android.provider.CallLog.Calls.CONTENT_URI,
true, callsObserver);
}
private void unregisterContentObservers() {
ContentResolver cr = getContentResolver();
if (callsObserver != null) { // just paranoia
cr.unregisterContentObserver(callsObserver);
callsObserver = null;
}
}
}
This is the answer for this question.
Android onChange() method only returns false