Wednesday, September 4, 2013

Android Call History Example | How to Get Phone Call Record in Android | Read Call History in Android Phone | Code for Get Phone Call Record in Android

Hello Friends!
Today I am going to share very important code for get phone call history in Android. Don't forget to add
permission-
<android:name="android.permission.READ_CALL_LOG"/>


MainActivity.java


package com.manish.callhistory;

import java.util.Date;

import com.manish.callhistory.R;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CallLog;
import android.widget.TextView;

public class MainActivity extends Activity {
 TextView textView = null;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  textView = (TextView) findViewById(R.id.textview_call);
  getCallDetails();
 }

 private void getCallDetails() {

  StringBuffer sb = new StringBuffer();
  Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null,
    null, null, null);
  int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
  int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
  int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
  int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
  sb.append("Call Log :");
  while (managedCursor.moveToNext()) {
   String phNumber = managedCursor.getString(number);
   String callType = managedCursor.getString(type);
   String callDate = managedCursor.getString(date);
   Date callDayTime = new Date(Long.valueOf(callDate));
   String callDuration = managedCursor.getString(duration);
   String dir = null;
   int dircode = Integer.parseInt(callType);
   switch (dircode) {
   case CallLog.Calls.OUTGOING_TYPE:
    dir = "OUTGOING";
    break;

   case CallLog.Calls.INCOMING_TYPE:
    dir = "INCOMING";
    break;

   case CallLog.Calls.MISSED_TYPE:
    dir = "MISSED";
    break;
   }
   sb.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
     + dir + " \nCall Date:--- " + callDayTime
     + " \nCall duration in sec :--- " + callDuration);
   sb.append("\n----------------------------------");
  }
  //managedCursor.close();
  textView.setText(sb);
 }

}

activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ScrollView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/textview_call"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true" />
    </ScrollView>

</RelativeLayout>

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.manish.callhistory"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <android:name="android.permission.READ_CALL_LOG"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.manish.callhistory.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Thanks!

124 comments:

  1. Good effort man.Every time you are posting interesting topics.Carry on...

    ReplyDelete
  2. Great Little Tutorial !........Thank you

    ReplyDelete
  3. Hello manish, I always read your blog it is very helpful to me and others who want learn android. you always reply all off your visitors questions i like it.really you have good knowledge in your domain, you are my role model, i want be like you.i want talk with you can i have your phone number please? if you don't mind.

    thanks,
    payal

    ReplyDelete
    Replies
    1. Thanks! Thanks! Thanks ! Thanks! Thanks!
      But phone number why? If you need any please post your query here are make me email at my email-id manishupacc@gmail.com
      :)

      Delete
    2. Actually i am working on face deduct application and i am facing some trouble. can you please help me? i want discuss my problem with you.
      Please help me--------

      Delete
    3. Okay you can ping me at manishupacc@gmail.com

      Thanks!

      Delete
  4. hello..actually i want to save complete log in arraylist so i could view contact pic associated with the number...

    ReplyDelete
    Replies
    1. So you can save it into ArrayList and display it in listview. you should create custom adapter and arraylist like. And please mind it in below version of devices you can't get Contact Image.

      Delete
  5. hello..nice tutorial.. but i have error at managedQuery(CallLog.Calls.CONTENT_URI, null,
    null, null, null);

    ReplyDelete
    Replies
    1. No worry its only because of depriciate method. Just search for another option on google or leave it as it is. It will work with out issue.

      Delete
    2. This comment has been removed by the author.

      Delete
    3. This comment has been removed by the author.

      Delete
  6. hii managedQuery(CallLog.Calls.CONTENT_URI, null,
    null, null, null); is not working in listfragment

    ReplyDelete
  7. hii sir..am following your blog.. thank u so much..and how to get specific contact call history..

    ReplyDelete
    Replies
    1. where you are getting all contact call history, just create a condition like-

      while (managedCursor.moveToNext()) {
      String phNumber = managedCursor.getString(number);

      if(phNumber.equles"08888888888"){

      String callType = managedCursor.getString(type); String callDate = managedCursor.getString(date); Date callDayTime = new Date(Long.valueOf(callDate)); String callDuration = managedCursor.getString(duration); String dir = null; int dircode = Integer.parseInt(callType); switch (dircode) { case CallLog.Calls.OUTGOING_TYPE: dir = "OUTGOING"; break; case CallLog.Calls.INCOMING_TYPE: dir = "INCOMING"; break; case CallLog.Calls.MISSED_TYPE: dir = "MISSED"; break; } sb.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- " + dir + " \nCall Date:--- " + callDayTime + " \nCall duration in sec :--- " + callDuration); sb.append("\n----------------------------------"); } //managedCursor.close(); textView.setText(sb); }

      }

      }

      I have not check it may be syntax error in code but logic is only this. so please check and modify.

      Thanks!

      Delete
    2. This comment has been removed by the author.

      Delete
  8. Is it also work for android version 4.2??

    ReplyDelete
  9. i am getting error while running on emulator "unfortunately callhistory is stopped"
    & im getting question mark @ the line
    Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null, null, null, null);

    plz help me with this !! ASAP

    ReplyDelete
    Replies
    1. Your emulator have phone contact? If yes sure it should work..

      Delete
  10. there is no error but i m getting only a blank page when i m running it on my android phone

    ReplyDelete
  11. if i want to send the details on a server what else should i have to do it in that

    ReplyDelete
    Replies
    1. Hi Archna, If everything Okay and you have call history sure it should work. It is working code and for send call history on server you should use Async class. Please check this demo-

      http://www.androidhub4you.com/2013/03/main-thread-issue-in-android-async.html

      Delete
    2. thank you sir, but i m unable to get the output. i installed the app on my android phone it asked for permission of reading the contacts and it got installed successfully. Still when i m opening it i m only getting a blank page.

      Delete
  12. hello sir, still the problem is not solved i wrote the code again but i m getting an error "unfortunately, callhistory has stopped. " both on phone as well as emulator. please help to sort it out.

    ReplyDelete
    Replies
    1. is read contacts permission in your manifest?
      android:name="android.permission.READ_CONTACTS"

      Delete
    2. In my phone it is working fine without any permission but you can try this one too-
      android:name="android.permission.READ_CALL_LOG"

      may be it will work for you..

      Delete
    3. thank you so much sir. :) .
      its working fine with this permission android:name="android.permission.READ_CALL_LOG".

      Delete
    4. Thank God and thanks to Shariat, see below comment...
      well on some device it is working without any permission :) but i don't know why ..

      Delete
    5. sir can you please help me with two more codes???

      Delete
    6. if i have any demo code or any link sure i will provide.

      Delete
    7. we have to get all the details of the msg sent and received from an android mobile, and moreover if we get the details of the activity done by the person on whatsapp and facebook

      Delete
    8. 1) yes you can get all send/receive messages list, if you need code please share your email-id.
      2)getting facebook and whatsapp activity some tricky, i have never try it. you should use their APIs.

      Delete
    9. thanks you so much :) my email-id is archnalal1992@gmail.com

      Delete
    10. Download from here-
      http://www.androidhub4you.com/2014/02/android-sms-history-get-messages-record.html

      https://github.com/manishsri01/SMSHistoryDemo

      Delete
  13. This comment has been removed by the author.

    ReplyDelete
  14. Following permissions are required
    1. READ_CALL_LOG
    2. WRITE_CALL_LOG

    ReplyDelete
    Replies
    1. Thanks dear but here we are only reading contacts so we need only this permission-
      android:name="android.permission.READ_CALL_LOG"
      Well in my phone it is working without Call_Log permission like we don't need to give camera permission.

      Delete
  15. Nice Tutorial, helped me. Thank you.....

    ReplyDelete
  16. Nice tutorial and i just want to ask is it possible to use this coding for charge log instead of call log? if not can you please teach me how to do it...i searched everywhere to find the coding for charge log but still it is hopeless.

    ReplyDelete
    Replies
    1. Charge log means? Battery charging status? or you want know about call charges when you make call to someone? if yes then it is not possible. It is possible only by your network service provider.

      Delete
    2. Yes, it is for battery charging status, the data which is the time, date, level and status will be recorded each time the USB connected to the phone for charging. Do you have any idea on how to do it?

      Delete
    3. Check this code-
      private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
      battryLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
      int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);
      int temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
      int voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
      //System.out.println(battryLevel + scale + temp + voltage);
      }
      };

      Delete
  17. thanks Manish. I just did what you explain here, but when i run my program it warns that the project unfortunately stopped. can you help me what am i supposed to do?

    ReplyDelete
    Replies
    1. Please add this permission in your manifest.xml-
      android:name="android.permission.READ_CALL_LOG"

      Delete
    2. thank you very much Manish. Do you know how i can get the missed call duration in milliseconds?

      Delete
    3. In my knowledge you can get the time of miss call but duration of missed call is tough. Sorry no idea.

      Delete
  18. Hi Sir, i need latest ten messages how will write Please send that code

    ReplyDelete
  19. Hi Sir, I need Latest ten call log number , how will write please send that code Sir ..........................

    ReplyDelete
  20. hey can u post call logs example by using providers(android 4.4) and call history should be send to the email.....
    and my id - sravanipractice@gmail.com

    thank u........

    ReplyDelete
  21. hi manish, gud tutorial ....... This code is not working in fragment activity, i am getting an error in this line..Create managed query method...
    Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null, null, null, null);

    ReplyDelete
    Replies
    1. I think you should use Asynck task and it will work..

      Delete
  22. hi manish, I want code for how to import this call log to my sd card as an xml file and is it possible to include call cost?can you please share the code.

    ReplyDelete
  23. the code is not working in real device
    please help

    ReplyDelete
    Replies
    1. Main Thread issue may be here. So try to get call history inside AsYnc task.

      Delete
  24. Hello,

    Its really nice and informative tutorial for us. But I am having 1 query regarding the Call logs, this code works fine with single sim devices but its not working properly in case of dual sim. So can you please kindly guide on this that how can we get logs for dual sim. If the api can't do that then how can we find work around because phones like Micromax, Moto g which are dual sim devices are having in built call logs and they are providing these information correctly so that is absolutely possible but I don't know how to go ahead with that. So it would be really great if you can help me in that.

    Keyur

    ReplyDelete
    Replies
    1. By default it will work for sim-1. So if you need for both you need to do some code.

      Delete
  25. How can i create my own missed call list.plz help me as soon as.thnks in advance.

    ReplyDelete
    Replies
    1. Own means? This is all call record list, you can put/use it any where.

      Delete
  26. this is mistake TextView textView=null;
    solution
    TextView textView

    ReplyDelete
  27. Dear sir,
    I am following you and your blogs are really extraordinary and so helpful to us. Sir, can you please provide the demo application/code for the same? This will be very helpful to me.
    Thank you.
    Regards.

    ReplyDelete
    Replies
    1. Please copy paste form above as it is not much big code..

      Delete
  28. sir,
    your blog really he;ping me a lot thank you,i am trying to develop an application for birthday remainder with the existing birthday data with data.
    can you please suggest me some code or something.

    ReplyDelete
  29. Hi I am getting this error:
    cannot find symbol
    symbol : method managedQuery(android.net.Uri,,,,)
    Do you think its a problem related with some import?

    Thanks!

    ReplyDelete
  30. I Only get Last Missed Call on Text-View so what can i do.????

    ReplyDelete
  31. I want only Outgoing Call details. That as to detect after each call.
    It should be automatic, no need of user interaction.
    It is possible to fetch the detail after each call.?

    ReplyDelete
  32. Hi,Dear Bro ur tutor is realy helpful..i need some related thing,
    i need offnet and onnet call summary ,plz suggest me some code
    Thanks

    ReplyDelete
  33. While run this code i got the following error.so how can i solve this error.please help me...

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.calllog/com.example.calllog.MainActivity}: java.lang.SecurityException: Permission Denial: opening provider com.android.providers.contacts.CallLogProvider from ProcessRecord{414366b0 3471:com.example.calllog/10108} (pid=3471, uid=10108) requires android.permission.READ_CONTACTS or android.permission.WRITE_CONTACTS

    ReplyDelete
    Replies
    1. Had you added permission in your manifest?



      and if needed also add-
      android.permission.READ_CONTACTS
      android.permission.WRITE_CONTACTS

      Delete
    2. this permission needed-
      android:name="android.permission.READ_CALL_LOG"

      Delete
  34. Hello
    I want only last call (Incoming,outgoing ,missed..etc) details ,help me ASAP

    ReplyDelete
  35. This comment has been removed by the author.

    ReplyDelete
  36. hello sir

    I used your code like this

    Cursor managedCursor = managedQuery( CallLog.Calls.CONTENT_URI,null, null,null, null);
    int number = managedCursor.getColumnIndex( CallLog.Calls.NUMBER );
    int type = managedCursor.getColumnIndex( CallLog.Calls.TYPE);
    int date = managedCursor.getColumnIndex( CallLog.Calls.DATE);
    int duration = managedCursor.getColumnIndex( CallLog.Calls.DURATION);

    but in case of missed call it give duration more then 0 in some devices only.

    Thanks

    ReplyDelete
  37. Thank you for the code.
    Can you please send a code to read call log after every call automatic an save automatic.
    Thank you in advance.

    ReplyDelete
  38. Actually sir i am reading whole call log and show like you are showing but the problem is that if call type is missed call in call log that time duration should be 0 but it give be more than 0 what should i do?

    ReplyDelete
  39. since managedquery is deprecated can you please provide the upated version of this example.?

    ReplyDelete
  40. How to get call log for particular sim in Dual Sim device?

    ReplyDelete
    Replies
    1. I think above code provide us call history from our phone, no matter from which SIM you get that. I am not sure how can you do this, please Google and let me know if you find anything.

      Thanks!

      Delete
    2. Hey manish how can we get the name of the user from which i have got the call

      Delete
  41. Replies
    1. I don't think so, because its get your phone call history and if there is no history how can you get the record from phone database.

      Delete
  42. could you please post android automatic call recorder project

    ReplyDelete
  43. How can i get the name i am getting everything but how can i get name

    ReplyDelete
  44. how get missedcall(or sms) per cantact ?

    ReplyDelete
    Replies
    1. You will get all data from URI and then use if condition before switch condition and if it match to a given number then only write the log.

      Delete
  45. i used this int owner = managedCursor.getColumnIndex(CallLog.Calls.PHONE_ACCOUNT_COMPONENT_NAME); for getting the phone account component name used to place the call.
    then, I add it in the string builder along with other fields.
    The app is crashing every time

    ReplyDelete
    Replies
    1. Same for PHONE_ACCOUNT_ID

      Delete
    2. what is the error? have you given permission into manifest?

      Delete
  46. Hello Manish

    I have implement this codes works fine but when i see my contact log from my phone it displays more than 100 contact log history and your code give me only 24 record history so how can i get all history completely

    ReplyDelete
    Replies
    1. Can't say anything without debug the app. But please check your 100 contacts have phone number. And scrollview is able to scroll till 100 contacts, may be it is scrollview issue.

      Do one thing put your record into Listview instead of StringBuilder and see if it work.

      Delete
  47. sir..what about this
    take a input from the user and save it and then
    use in any class in android

    ReplyDelete
  48. Replies
    1. Do something like this-

      String str_date="13-09-2011";
      DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
      Date date = (Date)formatter.parse(str_date);
      System.out.println("Today is " +date.getTime());

      Delete
  49. it is not working... It shows an error.Please help me!!!!!

    ReplyDelete
  50. Hi, thanks for your tutorial. In my application, I need to list call logs for a particular contact. I tried your method (compare phone number) but it is not very optimized and contact number and call log number are not always with same format. Any idea to do better ?

    ReplyDelete
    Replies
    1. I think you can use String compare like if number.contains(95999999) someting like that.

      Delete
  51. I Want to get Contact Name . from your code i can get only the contact number, not contact name .

    ReplyDelete
    Replies
    1. From call history you can't get the contact name. For this you can do one thing compare the number from contact database and return the name.

      Delete
  52. is it possible to get call cost

    ReplyDelete
    Replies
    1. Do you think logically it is possible? Well answer is no. Without help of service provider you can't get the call cost.

      Delete
    2. Thank you for your quick response.

      Delete
  53. Hello Manish
    I have a Android app project .
    Kindly contact me.

    ReplyDelete
  54. Hello Manish
    I have a Android app project .
    Kindly contact me.

    ReplyDelete
    Replies
    1. Drop me a test email at manishupacc@gmail.com with your contact number.

      Delete
  55. Hello Manish

    i can get total Datausage by TrafficStats class. but i don't know how to get 2G, 3G, 4G, Wifi data usage separately...

    ReplyDelete
  56. Hello Sir... Is it possible to fetch the contact name like we get in phone call log rather than using CACHED_NAME.

    ReplyDelete
  57. Hello Sir thank you for this code but plz could u help me ..I want to this code should retrieve the name of contact number as well how could i use a code to solve this problem thank you

    ReplyDelete
  58. hai manish
    i want only last week calls insted of total log how can i do it?

    ReplyDelete