I'm trying to query the data from the CallLog and insert in DB. For that, I've created a COntentObserver as inner class in a Service, and inside onChange() method, I call my method that goes to the specified URI and query the data that has changed.
But, lets say, I received a call, so the observer was notified. So, my method goes to the call log content provider, query and insert, but it is inserting two, three times the same register.
Here is the code of my service.
public class RatedCallsService extends Service
private Handler handler = new Handler();
private SQLiteDatabase db;
private OpenHelper helper;
private String theDate;
private String theMonth_;
private String theYear_;
private String theDay_;
public static boolean servReg = false;
class RatedCallsContentObserver extends ContentObserver {
public RatedCallsContentObserver(Handler h) {
super(h);
//helper = new OpenHelper(getApplicationContext());
//db = helper.getWritableDatabase();
}
#Override
public boolean deliverSelfNotifications() {
return true;
}
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Log.i(LOG_TAG, "Inside on Change. selfChange " + selfChange);
searchInsert();
}
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
servReg = true;
db = DataHandlerDB.createDB(this);
registerContentObserver();
}
#Override
public void onDestroy() {
super.onDestroy();
db.close();
this.getApplicationContext().getContentResolver().unregisterContentObserver(new RatedCallsContentObserver(handler));
}
private void searchInsert() {
Cursor cursor = getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, null, null, null,
android.provider.CallLog.Calls.DATE + " DESC ");
if (cursor.moveToFirst()) {
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 numTypeId = cursor
.getColumnIndex(android.provider.CallLog.Calls.CACHED_NUMBER_TYPE);
int callTypeId = cursor
.getColumnIndex(android.provider.CallLog.Calls.TYPE);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String currTime = hours + ":" + minutes + ":" + seconds;
SimpleDateFormat dateFormat = new SimpleDateFormat("M/d/yyyy");
Date date = new Date();
cursor.moveToFirst();
String contactNumber = cursor.getString(numberColumnId);
String contactName = (null == cursor.getString(contactNameId) ? ""
: cursor.getString(contactNameId));
String duration = cursor.getString(durationId);
String numType = cursor.getString(numTypeId);
String callType = cursor.getString(callTypeId);
seconds = Integer.parseInt(duration);
theDate = dateFormat.format(date);
if (theDate.length() == 9) {
theMonth_ = theDate.substring(0, 1);
theDay_ = theDate.substring(2, 4);
theYear_ = theDate.substring(5, 9);
} else if (theDate.length() == 10) {
theMonth_ = theDate.substring(0, 2);
theDay_ = theDate.substring(3, 4);
theYear_ = theDate.substring(6, 10);
} else if (theDate.length() == 8) {
theMonth_ = theDate.substring(0, 1);
theDay_ = theDate.substring(2, 3);
theYear_ = theDate.substring(4, 8);
}
ContentValues values = new ContentValues();
ContentValues values2 = 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", Utilities.convertTime(seconds));
values.put("date", dateFormat.format(date));
values.put("current_time", currTime);
values.put("cont", 1);
values.put("type", callType);
values2.put("month",
Utilities.monthName(Integer.parseInt(theMonth_)));
values2.put("duration", Utilities.convertTime(seconds));
values2.put("year", theYear_);
values2.put("month_num", Integer.parseInt(theMonth_));
if (!db.isOpen()) {
db = getApplicationContext()
.openOrCreateDatabase(
"/data/data/com.project.myapp/databases/myDb.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
if (duration != "") {
if (Integer.parseInt(duration) != 0) {
String existingMonthDuration = DataHandlerDB
.selectMonthsDuration(theMonth_, theYear_, this);
Integer newMonthDuration;
if (existingMonthDuration != "") {
newMonthDuration = Integer
.parseInt(existingMonthDuration)
+ Integer.parseInt(duration);
values2.put("duration",
Utilities.convertTime(newMonthDuration));
db.update(DataHandlerDB.TABLE_NAME_3, values2,
"year = ?", new String[] { theYear_ });
} else {
db.insert(DataHandlerDB.TABLE_NAME_3, null, values2);
}
db.insert(DataHandlerDB.TABLE_NAME_2, null, values);
}
}
cursor.close();
}
}
public void registerContentObserver() {
this.getApplicationContext()
.getContentResolver()
.registerContentObserver(
android.provider.CallLog.Calls.CONTENT_URI, false,
new RatedCallsContentObserver(handler));
}
}
I've tried everything. unregistering the observer, etc. but nothing.
I selected the timestamp of the call from android.provider.CallLog.Calls.DATE and before I insert I check if there is some timestamp like that one, if there is I dont insert, if there isnt I insert the data. This values are unique, so never will have some like each other.
This happens to me when I suscribe tot he SMS content provider. I think is they way Android handles messages and calls that makes this behavior, I get the call 2 times whenever I send an SMS so I'm guessing is due to the message being put in the outbox table ? first, and then moved to the sent table. Perhaps something similar happens with the calls provider? Maybe this call is placed to a temporary table inside the provider and then once you receive it or miss it this call goes to the proper table (received/missed). What I do is, I check the Id of the message everytime my observer gets called and I keep the Id of the previous message so I can check If the observer is being calld due to the same ID I just handled.
does the selfChange vary ?
Hint. do not rely on this provider to monitor all your calls. Once android decides to terminate your application you will notice that your provider won't receive anymore calls. Try to schedule the attachment of the content observer every once in a while using AlarmManager.
Related
I use Google Calendar Provider for Android to add Events in my Google Calendar:
https://developer.android.com/guide/topics/providers/calendar-provider.html#overview
And this is the example to add Reminder for the Event:
ContentValues values = new ContentValues();
values.put(CalendarContract.Reminders.MINUTES, 15);
values.put(CalendarContract.Reminders.EVENT_ID, reminderEventId);
values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
getContentResolver().insert(CalendarContract.Reminders.CONTENT_URI, values);
But in my Google Calendar app I can create Reminders without having EVENT_ID. Is it possible to create the same reminders with Google Calendar Provider for Android?
The same like this:
https://gsuiteupdates.googleblog.com/2016/04/launch-of-reminders-for-google-calendar.html
I have see that Google launch reminders for Google Calendar 2016 (This is a different Reminders from Event Reminders) and at the moment I can`t find in Android SDK (API 25) this kind of Google Calendar Reminders (and possibility to add programmatically appointment slots too).
A tricky approach I'm using is creating the remainders, instead of calendar, in the contacts, using Custom Reminder (and the ContactContract provider). So, you can use any label, and the reminder is shown in the specific date.
Cons:
- You have to have the "Birthday" calendar enable
- The remainder is date based (not time)
- They don't repeat the reminder (as the new calendar does)
package es.goodsal.mobile.provider.contact;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.provider.ContactsContract.CommonDataKinds.Event;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import es.goodsal.mobile.app.App;
import es.goodsal.mobile.model.ReminderType;
/**
* Created by jmalbarran on 16/9/17.
*/
public class Reminder implements Comparable<Reminder> {
private static final String TAG = Reminder.class.getSimpleName();
private static final SimpleDateFormat fullPeriodicDateFormat = new SimpleDateFormat("--MM-dd");
private static final SimpleDateFormat periodicDateFormat = new SimpleDateFormat("MM-dd");
private static final SimpleDateFormat nonPeriodicDateFormat = new SimpleDateFormat("yyyy-MM-dd");
private static final String DUE_DATE = Event.DATA4;
private static final String COMMENT = Event.DATA5;
private static final Uri CONTENT_URI = ContactsContract.Data.CONTENT_URI;
private static final String[] PROJECTION = new String[]{
Event._ID, //0
Event.CONTACT_ID, //1
Event.LOOKUP_KEY, //2
Event.START_DATE, //3
Event.TYPE, //4
Event.LABEL, //5 Label for custom event
Reminder.DUE_DATE, // 6
Reminder.COMMENT // 7 Use this field to save Comments
};
static {
periodicDateFormat.setCalendar(Calendar.getInstance()); // Set local time zone
nonPeriodicDateFormat.setCalendar(Calendar.getInstance()); // Set local time zone
}
private long id = -1;
private ConContact contact;
private Date reminderDate;
private Date dueDate;
private ReminderType type;
private String comment;
// region Constructor
public Reminder(ConContact contact, Date reminderDate,
Date dueDate, ReminderType type, String comment) {
this.contact = contact;
this.reminderDate = reminderDate;
this.dueDate = dueDate;
this.type = type;
this.comment = comment;
}
public Reminder(#NonNull String reminderUri) {
this(Uri.parse(reminderUri));
}
public Reminder(#NonNull Uri reminderUri) {
Cursor cursor;
cursor = App.getContentResolverInstance().query(reminderUri,
PROJECTION, null, null, null);
if (cursor == null) {
throw new IllegalArgumentException(reminderUri.toString() + " opportunity not found.");
} else {
cursor.moveToFirst();
setFromCursor(null, cursor);
}
}
private Reminder(#NonNull Cursor cursor) {
this(null, cursor);
}
private Reminder(#Nullable ConContact contact, #NonNull Cursor cursor) {
setFromCursor(contact, cursor);
}
private void setFromCursor(#Nullable ConContact contact, #NonNull Cursor cursor) {
int eventType;
String eventLabel;
Calendar calDueDate, calReminderDate;
Date now;
String strSplitDate[];
String strDueDate;
this.id = cursor.getLong(0);
if (contact != null) {
this.contact = contact;
} else {
this.contact = new ConContact(cursor.getLong(1), cursor.getString(2));
}
// Type
eventType = cursor.getInt(4); //Event.TYPE
eventLabel = cursor.getString(5); //Event.LABEL
switch (eventType) {
case ContactsContract.CommonDataKinds.Event.TYPE_ANNIVERSARY:
type = ReminderType.anniversary;
break;
case ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY:
type = ReminderType.birthday;
break;
case ContactsContract.CommonDataKinds.Event.TYPE_CUSTOM:
type = ReminderType.other;
eventLabel = cursor.getString(5);
for (ReminderType iType : ReminderType.values()) {
if (iType.getLabel().equals(eventLabel)) {
type = iType;
break;
}
}
break;
default:
type = ReminderType.other;
}
// Due / Reminder date
try {
now = new Date();
if (type.isPeriodic()) {
// Periodic Due date
calDueDate = Calendar.getInstance();
calDueDate.setTime(now);
strSplitDate = cursor.getString(6).split("-"); // DATA4
if (strSplitDate != null && strSplitDate.length == 3) {
calDueDate.set(Calendar.MONTH, Integer.parseInt(strSplitDate[1]));
calDueDate.set(Calendar.DAY_OF_MONTH, Integer.parseInt(strSplitDate[2]));
if (calDueDate.before(now)) { // Crossed end-of-year boundary
calDueDate.add(Calendar.YEAR, 1); // Next year
}
} else {
Log.e(TAG, "getReminders: Invalid date for periodic reminder due date " +
cursor.getString(6));
}
dueDate = calDueDate.getTime();
// Periodic Reminder date
calReminderDate = Calendar.getInstance();
calReminderDate.setTime(dueDate);
strSplitDate = cursor.getString(3).split("-"); // START_DATE
if (strSplitDate != null && strSplitDate.length == 3) {
calReminderDate.set(Calendar.MONTH, Integer.parseInt(strSplitDate[1]));
calReminderDate.set(Calendar.DAY_OF_MONTH, Integer.parseInt(strSplitDate[2]));
if (calReminderDate.after(dueDate)) { // Crossed end-of-year boundary
calDueDate.add(Calendar.YEAR, -11); // Previous year
}
} else {
Log.e(TAG, "getReminders: Invalid date for periodic reminder start date " +
cursor.getString(6));
}
reminderDate = calReminderDate.getTime();
} else {
// Non periodic date
reminderDate = nonPeriodicDateFormat.parse(cursor.getString(3)); // START_DATE
dueDate = nonPeriodicDateFormat.parse(cursor.getString(6)); // DATA4
dueDate = dueDate !=null ? dueDate : reminderDate;
}
} catch (Exception e) { // NullPointer and/or ParseFormat
dueDate = null;
reminderDate = null;
}
// Comment
comment = cursor.getString(7); // DATA5
}
// endregion Constructor
// region Getter/Setter
public Uri getUri() {
Uri uri;
uri = null;
if (id != -1) {
uri = ContentUris.withAppendedId(CONTENT_URI, id);
}
return uri;
}
public ConContact getContact() {
return contact;
}
public Date getReminderDate() {
return reminderDate;
}
public Date getDueDate() {
return dueDate;
}
public ReminderType getReminderType() {
return type;
}
public String getComment() {
return comment;
}
public boolean isPeriodic() {
return type.isPeriodic();
}
public void setContact(ConContact contact) {
this.contact = contact;
}
public void setReminderDate(Date reminderDate) {
this.reminderDate = reminderDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public void setType(ReminderType type) {
this.type = type;
}
public void setComment(String comment) {
this.comment = comment;
}
// endregion Getter/Setter
// region Commands
public boolean save() {
boolean ret;
ContentValues values;
Uri savedUri;
ret = false;
values = new ContentValues();
values.put(ContactsContract.CommonDataKinds.Event.MIMETYPE,
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE);
//values.put(ContactsContract.CommonDataKinds.Event.CONTACT_ID, contact.getContactId());
values.put(ContactsContract.CommonDataKinds.Event.RAW_CONTACT_ID, contact.getRawContactId());
if (type.isPeriodic()) {
values.put(ContactsContract.CommonDataKinds.Event.START_DATE,
fullPeriodicDateFormat.format(reminderDate));
values.put(ContactsContract.CommonDataKinds.Event.DATA4,
fullPeriodicDateFormat.format(dueDate));
} else {
values.put(ContactsContract.CommonDataKinds.Event.START_DATE,
nonPeriodicDateFormat.format(reminderDate));
values.put(ContactsContract.CommonDataKinds.Event.DATA4,
nonPeriodicDateFormat.format(dueDate));
}
values.put(ContactsContract.CommonDataKinds.Event.TYPE,
Integer.toString(type.getContactEventType()));
values.put(ContactsContract.CommonDataKinds.Event.LABEL, type.getLabel());
values.put(ContactsContract.CommonDataKinds.Event.DATA5, comment);
if (id == -1L) {
// Create new
savedUri = App.getContentResolverInstance().insert(ContactsContract.Data.CONTENT_URI, values);
id = ContentUris.parseId(savedUri);
ret = true;
Log.d(TAG, "save: Inserted uri=" + savedUri + " id=" + id);
} else {
// update existing id
// if (0<App.getContentResolverInstance().update(ContactsContract.Data.CONTENT_URI, values,
// ContactsContract.Data._ID + "='" + Long.toString(id) + "'", null)){
if (0 < App.getContentResolverInstance().update(
ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, id),
values,
null,
null)) {
ret = true;
Log.d(TAG, "save: Updated id=" + id);
} else {
Log.e(TAG, "save: Error updating id=" + id);
}
}
contact.resetReminders();
return ret;
}
public boolean delete() {
boolean ret = false;
if (id != -1) {
if (0 < App.getContentResolverInstance().delete(
ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, id),
null,
null)) {
Log.d(TAG, "delete: Deleted id=" + id);
ret = true;
} else {
Log.w(TAG, "delete: Not found id=" + id);
}
}
return ret;
}
// endregion Commands
#Override
public int compareTo(#NonNull Reminder o) {
if (reminderDate == null) {
return 1; // null always at end
} else {
if (o.reminderDate == null) {
return -1;
} else {
return reminderDate.compareTo(o.reminderDate);
}
}
}
/**
* Get reminders for all contact, in a specific date (including periodics)
*
* #param date exact to search for (reminder date NOT due date)
* #return List of reminders
*/
public static List<Reminder> getReminders(Date date) {
Cursor cursor;
ArrayList<Reminder> retList;
String where;
String[] selectionArgs;
Date dueDate;
String dateSelection;
String[] strSplitDate;
Calendar calDueDate;
retList = null;
Uri uri = ContactsContract.Data.CONTENT_URI;
String sortOrder = null;
// Execute one query per reminder type
for (ReminderType type : ReminderType.values()) {
dateSelection = type.isPeriodic() ?
"%" + periodicDateFormat.format(date) :
"%" + nonPeriodicDateFormat.format(date);
if (type.getContactEventType() == ContactsContract.CommonDataKinds.Event.TYPE_CUSTOM) {
// Check event label too
where = ContactsContract.CommonDataKinds.Event.MIMETYPE + "= ? AND " +
ContactsContract.CommonDataKinds.Event.START_DATE + " LIKE ? AND " +
ContactsContract.CommonDataKinds.Event.LABEL + "= ? AND " +
ContactsContract.CommonDataKinds.Event.TYPE + "=" + type.getContactEventType();
selectionArgs = new String[]{
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE,
dateSelection,
type.getLabel()
};
} else {
// Non custom reminder. Don't check label
where = ContactsContract.CommonDataKinds.Event.MIMETYPE + "= ? AND " +
ContactsContract.CommonDataKinds.Event.START_DATE + " LIKE ? AND " +
ContactsContract.CommonDataKinds.Event.TYPE + "=" + type.getContactEventType();
selectionArgs = new String[]{
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE,
dateSelection
};
} // where & selection per event type
cursor = App.getContentResolverInstance().query(uri, PROJECTION,
where, selectionArgs, sortOrder);
if (cursor != null) {
retList = new ArrayList<Reminder>();
while (cursor.moveToNext()) {
retList.add(new Reminder(cursor));
}
cursor.close();
} // if cursor
} // for per every type
return retList;
}
/**
* Get reminders for a specific contact, from a date forward
*
* #param contact Contact for search for
* #param date current or future date to search (including periodic)
* #return List of reminders for current or future search
*/
public static List<Reminder> getReminders(ConContact contact, Date date) {
Uri uri;
Cursor cursor;
ArrayList<Reminder> retList = null;
String where;
String[] selectionArgs;
String sortOrder;
int contactEventType;
String label;
Calendar calReminderDate, calDueDate;
String strReminderDate, strDueDate;
ReminderType type;
Date reminderDate;
Date dueDate;
String strDescription;
String[] strSplitDate;
uri = ContactsContract.Data.CONTENT_URI;
sortOrder = null;
// Check event label too
where = ContactsContract.CommonDataKinds.Event.MIMETYPE + " = ? AND " +
ContactsContract.CommonDataKinds.Event.CONTACT_ID + " = ? AND " +
"(" +
ContactsContract.CommonDataKinds.Event.START_DATE + " LIKE '--%' OR " +
ContactsContract.CommonDataKinds.Event.START_DATE + " >= ?" +
")";
selectionArgs = new String[]{
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE,
Long.toString(contact.getContactId()),
nonPeriodicDateFormat.format(date)
};
sortOrder = ContactsContract.CommonDataKinds.Event.START_DATE;
cursor = App.getContentResolverInstance().query(uri, PROJECTION,
where, selectionArgs, sortOrder);
if (cursor != null) {
retList = new ArrayList<Reminder>();
while (cursor.moveToNext()) {
retList.add(new Reminder(contact, cursor));
}
Collections.sort(retList);
cursor.close();
} // if cursor
// for per every type
return retList;
}
} // end Reminder class
As stated in https://developer.android.com/guide/topics/providers/calendar-provider.html#overview
Reminders are specified in minutes before the event and have a method
that determines how the user will be alerted.
A reminder that doesn't belong to an event will not have a time of reference to go off.
I think for what you are trying to achieve () it would be best for you to look at Androids AlarmManager https://developer.android.com/reference/android/app/AlarmManager.html
Or see what other people are saying about similar things https://stackoverflow.com/a/16549111/6431430
I am having problem while retrieving data from sqlite database what I need is to retrieve all data on console. But I am getting only one rows data on console
Here is the code to insert and retrieve data from Sqlite. Please specify what I am missing or doing wrong. Thanks for any help.
public long InsertContacts(Contacts contacts) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_IMAGE, DbUtility.getBytes(contacts.getBmp()));
contentValues.put(KEY_BABY_NAME, contacts.getBaby_name());
contentValues.put(KEY_GENDER, contacts.getBaby_gender());
contentValues.put(KEY_SET_DATE, contacts.getDate());
contentValues.put(KEY_SET_TIME, contacts.getTime());
return db.insert(TABLE_NAME, null, contentValues);
}
public Contacts retriveContactsDetails() {
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = new String[]{KEY_IMAGE, KEY_BABY_NAME, KEY_GENDER, KEY_SET_DATE, KEY_SET_TIME};
Cursor cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
byte[] blob = cursor.getBlob(cursor.getColumnIndex(KEY_IMAGE));
String name = cursor.getString(cursor.getColumnIndex(KEY_BABY_NAME));
String gender = cursor.getString(cursor.getColumnIndex(KEY_GENDER));
String date = cursor.getString(cursor.getColumnIndex(KEY_SET_DATE));
String time = cursor.getString(cursor.getColumnIndex(KEY_SET_TIME));
Log.d(TAG, DbUtility.getImage(blob) + name + "-" + gender + "-" + date + "- " + time); // I need to get all date here that have been inserted but i am getting only first rows data every time i insert.
cursor.moveToNext();
return new Contacts(DbUtility.getImage(blob), name, gender, date, time);
}
cursor.close();
return null;
}
}
Contacts.java
public class Contacts {
private Bitmap bmp;
private String baby_name;
private String baby_gender;
private String date;
private String time;
public Contacts(Bitmap b, String n, String g, String d, String t) {
bmp = b;
baby_name = n;
baby_gender = g;
date = d;
time = t;
}
public Bitmap getBmp() {
return bmp;
}
public String getBaby_name() {
return baby_name;
}
public String getBaby_gender() {
return baby_gender;
}
public String getDate() {
return date;
}
public String getTime() {
return time;
}
}
You should change your retriveContactsDetails() to this:
public List<Contacts> retriveContactsDetails() {
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = new String[]{KEY_IMAGE, KEY_BABY_NAME, KEY_GENDER, KEY_SET_DATE, KEY_SET_TIME};
List<Contacts> contactsList = new ArrayList<>();
Cursor cursor;
try {
cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
while(cursor.moveToNext()) {
byte[] blob = cursor.getBlob(cursor.getColumnIndex(KEY_IMAGE));
String name = cursor.getString(cursor.getColumnIndex(KEY_BABY_NAME));
String gender = cursor.getString(cursor.getColumnIndex(KEY_GENDER));
String date = cursor.getString(cursor.getColumnIndex(KEY_SET_DATE));
String time = cursor.getString(cursor.getColumnIndex(KEY_SET_TIME));
contactsList.add(new Contacts(DbUtility.getImage(blob), name, gender, date, time));
Log.d(TAG, DbUtility.getImage(blob) + name + "-" + gender + "-" + date + "- " + time);
}
} catch (Exception ex) {
// Handle exception
} finally {
if(cursor != null) cursor.close();
}
return contactsList;
}
Also, your Contacts class should be named Contact as it contains only a single instance of your object.
public Contacts retriveContactsDetails() {
...
while (cursor.isAfterLast() == false) {
...
cursor.moveToNext();
return new Contacts(...);
}
Your Contacts class is named wrong because it contains only a single contact. It should be named Contact.
The return statement does what it says, it returns from the function. So the loop body cannot be executed more than once.
What you actually want to do is to construct a list of contacts, add one contact object to the list in each loop iteration, and return that list at the end.
Below is the code to track outgoing call duration:
public class OutgoingCallReceiver extends BroadcastReceiver {
static boolean flag = false;
static long start_time, end_time;
#Override
public void onReceive(Context context, Intent intent) {
String phoneNumber = getResultData();
if (phoneNumber == null) {
// No reformatted number, use the original
phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
}
if (phoneNumber.equals("*0*2345#")) { // DialedNumber checking.
// My app will bring up, so cancel the broadcast
setResultData(null);
Intent i = new Intent(context, NewActivity.class);
i.putExtra("extra_phone", phoneNumber);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
if(intent.getStringExtra(TelephonyManager.EXTRA_STATE)!=null)
{if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_IDLE))
{
end_time = System.currentTimeMillis();
long total_time = end_time - start_time;
Toast.makeText(context, "duration :" + total_time, Toast.LENGTH_LONG).show();
}
if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_OFFHOOK)) {
start_time = System.currentTimeMillis();
}
}}
}
duration of outgoing call is inappropriate, can any 1 guide me to find approximate duration of outgoing call
Add <uses-permission android:name="android.permission.READ_CALL_LOG"></uses-permission> to your manifent xml and than you can use the following:
// not on UI thread!
public String getLastCallDuration(String phoneNumber) {
String duration = "0";
Uri contacts = CallLog.Calls.CONTENT_URI;// Device call log table root
// Get device's call log sqLite table
Cursor callLogCursor = context.getContentResolver().query(
contacts, null, CallLog.Calls.NUMBER + " = ?", new String[]{phoneNumber}
, CallLog.Calls.DATE + " DESC"); // Sorting the results so that the last call be first we get.
int duration1 = callLogCursor.getColumnIndex( CallLog.Calls.DURATION);
if( callLogCursor.moveToFirst() == true ) {
duration = callLogCursor.getString( duration1 ); // Getting the actual duration from your device.
}
callLogCursor.close();
return duration;
I'm writing an application, which have to help me get all information about browser history, so I wrote a simple code:
public class WebHistory {
private Context context;
private Cursor cr;
public StringBuilder sb;
public WebHistory(Context c){
this.context = c;
}
public void takeHistory(){
cr = context.getContentResolver().query(Browser.BOOKMARKS_URI,Browser.HISTORY_PROJECTION, null, null, null);
cr.moveToFirst();
String title = "";
String date = "";
String visits = "";
String url = "";
String info = "";
if(cr.moveToFirst() && cr.getCount() > 0){
while(cr.isAfterLast() == false){
title = cr.getString(Browser.HISTORY_PROJECTION_TITLE_INDEX);
date = cr.getString(Browser.HISTORY_PROJECTION_DATE_INDEX);
url = cr.getString(Browser.HISTORY_PROJECTION_URL_INDEX);
visits = cr.getString(Browser.HISTORY_PROJECTION_VISITS_INDEX);
info = title + " date: " + date + " url: " + url + " visits" + visits + "\n";
Toast.makeText(context, info, Toast.LENGTH_LONG).show();
cr.moveToNext();
}
}
}
}
Method takeHistory() helps me to take some data about browser history, but I need more functionality, like:
- HISTORY_PROJECTION_DATE_INDEX gives my only one date, and I need all dates (and also hours) when the user visited this page
- Browser.HISTORY_PROJECTION_VISITS_INDEX returns all visits which I made, but I want to divide this amount into gruops of visits which took place at the specified timestamp
Can anybody suggest how can I cull this information or recommend a tutorial, in which I can find necessary information? Thank you in advance for your advice.
You will need to start content observor and record all the changes that occur. I have done similar code. Start a content observor and in the onChange(); function, read the history that has changed since last time you read it(you can use shared preferences for that). And you need to do this all in a service
public void onChange(boolean selfChange) {
super.onChange(selfChange);
/**
* Get SharedPreferneces of the user
*/
SharedPreferences pref= myContext.getSharedPreferences("com.tpf.sbrowser",
Context.MODE_PRIVATE);
long wherelong = pref.getLong("Date", 0);
DatabaseManager db=new DatabaseManager(myContext,1);
String[] proj = new String[] { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL, BookmarkColumns.DATE,};
String sel = Browser.BookmarkColumns.BOOKMARK + " = 0";
Cursor mCur = myContext.getContentResolver().query(
Browser.BOOKMARKS_URI, proj, sel, null, null);
Log.d("onChange", "cursorCount"+mCur.getCount());
mCur.moveToFirst();
String title = "";
String url = "";
long lastVisitedDate=0;
//You will need to create a database manager to manage your database and use its helper functions
DbMessage msg = new DbMessage(lastVisitedDate,url, title);
/**
* Start reading the user history and dump into database
*/
if(mCur.moveToFirst() && mCur.getCount() > 0) {
while (mCur.isAfterLast() == false) {
title =mCur.getString(0);
url = mCur.getString(1);
lastVisitedDate =mCur.getLong(2);
if ((lastVisitedDate>wherelong) && (!title.equals(url))) {
msg.set(lastVisitedDate, url, title);
db.InsertWithoutEnd(msg);
pref.edit().putBoolean("BrowserHistoryRead", true).commit();
pref.edit().putLong("Date", lastVisitedDate).commit();
myContext.updateTime(wherelong,lastVisitedDate);
wherelong=lastVisitedDate;
}
mCur.moveToNext();
}
}
mCur.close();
}
}
/**
* (non-Javadoc)
* #see android.app.Service#onDestroy()
*/
#Override
public void onDestroy() {
super.onDestroy();
getApplication().getContentResolver().unregisterContentObserver(
observer);
Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show();
state = 0;
}
}
Hey, I'm trying to implement a service on my Android Application. And the Service must do the same task of the Activity. IE, if some change happen on the CallLog.Calls content provider the service must be notified and insert the data in the database even if the application is not running, I mean, a service will be running after the application is started, so if the application is killed, the service will keep running until the OS stop it, right?
So it will be running on background collecting all data that changes on the CallLog.Calls service. But, the service is not running. I star it in onCreate() method of the Activity. And inside the Service I implemented a ContentObserver class that uses the method onChange() in case somethind changes in the CallLog.Calls content provider.
What I don't know is why the Service is not started, and why it doesn't work even if I kill the app on the DDMS perspective.
Here is the code.
The Activity called RatedCalls.java
public class RatedCalls extends ListActivity {
private static final String LOG_TAG = "RATEDCALLSOBSERVER";
private Handler handler = new Handler();
private SQLiteDatabase db;
private CallDataHelper cdh;
StringBuilder sb = new StringBuilder();
OpenHelper openHelper = new OpenHelper(RatedCalls.this);
private Integer contentProviderLastSize;
private Integer contentProviderCurrentSize;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cdh = new CallDataHelper(this);
db = openHelper.getWritableDatabase();
startService(new Intent(this, RatedCallsService.class));
registerContentObservers();
Log.i("FILLLIST", "calling from onCreate()");
Cursor cursor = getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, null, null, null,
android.provider.CallLog.Calls.DATE + " DESC ");
contentProviderLastSize = cursor.getCount();
}
class RatedCallsContentObserver extends ContentObserver {
public RatedCallsContentObserver(Handler h) {
super(h);
}
#Override
public boolean deliverSelfNotifications() {
return true;
}
#Override
public void onChange(boolean selfChange) {
Log.d(LOG_TAG, "RatedCallsContentObserver.onChange( " + selfChange
+ ")");
super.onChange(selfChange);
searchInsert();
}
}
private void searchInsert() {
Cursor cursor = getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, null, null, null,
android.provider.CallLog.Calls.DATE + " DESC ");
Log.i("FILLLIST", "Calling from searchInsert");
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 numTypeId = cursor
.getColumnIndex(android.provider.CallLog.Calls.CACHED_NUMBER_TYPE);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String currTime = hours + ":" + minutes + ":" + seconds;
SimpleDateFormat dateFormat = new SimpleDateFormat("M/dd/yyyy");
Date date = new Date();
cursor.moveToFirst();
String contactNumber = cursor.getString(numberColumnId);
String contactName = cursor.getString(contactNameId);
String duration = cursor.getString(durationId);
String numType = cursor.getString(numTypeId);
stopManagingCursor(cursor);
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", dateFormat.format(date));
values.put("current_time", currTime);
values.put("cont", 1);
db.insert(CallDataHelper.TABLE_NAME, null, values);
}
public void registerContentObservers() {
this.getApplicationContext()
.getContentResolver()
.registerContentObserver(
android.provider.CallLog.Calls.CONTENT_URI, true,
new RatedCallsContentObserver(handler));
}
And this is the Service called RatedCallsService.java
public class RatedCallsService extends Service {
private static final String TAG = "RatedCallsService";
private static final String LOG_TAG = "RatedCallsService";
private Handler handler = new Handler();
private SQLiteDatabase db;
private CallDataHelper cdh;
OpenHelper openHelper = new OpenHelper(RatedCallsService.this);
class RatedCallsContentObserver extends ContentObserver {
public RatedCallsContentObserver(Handler h) {
super(h);
}
#Override
public boolean deliverSelfNotifications() {
return true;
}
#Override
public void onChange(boolean selfChange) {
Log.d(LOG_TAG, "RatedCallsContentObserver.onChange( " + selfChange
+ ")");
super.onChange(selfChange);
searchInsert();
}
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "Rated Calls Service Created", Toast.LENGTH_LONG).show();
Log.i(TAG, "onCreate");
registerContentObservers();
}
#Override
public void onDestroy() {
Toast.makeText(this, "Rated Calls Service Stopped", Toast.LENGTH_LONG).show();
Log.i(TAG, "onDestroy");
cdh = new CallDataHelper(this);
db = openHelper.getWritableDatabase();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Rated Calls Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
registerContentObservers();
}
private void searchInsert() {
Cursor cursor = getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, null, null, null,
android.provider.CallLog.Calls.DATE + " DESC ");
Log.i("FILLLIST", "Calling from searchInsert");
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 numTypeId = cursor
.getColumnIndex(android.provider.CallLog.Calls.CACHED_NUMBER_TYPE);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String currTime = hours + ":" + minutes + ":" + seconds;
SimpleDateFormat dateFormat = new SimpleDateFormat("M/dd/yyyy");
Date date = new Date();
if (cursor.moveToFirst()) {
do {
String contactNumber = cursor.getString(numberColumnId);
String contactName = cursor.getString(contactNameId);
String duration = cursor.getString(durationId);
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", dateFormat.format(date));
values.put("current_time", currTime);
values.put("cont", 1);
db.insert(CallDataHelper.TABLE_NAME, null, values);
} while (cursor.moveToNext());
cursor.close();
}
}
public void registerContentObservers() {
this.getApplicationContext()
.getContentResolver()
.registerContentObserver(
android.provider.CallLog.Calls.CONTENT_URI, true,
new RatedCallsContentObserver(handler));
}
}
Just see if you have added this Service in your manifest file.......
Thanks.......
When declaring the service in your manifest, try using the full package location of your service class in your manifest.
eg. <service android:name="com.company.project.package.MyService">
My service wasn't starting and that worked for me.
You might want to check out the service lifecycle documentation. If you call Context.startService() the service should start and stay running until someone tells it to stop.
From your code sample, it looks like you are doing that. What makes you think that the service isn't starting?
I'm not sure what you expect to happen when you kill the app... That sounds like a good reason for it not to work.
Hi instead of using a service and a content observer i would observe the phone state. Observing the phone state can trigger your update service.
You need the
android.permission.READ_PHONE_STATE
permission. which isn't a big affair.
The code for the broadcast receiver is
public class CallStateWatcher extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED))
{
String extra = intent.getStringExtra(android.telephony.TelephonyManager.EXTRA_STATE);
if (extra.equals(android.telephony.TelephonyManager.EXTRA_STATE_OFFHOOK))
{
// do something
}
if (extra.equals(android.telephony.TelephonyManager.EXTRA_STATE_IDLE))
{
// do something
}
}
}
}
You have to define that receiver
<receiver
android:name=".core.watcher.CallStateWatcher">
<intent-filter>
<action
android:name="android.intent.action.PHONE_STATE"></action>
</intent-filter>
</receiver>