Posted By Our Mentors
Amreen Khan
Android Developer
animesh bansal
iphone App Developer
Devendra chouksey
Android Developer
Dilip Saket
IOS apps developer
Hemraj Jhariya
iOS Developer
Jaihind singh Rajput
Smart Phone App Dev
Mujahid khan
Android developer
Narendra Yadav
android developer
Narinder Gupta
Mobile App Architect
Pradeep singh Thakur
Mobile App Architect
Sanjay Sharma
Andriod Developer
Shakti Rajpal
IT Architect
Soniya Vishwakarma
iPhone App Developer
Sunil Raghuwanshi
iPhone App Developer
Supriya Kapse
Senior developer
View current Topics
How to use Broadcast receiver for incoming and outgoing call and show in listview using database? Android
This tutorial describes how to create and consume Android services and show incoming and outgoing call in listview using database. A broadcast receiver is a class which extends BroadcastReceiver and which is registered as a receiver in an Android Application via the AndroidManifest.xml file(or via code).
Posted By: Narendra Yadav Date: 09 Jul 2012 View: 2915
      Rate This !!


How to use Broadcast receiver for incoming and outgoing call and show in listview using database?

This tutorial describes how to create and consume Android services. A broadcast receiver is a class which extends BroadcastReceiver and which is registered as a receiver in an Android Application via the AndroidManifest.xml file(or via code).

In the manifest file of you receicving activity, you have to declare which is your broadcast receiver class, for example:

<receiver android:name="MyPhoneReceiver" >

            <intent-filter>

                <action android:name="android.intent.action.PHONE_STATE" ></action>

                 <action android:name="android.provider.Telephony.SMS_RECEIVED" />

            </intent-filter>

 </receiver>

 

As you can see, you also define the intent filter here, that is, which intents should be received by the broadcas receiver.

Then you have to define a class which extends BroadcastReceiver. This is the class you defined in the manifest file:

public class MyPhoneReceiver extends BroadcastReceiver {

 

     @Override

     public void onReceive(Context context, Intent intent) {

          Bundle extras = intent.getExtras();

           if (extras != null) {

                String state = extras.getString(TelephonyManager.EXTRA_STATE);

                Log.w("DEBUG", "aa"+state);

                if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {

                     String phoneNumber = extras

                                .getString(TelephonyManager.EXTRA_INCOMING_NUMBER);

                     Log.w("DEBUG", "aa"+phoneNumber);

                }

           }        

          

}

Here, all intents which are passed through the filter are received and you can access them using the parameter passed in the method call.

       

          The class BroadcastReceiver defines the onReceive() method. Only during this method yourBroadcastReceiver object will be valid, afterwards the Android system can recycle theBroadcastReceiver. Therefore you cannot perform any asynchronous operation in the onReceive()method.

          We will define a broadcast receiver which listens to telephone state changes. If the phone receives or dials a phone call then our receivers will be notified and log a message.

Receiver Lifecycle:

There is only one lifecycle method for the intent receiver as onReceive(). The method gets called when intent is broadcasted. The receiver object is only valid for the duration of the onReceive() method, after the method ends the object is considered to be non-active and can be garbage collected. Because of this the intent receiver onReceive() method should not handle any asynchronous operation.

To receiver an intent by the intent receiver the application does not need to be running. When the intent is broadcasted the system will start the application to call the intent receiver.

Example: In this example we use database, I hope you have some knowledge about database.

//This is PhoneReceiver.java file for receiving all incoming calls using broadcast receiver.

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.os.Bundle;

import android.telephony.SmsMessage;

import android.telephony.TelephonyManager;

import android.text.format.Time;

import android.util.Log;

 

public class MyPhoneReceiver extends BroadcastReceiver {

 

            @Override

            public void onReceive(Context context, Intent intent) {

 

                        PhoneRecieverBroadcastActivity.db.open();

                        Bundle extras = intent.getExtras();

                        if (extras != null) {

                                    String state = extras.getString(TelephonyManager.EXTRA_STATE);

                                    Log.w("DEBUG", "aa" + state);

                                    if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {

                                                String phoneNumber = extras

                                                                        .getString(TelephonyManager.EXTRA_INCOMING_NUMBER);

                                                Log.w("DEBUG", "aa" + phoneNumber);

                                                doSomething(phoneNumber);

                                    }

                        }

                        PhoneRecieverBroadcastActivity.db.close();

            }

 

            private void doSomething(String number) {

                        Log.d("<<<>>>", number);

 

                        Time today = new Time(Time.getCurrentTimezone());

                        today.setToNow();

 

                        PhoneRecieverBroadcastActivity.db.insertUserProfile(number, "",

                                                today.monthDay + "-" + (today.month + 1) + "-" + today.year,

                                                today.format("%k:%M:%S"));

 

            }

}

 

//This is OutgoingCallInterceptor.java file for receiving all outgoing calls using broadcast receiver.

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.text.format.Time;

import android.util.Log;

 

 

public class OutgoingCallInterceptor extends BroadcastReceiver {

            @Override

            public void onReceive(Context context, Intent intent) {

                        final String oldNumber = intent

                                                .getStringExtra(Intent.EXTRA_PHONE_NUMBER);

                        PhoneRecieverBroadcastActivity.db.open();

 

                        this.setResultData(oldNumber);

                        final String newNumber = this.getResultData();

                        String msg = "Intercepted outgoing call. Old number " + oldNumber

                                                + ", new number " + newNumber;

 

                        Time today = new Time(Time.getCurrentTimezone());

                        today.setToNow();

 

                        Log.v("Current date and time ",

                                                "d/t" + today.monthDay + "-" + (today.month + 1) + "-"

                                                                        + today.year + " " + today.format("%k:%M:%S"));

 

                        PhoneRecieverBroadcastActivity.db.insertUserProfile("", oldNumber,

                                                today.monthDay + "-" + (today.month + 1) + "-" + today.year,

                                                today.format("%k:%M:%S"));

 

                        PhoneRecieverBroadcastActivity.db.close();

            }

}

// This is PhoneRecieverBroadcastActivity.java for showing all phone call details onclick button // in listview.

import java.util.ArrayList

 

import com.vit.adapters.PhoneListItem;

import com.vit.collection.PhoneNumberDetails;

import com.vit.db.DataHelper;

 

import android.app.Activity;

import android.content.Context;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.LinearLayout;

import android.widget.ListView;

 

public class PhoneRecieverBroadcastActivity extends Activity {

            ListView lv;

            Context context;

            Button btn;

   public static DataHelper db;

   private LinearLayout ll;

  

   @Override

  

   protected void onCreate(Bundle savedInstanceState) {

            // TODO Auto-generated method stub

            super.onCreate(savedInstanceState);

            setContentView(R.layout.main);

            context=this;

            db=new DataHelper(context);

           

            lv=(ListView) findViewById(R.id.list);

            btn=(Button)findViewById(R.id.btn);

            ll=(LinearLayout)findViewById(R.id.ll);

            btn.setOnClickListener(new OnClickListener() {

                       

                        @Override

                        public void onClick(View v) {

                                    // TODO Auto-generated method stub

                                    db.open();

                                    ll.setVisibility(0);

                                    ArrayList<PhoneNumberDetails> phone_arrylist=db.getPhoneRecord();

                                    lv.setAdapter(new PhoneListItem(context, phone_arrylist));

                                    db.close();

                        }

            });

           

           

}         

           

}

 

// This is PhoneListItem.java file for making custom adapter for listview

import java.util.ArrayList;

import android.content.Context;

import android.util.Log;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.BaseAdapter;

import android.widget.TextView;

import com.phonereceiverbroadcast.R;

import com.vit.collection.PhoneNumberDetails;

public class PhoneListItem extends BaseAdapter{

            private Context ctx;

            private LayoutInflater inflater;

            private ArrayList<PhoneNumberDetails> phoneinfo;

            public PhoneListItem(Context ctx,ArrayList<PhoneNumberDetails> doctorinfo) {

                        // TODO Auto-generated constructor stub

                        this.ctx=ctx;

                        this.phoneinfo=doctorinfo;

                        inflater=(LayoutInflater)this.ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            }         

            public int getCount() {

                        // TODO Auto-generated method stub

                        if(this.phoneinfo==null)

                                    return 0;

                        else

                                    return this.phoneinfo.size();

            }         

            public Object getItem(int position) {

                        // TODO Auto-generated method stub

                        return null;

            }         

            public long getItemId(int position) {

                        // TODO Auto-generated method stub

                        return 0;

            }         

            public View getView(int position, View convertView, ViewGroup parent) {

                        // TODO Auto-generated method stub

                        View view=convertView;

                        ViewHolder holder;

                        if(view==null){

                                    view=inflater.inflate(R.layout.phonelistrow, null);

                                    holder=new ViewHolder();

                                    holder.in_no=(TextView) view.findViewById(R.id.in_no);

                                    holder.out_no=(TextView) view.findViewById(R.id.out_no);

                                    holder.date=(TextView) view.findViewById(R.id.date);

                                    holder.time=(TextView) view.findViewById(R.id.time);

                                    view.setTag(holder);

                        }

                        else{

                                    holder=(ViewHolder) view.getTag();

                        }

                        try{

                                                holder.in_no.setText(phoneinfo.get(position).getIncoming_no());

                                                holder.out_no.setText(phoneinfo.get(position).getOutgoing_no());

                                                holder.date.setText(phoneinfo.get(position).getDate());

                                                holder.time.setText(phoneinfo.get(position).getTime());

                        }catch(Exception e){

                                    Log.e("Error is ", e.toString());

                        }

                        return view;

            }         

            public class ViewHolder

              {       

            public TextView in_no,out_no,date,time;     

    }

}

//This is PhoneNumberDetails.java file for getter and setter.

 

/**

 * @author Narendra yadav

 *

 */

public class PhoneNumberDetails {

      

       private String incoming_no;

       private String outgoing_no;

       private String date;

       private String time;

      

       public String getIncoming_no() {

              return incoming_no;

       }

       public void setIncoming_no(String incoming_no) {

              this.incoming_no = incoming_no;

       }

       public String getOutgoing_no() {

              return outgoing_no;

       }

       public void setOutgoing_no(String outgoing_no) {

              this.outgoing_no = outgoing_no;

       }

       public String getDate() {

              return date;

       }

       public void setDate(String date) {

              this.date = date;

       }

       public String getTime() {

              return time;

       }

       public void setTime(String time) {

              this.time = time;

       }

      

}

 

//This is DataHelper.java file for use database.

import java.util.ArrayList;

import com.vit.collection.PhoneNumberDetails;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

import android.database.sqlite.SQLiteStatement;

import android.util.Log;

 

public class DataHelper {

 

       private static final String TAG = "DataHelper";

       private static final String DATABASE_NAME = "database.phone";

       private static final int DATABASE_VERSION = 1;

       private static final String TBL_PHONE = "PhoneDetails";

 

       private static final String phoneTbl = "CREATE TABLE " + TBL_PHONE

                     + "(Incoming_no TEXT , " + " Outgoing_no TEXT," + " Dtae TEXT,"

                     + " Time TEXT" + ")";

 

       private Context context;

       private SQLiteDatabase db;

       OpenHelper openHelper;

 

       private SQLiteStatement stmtInsertPhone;;

 

       private static final String INSERT_USER = "insert into " + TBL_PHONE

                     + "(Incoming_no, Outgoing_no, Dtae, Time) values (?,?,?,?)";

 

       public DataHelper(Context context) {

 

              try {

 

                     this.context = context;

                     openHelper = new OpenHelper(this.context);

                     Log.i("Hospital DB created succesfully",

                                  "=============================");

 

              } catch (Exception e) {

 

                     Log.e(TAG, "================================" + e);

 

              }

       }

 

       public void open() {

              this.db = openHelper.getWritableDatabase();

       }

 

       public void close() {

              this.db.close();

       }

 

       public long insertUserProfile(String in_call, String out_call, String date,

                     String time) {

 

              this.stmtInsertPhone = this.db.compileStatement(INSERT_USER);

 

              try {

 

                     this.stmtInsertPhone.bindString(1, in_call);

                     Log.i("incoing call", "" + in_call);

                     this.stmtInsertPhone.bindString(2, out_call);

                     Log.i("outcall call", "" + out_call);

                     this.stmtInsertPhone.bindString(3, date);

                     Log.i("date", "" + date);

                     this.stmtInsertPhone.bindString(4, time);

                     Log.i("time", "" + time);

 

                     stmtInsertPhone.executeInsert();

                     Log.i(TAG, "Profile inserted==========================");

                     return 1;

 

              } catch (Exception e) {

                     Log.i(TAG, "EXCEPTION ON insertUserProfile....." + e);

                     return -1;

              }

       }

 

       public ArrayList<PhoneNumberDetails> getPhoneRecord() {

              Cursor cursor = db.query(TBL_PHONE, null, null, null, null, null, null);

              Log.v("phone record length :", " " + cursor.getCount());

              ArrayList<PhoneNumberDetails> phonedetails = new ArrayList<PhoneNumberDetails>();

              if (cursor.getCount() > 0) {

                     if (cursor.moveToNext()) {

                           do {

                                  PhoneNumberDetails ph = new PhoneNumberDetails();

                                  ph.setDate(cursor.getString(cursor.getColumnIndex("Dtae")));

                                  ph.setIncoming_no(cursor.getString(cursor

                                                .getColumnIndex("Incoming_no")));

                                  ph.setOutgoing_no(cursor.getString(cursor

                                                .getColumnIndex("Outgoing_no")));

                                  ph.setTime(cursor.getString(cursor.getColumnIndex("Time")));

                                  phonedetails.add(ph);

                                  ph = null;

                           } while (cursor.moveToNext());

                     }

              }

              return phonedetails;

       }

 

       public void deleteAll() {

              this.db.delete(TBL_PHONE, null, null);

       }

 

       private static class OpenHelper extends SQLiteOpenHelper {

 

              OpenHelper(Context context) {

                     super(context, DATABASE_NAME, null, DATABASE_VERSION);

              }

 

              @Override

              public void onCreate(SQLiteDatabase db) {

 

                     db.execSQL(phoneTbl);

              }

 

              @Override

              public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

                     Log.w("Example",

                                  "Upgrading database, this will drop tables and recreate.");

 

                     // Enable foreign key constraints

                     db.execSQL("PRAGMA foreign_keys=ON;");

 

                     db.execSQL("DROP TABLE IF EXISTS " + TBL_PHONE);

                     onCreate(db);

              }

 

       }

 

}

// This is main.xml for Activity

 

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical" >

 

    <Button

        android:id="@+id/btn"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="Get Phone call detail" />

 

    <LinearLayout

        android:id="@+id/ll"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:background="@drawable/addressselector"

        android:visibility="gone" >

 

        <TextView

            android:id="@+id/in_no"

            android:layout_width="90dp"

            android:layout_height="wrap_content"

            android:text="Incoming No." />

 

        <TextView

            android:id="@+id/out_no"

            android:layout_width="90dp"

            android:layout_height="wrap_content"

            android:layout_marginLeft="5dp"

            android:text="Outgoing No." />

 

        <TextView

            android:id="@+id/date"

            android:layout_width="65dp"

            android:layout_height="wrap_content"

            android:layout_marginLeft="5dp"

            android:text="Date" />

 

        <TextView

            android:id="@+id/time"

            android:layout_width="65dp"

            android:layout_height="wrap_content"

            android:layout_marginLeft="5dp"

            android:text="Time" />

    </LinearLayout>

 

    <ListView

        android:id="@+id/list"

        android:layout_width="match_parent"

        android:layout_height="wrap_content" >

    </ListView>

 

</LinearLayout>

 

//This is phonelistrow.xml for custom adapter

 <?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:background="@drawable/emailselector"

    android:orientation="horizontal" >

 

    <TextView

        android:id="@+id/in_no"

        android:layout_width="90dp"

        android:layout_height="wrap_content" />

 

    <TextView

        android:id="@+id/out_no"

        android:layout_width="90dp"

        android:layout_height="wrap_content"

        android:layout_marginLeft="5dp" />

 

    <TextView

        android:id="@+id/date"

        android:layout_width="65dp"

        android:layout_height="wrap_content"

        android:layout_marginLeft="5dp" />

 

    <TextView

        android:id="@+id/time"

        android:layout_width="65dp"

        android:layout_height="wrap_content"

        android:layout_marginLeft="5dp" />

 

</LinearLayout>

 

Output is:broadcatexample.png

I cheated on my boyfriend men and women open

Posted Queries