I'm stuck with the call_log functionality in Froyo. As many of you know, Froyo logs in call log not only calls but also each outgoing and incomming SMS message. You can chose in options to show all that crap, or only specific types (outgoing calls, incoming calls, sent messages, received messages etc), but since this is radio button, you cannot specify for example only ongoing and incoming calls. Very known and annoing Froyo functionality.
So I started to write some simple tool to read the call log by myself. Here is the code snippet:
try {
mCur = getApplicationContext().getContentResolver()
.query(CallLog.Calls.CONTENT_URI, columns, null, null, null );
mCur.moveToFirst();
io = mCur.getColumnIndex(CallLog.Calls._ID);
bo = mCur.getColumnIndex(CallLog.Calls.NUMBER);
no = mCur.getColumnIndex(CallLog.Calls.CACHED_NAME);
to = mCur.getColumnIndex(CallLog.Calls.TYPE);
while (mCur.isAfterLast() == false) {
i = mCur.getString(io);
b = mCur.getString(bo);
n = mCur.getString(no);
t = mCur.getString(to);
Log.i(TAG, "CallLog: ID="+i+" number="+b+" name="+n+" type="+t);
mCur.moveToNext();
}
} catch (Exception e) {
Log.e(TAG, "updateCallLog", e);
} finally {
if (mCur != null) {
mCur.close();
mCur = null;
}
}
Surprise, surprise, the call_log provider skips the sms records from the call log. So with the code above I see only call records (incoming or outgoing), all other records are skipped. The little more digging into it revealed that the CallLog provider adds internally filtering to the call log database:
02-03 09:26:42.348 E/CLCService(28244): android.database.sqlite.SQLiteException:
near ")": syntax error: , while compiling:
SELECT _id, name, number, type FROM logs WHERE (logtype=100 OR logtype=500) AND (_ID=)
Do not look for the syntax error, it was created on purpose to force provider to dump the SQL query by calling query(CallLog.Calls.CONTENT_URI, columns, "_ID=", null, null )). The (_ID=) is what is provided in the query, the rest of (logtype=100 OR logtype=500) is apparently added by the call log provider itself.
So I have two questions:
Where I can find in the Android code how the provider is adding the logtype filter? I was looking into CallLog.java and CallLogProvider.java and cannot find it.
How can I read all records from the call log in Froyo? I cannot bypass the call log provider and use my own SQL helper for this until I will not root the phone, which is not an option. Is there any other way to do it?
I'm not certain just what is going wrong but reading the call log to get just incoming or outgoing calls is simple enough. The sample below adds restrictions to the query so that it only returns data for outgoing calls made after a certain date. The where string uses question marks to indicate where the values from the wargs array should be substituted in to form the sql query.
About where the extra WHERE clause occurs. Almost certainly in the calllog provider implementation. The providers commonly have a switch statement that uses the uri that you use to open the provider and then adds restrictions based on the uri. The calllog one seems to be in packages/providers/ContactsProvider.
public static int getMinutesUsedSince(Context context, Date date) {
Uri uri = CallLog.Calls.CONTENT_URI;
String columns[] = new String[] { CallLog.Calls.DURATION };
String where = CallLog.Calls.TYPE + "=? AND " + CallLog.Calls.DATE + ">?";
String wargs[] = new String[] {
String.valueOf(CallLog.Calls.OUTGOING_TYPE),
String.valueOf(date.getTime())
};
String sortOrder = "date DESC";
Cursor c = context.getContentResolver().query(uri, columns, where, wargs, sortOrder);
long sum = 0;
int durationIndex = c.getColumnIndex(CallLog.Calls.DURATION);
if (c.moveToFirst()) {
do {
/* for each individual call, round up to the nearest minute */
long duration = c.getLong(durationIndex);
long minutes = (long)Math.ceil(duration / 60.0);
sum += minutes;
} while (c.moveToNext());
}
c.close();
return (int)sum;
}
Related
For a Contacts backup app, I save all the information to a CSV file, and then I need to restore it back. It works great, however if I press restore twice, it duplicates all the contacts.
I tried the following code to remove duplicates, it does work but fails in certain cases.
Basically it fails when there is no explicit DISPLAY_NAME, for e.g. if a contact seems to only have a phone number and the DISPLAY_NAME is the phone number, or same for an email address. I cannot understand why it wont always work since it does seem that the DISPLAY_NAME field contains phonenumber/email address.
Here is the code that I used:
private boolean contactExists(String displayname, String emailstring, String phonestring){
Cursor crsr = BA.applicationContext.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI,
new String[] { "display_name", "_id"},
"display_name = ? ",
new String[] {displayname},
null);
while (crsr.moveToNext()){
HashMap m = new HashMap();
for (int col = 0; col < crsr.getColumnCount(); col++) {
m.put(crsr.getColumnName(col), Integer.valueOf(col));
}
int id = crsr.getInt(((Integer)m.get("_id")).intValue());
String emails = GetEmails(id);
String phones = GetPhones(id);
if (emails.contentEquals(emailstring) && phones.contentEquals(phonestring))
{
crsr.close();
return true;
}
}
crsr.close();
return false;
}
UPDATE:
I tried with DISPLAY_NAME_PRIMARY with the same results.
However what I noticed is that, if I create the contacts on the same device/emulator, the duplicate is detected, when I re-restore the same contacts.
On going across devices, it seems that one reason it does not work is that at some point the special characthers are removed.
For e.g. the display name "John.Doe" is read from the CSV, but when it gets inserted, it becomes "John Doe". I cannot see where in the code the "." is ever stripped out.
What happens depends on the version of Android the device is running. If the version is Honeycomb (3.0) or later, the contact will always have a name. The name field is DISPLAY_NAME_PRIMARY, and if there's no name in any of the raw contacts, this field is set to a phone number or email address.
It's hard to know exactly what's going on with your code, because I can't tell how you're calling contactExists in all cases. But my guess is that you're looking at DISPLAY_NAME, when you may want to look at DISPLAY_NAME_PRIMARY.
As a side comment, what you're trying to do here is fraught with peril. The contacts provider is a complex system, and backing it up to a CSV may cause a lot of problems down the road. A much better strategy is to run a sync between the contacts provider and the cloud-based Google Contacts app.
Here is the code which finds duplicate contact. You need to pass the "NAME" as string and it will look for duplicate. It works in ICS but didn't check in GB, so basically you need to try your luck.
/**
* #param name
* #param context
* #return
*/
public boolean isContactExist(String name) {
boolean result = false;
try {
ContentResolver contentResolver = getContentResolver();
Uri uri = Data.CONTENT_URI;
String[] projection = new String[] { PhoneLookup._ID,
PhoneLookup.LOOKUP_KEY };
String selection = StructuredName.DISPLAY_NAME + " = ?";
String[] selectionArguments = { name };
Cursor cursor = contentResolver.query(uri, projection, selection,
selectionArguments, null);
if (cursor != null) {
while (cursor.moveToNext()) {
/*
* Log.i(TAG, "KEY = " + cursor.getString(cursor
* .getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)));
*/
result = true;
}
}
cursor.close();
} catch (Exception e) {
result = false;
e.printStackTrace();
}
return result;
}
Lets say that i have 100 calls in my call log. I want to find the unique contacts (not numbers) that they have been called.
The problem is that if a contact has two phone numbers (e.g. for Contact A i have a number for home and another for mobile) i will count that contact twice!
I tried the following.
I am reading the call log. Then for each number of the call log i call the following custom function:
private String getContactID (String number)
{
String contactID = "";
ContentResolver context = getContentResolver();
/// number is the phone number
Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,Uri.encode(number));
String[] mPhoneNumberProjection = { PhoneLookup._ID };
Cursor cur = context.query(lookupUri,mPhoneNumberProjection, null, null, null);
try
{
if (cur.moveToFirst())
{
contactID = cur.getString(0);
return contactID;
}
}
finally
{
if (cur != null)
cur.close();
}
return contactID;
}
So then i have a calllog with contact ids and timestamp of the call and using a Set i get the unique...
The above code works fine BUT the performance if very poor! I tried it in a new Google Nexus 4 and it takes about 1600 msec! I don't want to think about older smart phones...
Any suggestions?
Use a background thread to lazy load the information in a ListView.
Initially fetch only about 10 results and display them in the list. That should happen fast. After that, in the background thread, keep on fetching information, 10 at a time, and keep on adding them to your list.
I want to get the count of missed calls and unread messages in my application. and I'd like to open the relevant application when user click on the count.
Now biggest problem is how to get the count?
I searched online but couldn't find any solution.
Thanks in advance.
http://developer.android.com/reference/android/provider/CallLog.Calls.html
Take a look at this CallLog class. All you need is to query the phone for any calls then extract missed one (оr do this when you are querying the phone, in the selection arguments). The same applies for the messages. SMS are stored in the Content provider under "content://sms/"
Then just get the count of rows in the Cursor that is return by the query. :)
I hope this helps.
For missed calls:
String[] projection = {
CallLog.Calls.CACHED_NAME,
CallLog.Calls.CACHED_NUMBER_LABEL,
CallLog.Calls.TYPE
};
String where = CallLog.Calls.TYPE + "=" + CallLog.Calls.MISSED_TYPE;
Cursor c = this.getContentResolver().query(
CallLog.Calls.CONTENT_URI,
selection,
where,
null,
null
);
c.moveToFirst();
Log.d("CALL", ""+c.getCount()); //do some other operation
if (c.getCount() == SOME_VALUE_TO_START_APP_ONE) //...etc etc
In the where clause you set condition for selection of data. In our case we need everything which type equals CallLog.Calls.MISSED_TYPE. We select project the Name of the caller and his number, ofcourse you can specify more information to be queried like type of number like mobile, home, work.
The expression is equivalent to SQL query, something like: SELECT CACHED_NAME, CACHED_NUMBER_LABEL, TYPE FROM CONTENT_URI WHERE TYPE=MISSED_TYPE
This requires permissions to be added to the Manifest
<uses-permission android:name="android.permission.READ_LOGS"></uses-permission>
<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
For querying SMS ContentProvider:
Uri sms_content = Uri.parse("content://sms");
Cursor c = this.getContentResolver().query(sms_content, null,null, null, null);
c.moveToFirst();
Log.d("SMS COUNT", "" + c.getCount()); //do some other operation
// Here proceed with the what you wanted
if (c.getCount() == SOME_VALUE_TO_START_APP_ONE)//...etc etc
You can go deeper in the content tree like specifying the type of sms, like: content://sms/sent or content://sms/inbox and add projection and selection for the second argument of the query() method like, name, person, status of the message (like the Calls example).
This requires permission:
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
As I don't have enough reputation to answer #Prasad question comment about
ERROR -> getContentResolver() is undefined for the type new Runnable(){}
getContentResolver() is part of application context, so if you are using a BroadcastReceiver use context in onReceive() function like this
#Override
public void onReceive(Context context, Intent intent) {
context.getContentResolver()
}
If you are using the code above inside an Activity, then you can use
getApplicationContext().getContentResolver()
also make sure to use [Ctrl + Shift + O (O not zero)] to organize imports
Key Shortcut for Eclipse Imports
I'm wondering if the following is possible:
I've an app (service) that stays in background, and gets triggered whenever the user
Adds/deletes/updates a contact
Installs/uninstalls an app
Adds/deletes/renames a file on the FS
Do you think this is possible guys? (in a proper way of course, if it's possible to do it by hacking and dirty stuff I'd pass)
I tried to look over the internet a bit but didn't find discussions related to this point.
What's your guess ?
Haven't tried any of this myself, but:
http://mylifewithandroid.blogspot.com/2008/03/observing-content.html seems to deal with detecting contact data changes. Basically you need to register a ContentObserver and handle the changes you are notified of.
Check out http://developer.android.com/reference/android/content/Intent.html - from that you can register a BroadcastReceiver to be notified of applications being installed or uninstalled. Look for ACTION_PACKAGE_ADDED and ACTION_PACKAGE_REMOVED
Please refer to How to detect file or folder changes in Android? for how to detect when files are changed in the filesystem. You may be limited to your sandbox with a FileObserver, I'm not sure. Also - a rename doesn't seem to be explicitly notified, but you will probably detect it from a MOVED_FROM followed by MOVED_TO, or possibly a DELETE followed by CREATE
Found in the SDK sample for SDK version 5+:
/**
* Retrieves the contact information.
*/
#Override
public ContactInfo loadContact(ContentResolver contentResolver, Uri contactUri) {
ContactInfo contactInfo = new ContactInfo();
long contactId = -1;
// Load the display name for the specified person
Cursor cursor = contentResolver.query(contactUri,
new String[]{Contacts._ID, Contacts.DISPLAY_NAME}, null, null, null);
try {
if (cursor.moveToFirst()) {
contactId = cursor.getLong(0);
contactInfo.setDisplayName(cursor.getString(1));
}
} finally {
cursor.close();
}
// Load the phone number (if any).
cursor = contentResolver.query(Phone.CONTENT_URI,
new String[]{Phone.NUMBER},
Phone.CONTACT_ID + "=" + contactId, null, Phone.IS_SUPER_PRIMARY + " DESC");
try {
if (cursor.moveToFirst()) {
contactInfo.setPhoneNumber(cursor.getString(0));
}
} finally {
cursor.close();
}
return contactInfo;
}
You can specify the contact columns you want to retreive with Cursor cursor = contentResolver.query(contactUri, new String[]{Contacts._ID, Contacts.DISPLAY_NAME}, null, null, null); The column names are described at http://developer.android.com/reference/android/provider/ContactsContract.Contacts.html and looking at the sample, it seems cursor.getLong(0) here is the contact ID you're looking for. It also seems that it is volatile depending on how the contact is edited and how others are added, but you're catching those too so you should be able to handle those cases.
in my app I should do some action when a call comes but not answered by the user.
I have searched in the android.telephony and the NotificationManager, but I haven't found a method to solve this problem.
Does someone have an idea of how to get to know if there is a missed call on the phone or not ?
Here is code that can query the call log for a missed call. Basically, you will have to trigger this somehow and make sure that you give the call log some time ( a few seconds should do it) to write the information otherwise if you check the call log too soon you will not find the most recent call.
final String[] projection = null;
final String selection = null;
final String[] selectionArgs = null;
final String sortOrder = android.provider.CallLog.Calls.DATE + " DESC";
Cursor cursor = null;
try{
cursor = context.getContentResolver().query(
Uri.parse("content://call_log/calls"),
projection,
selection,
selectionArgs,
sortOrder);
while (cursor.moveToNext()) {
String callLogID = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls._ID));
String callNumber = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
String callDate = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.DATE));
String callType = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.TYPE));
String isCallNew = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.NEW));
if(Integer.parseInt(callType) == MISSED_CALL_TYPE && Integer.parseInt(isCallNew) > 0){
if (_debug) Log.v("Missed Call Found: " + callNumber);
}
}
}catch(Exception ex){
if (_debug) Log.e("ERROR: " + ex.toString());
}finally{
cursor.close();
}
I hope you find this useful.
From what I understand, you need to query the CallLog provider (or maybe CallLog.Calls), and this page explains how to query content provider: http://developer.android.com/guide/topics/providers/content-providers.html#basics
I'd be happy to see the code if you can make this work !
I suppose you have content providers to access call logs.
http://www.anddev.org/video-tut_-_querying_and_displaying_the_calllog-t169.html
http://www.devx.com/wireless/Article/41133
If this code works you just need to run this query at the right time. I mean check some samples that can notify you when you get a call in your device
http://groups.google.com/group/android-developers/browse_thread/thread/d97a759a3708cbe3
Once you get this notification put a timer or use some built in Intents to find that the phone is back to normal state and access the call logs...
Possible duplicate
broadcast receiver for missed call in android
Show Toast on Missed Call in android application