Sunday, 22 December 2013

Incoming Call Broadcast Reciever


Learn Android Development


In previous I discussed about how to handle incoming call or how to listen for Incoming call using Activity, In this post I will discuss the same using Broadcast Receiver.

Broadcast Receiver is  better way than Activity to listen for Incoming Calls.

So declare the Permission and Receiver in Manifest

Permission Required:

 <uses-permission android:name="android.permission.READ_PHONE_STATE" />

Declare the receiver and register it to listen "android.intent.action.PHONE_STATE"  action

android.manifest 


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.incomingcallreciever"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />
    
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        
        
        <receiver android:name=".IncommingCallReceiver" android:enabled="true">
            <intent-filter>
                                     <action android:name="android.intent.action.PHONE_STATE" /> 
                </intent-filter>
           </receiver>

    </application>

</manifest>







Incoming Call Receiver




import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.widget.Toast;


 public class IncommingCallReceiver extends BroadcastReceiver
 {
    
      Context mContext;
      
      
      @Override
      public void onReceive(Context mContext, Intent intent)
      {
          try
          {
           
              String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);

           
            
              if(state.equals(TelephonyManager.EXTRA_STATE_RINGING))
              {
                   Toast.makeText(mContext, "Phone Is Ringing", Toast.LENGTH_LONG).show();
                   // Your Code
              }
              
              if(state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))
              {
                   Toast.makeText(mContext, "Call Recieved", Toast.LENGTH_LONG).show();
                       // Your Code
              }
              
              if (state.equals(TelephonyManager.EXTRA_STATE_IDLE))
              {
                
                  Toast.makeText(mContext, "Phone Is Idle", Toast.LENGTH_LONG).show();
                      // Your Code
                
              }
          }
          catch(Exception e)
          {
              //your custom message
          }
       
     }
      
}






      

No comments:

Post a Comment