Monday 3 November 2014

Android Tutorial 47 : CALL States In Android

In this Post I will describe how to Handle incoming Calls on Android and Reacting to them i.e. receiving, rejecting etc.

We  can do this by Activity and by Broadcast Receiver, here we will do using Activity.

Permissions: 
As I mentioned in my earlier posts we require to declare permission in manifest file.
For listening and reacting to Incoming calls we need following permissions

android.permission.READ_PHONE_STATE   to listen to InComing Calls
"android.permission.MODIFY_PHONE_STATE"   to receive Incoming Calls 

You can learn more about permission  Here.

Add these permissions in your manifest file.
Your Manifest file should look like

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

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


 <application
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
        <activity
            android:name=".HomeActivity"
            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
>


Activity:

We need to use TelephonyManager class and  TELEPHONY_SERVICE.

The onCallStateChanged handler receives the phone number associated with incoming calls, and the
state parameter represents the current call state as one of the following three values:

➤ TelephonyManager.CALL_STATE_IDLE When the phone is neither ringing nor in a call

➤ TelephonyManager.CALL_STATE_RINGING When the phone is ringing

➤ TelephonyManager.CALL_STATE_OFFHOOK When the phone is currently in a call


How to Monitor Incoming Calls:


We need to have a listener to listen the InComing Calls

PhoneStateListener callStateListener = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber) {
// TODO React to incoming call.
}
};
telephonyManager.listen(callStateListener,
PhoneStateListener.LISTEN_CALL_STATE);


Code:


public class GetCallerInfoActivity extends Activity
{


  @Override
            public void onCreate(Bundle savedInstanceState)
            {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.main);
                   
                                       TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
                    PhoneStateListener callStateListener = new PhoneStateListener() {
                    public void onCallStateChanged(int state, String incomingNumber)
                    {
                            // TODO React to incoming call.
                            number=incomingNumber;
                            if(state==TelephonyManager.CALL_STATE_RINGING)
                            {
                                    Toast.makeText(getApplicationContext(),"Phone Is Riging", Toast.LENGTH_LONG).show();
                                   
                            }
                            if(state==TelephonyManager.CALL_STATE_OFFHOOK)
                            {
                                Toast.makeText(getApplicationContext(),"Phone is Currently in A call", Toast.LENGTH_LONG).show();
                            }
                           
                           
                            if(state==TelephonyManager.CALL_STATE_IDLE)
                            {
                                Toast.makeText(getApplicationContext(),"phone is neither ringing nor in a call", Toast.LENGTH_LONG).show();
                            }
                    }
                    };
                    telephonyManager.listen(callStateListener,PhoneStateListener.LISTEN_CALL_STATE);
                   
                   
                   
            }
                   
                   
            }



How To Launch the Dialer to Initiate Phone Calls:


Use an Intent action to start a dialer activity; you should specify the number to dial using the tel: schema as the data component of the Intent. 

Use the Intent.ACTION_DIAL Activity action to launch a dialer rather than dial the number immediately.
This action starts a dialer Activity, passing in the specified number but allowing the dialer application
to manage the call initialization (the default dialer asks the user to explicitly initiate the call). This
action doesn’t require any permissions and is the standard way applications should initiate calls.

Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:1234567"));
startActivity(intent); 

Android Tutorial 46 : DatePickerDialog in Android

We can use Time Picker  and Date Picker   widget to select a time and date , but TimePickerDialog and DatePickerDialog  is a better choice to do that.

In this post I will discuss how to use DatePickerDialog and TimePickerDialog to select Date and Time.



DatePickerDialog In Android
                       





Here I have described briefly, the Example with full source code is given below after this.
  
Declare following Variables in your Activity/Class

static final int DATE_DIALOG_ID = 0;
static final int TIME_DIALOG_ID=1;

// variables to save user selected date and time
public  int yearSelected,monthSelected,daySelected,hourSelected,minuteSelected;
  
// declare  the variables to show the date and time whenTime and Date Picker Dialog first appears
private int mYear, mMonth, mDay,mHour,mMinute; 

In the constructor you can initiallise the variable to current date and time.

                
                    final Calendar c = Calendar.getInstance();
                    mYear = c.get(Calendar.YEAR);
                    mMonth = c.get(Calendar.MONTH);
                    mDay = c.get(Calendar.DAY_OF_MONTH);
                    mHour = c.get(Calendar.HOUR_OF_DAY);
                    mMinute = c.get(Calendar.MINUTE);



//call the method when you need to show DatePickerDialog
 showDialog(DATE_DIALOG_ID);
//call the method when you need to show DatePickerDialog
  showDialog(TIME_DIALOG_ID);

// Register  DatePickerDialog listener
 private DatePickerDialog.OnDateSetListener mDateSetListener =
                        new DatePickerDialog.OnDateSetListener() {
                 // the callback received when the user "sets" the Date in the DatePickerDialog
                            public void onDateSet(DatePicker view, int yearSelected,
                                                  int monthOfYear, int dayOfMonth) {
                               year
Selected = yearSelected;
                               monthSelected = monthOfYear;
                               daySelected = dayOfMonth;
                              Toast.makeText(getApplicationContext(), "Date selected is:"+daySelected+"-"+monthSelected+"-"+yearSelected, Toast.LENGTH_LONG).show();
                                                         }
                        };


   // Register  TimePickerDialog listener                 
                        private TimePickerDialog.OnTimeSetListener mTimeSetListener =
                            new TimePickerDialog.OnTimeSetListener() {
             // the callback received when the user "sets" the TimePickerDialog in the dialog
                                public void onTimeSet(TimePicker view, int hourOfDay, int min) {

                                    hourSelected = hourOfDay;
                                    minuteSelected = min;
                                   Toast.makeText(getApplicationContext(), "Time selected is:"+hourSelected+"-"+minuteSelected, Toast.LENGTH_LONG).show();
                                                                  }
                            };


// Method automatically gets Called when you call showDialog()  method
                        @Override
                        protected Dialog onCreateDialog(int id) {
                            switch (id) {
                            case DATE_DIALOG_ID:
                                return new DatePickerDialog(this,
                                            mDateSetListener,
                                            mYear, mMonth, mDay);
                            case TIME_DIALOG_ID:
                                return new TimePickerDialog(this,
                                        mTimeSetListener, mHour, mMinute, false);
                            
                            }
                            return null;
                        }
                        

Date And Time Picker Dialog Example with Full Source Code

In the example   I have 2 buttons  
1: Select Date - to show DatePickerDialog 
2: Select Time - to show TimePickertDialog
When user selects a Date and Time in respective Dialogs we will set the selected date and time in Respective buttons. We will set selected date in Select Date Button and selected time in Select Time Button(See the last Snapshot)


main.xml



DatePickerDialog In Android



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


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:textSize="25dp"
        android:layout_gravity="center_horizontal"
        android:text="Date And Time Picker Example" />

    <Button
        android:id="@+id/buttonSelectDate"
        android:layout_marginTop="20dp"
        android:textSize="25dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Select Date" />

    <Button
        android:id="@+id/buttonSelectTime"
        android:layout_marginTop="20dp"
        android:textSize="25dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Select Time" />

</LinearLayout>




DateAndTimePickerActivity.java 

public class DateAndTimePickerActivity extends Activity
{

            Button btnSelectDate,btnSelectTime;
           
            static final int DATE_DIALOG_ID = 0;
            static final int TIME_DIALOG_ID=1;
           
          
      // variables to save user selected date and time
            public  int year,month,day,hour,minute;  

 // declare  the variables to Show/Set the date and time when Time and  Date Picker Dialog first appears
            private int mYear, mMonth, mDay,mHour,mMinute; 
            
            // constructor
            
            public DateAndTimePickerActivity()
            {
                        // Assign current Date and Time Values to Variables
                        final Calendar c = Calendar.getInstance();
                        mYear = c.get(Calendar.YEAR);
                        mMonth = c.get(Calendar.MONTH);
                        mDay = c.get(Calendar.DAY_OF_MONTH);
                        mHour = c.get(Calendar.HOUR_OF_DAY);
                        mMinute = c.get(Calendar.MINUTE);
            }
            
            @Override
            protected void onCreate(Bundle savedInstanceState) 
            {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.date_and_time_picker);
                        
                        // get the references of buttons
                        btnSelectDate=(Button)findViewById(R.id.buttonSelectDate);
                        btnSelectTime=(Button)findViewById(R.id.buttonSelectTime);
                        
                        // Set ClickListener on btnSelectDate 
                        btnSelectDate.setOnClickListener(new View.OnClickListener() {
                            
                            public void onClick(View v) {
                                // Show the DatePickerDialog
                                 showDialog(DATE_DIALOG_ID);
                            }
                        });
                        
                        // Set ClickListener on btnSelectTime
                        btnSelectTime.setOnClickListener(new View.OnClickListener() {
                            
                            public void onClick(View v) {
                                // Show the TimePickerDialog
                                 showDialog(TIME_DIALOG_ID);
                            }
                        });
                        
            }
            
            
            // Register  DatePickerDialog listener

             private DatePickerDialog.OnDateSetListener mDateSetListener =
                                    new DatePickerDialog.OnDateSetListener() {
                                // the callback received when the user "sets" the Date in the DatePickerDialog
                                        public void onDateSet(DatePicker view, int yearSelected,
                                                              int monthOfYear, int dayOfMonth) {
                                           year = yearSelected;
                                           month = monthOfYear;
                                           day = dayOfMonth;
                                           // Set the Selected Date in Select date Button
                                           btnSelectDate.setText("Date selected : "+day+"-"+month+"-"+year);
                                        }
                                    };

               // Register  TimePickerDialog listener                 
                                    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
                                        new TimePickerDialog.OnTimeSetListener() {
                                 // the callback received when the user "sets" the TimePickerDialog in the dialog
                                            public void onTimeSet(TimePicker view, int hourOfDay, int min) {
                                                hour = hourOfDay;
                                                minute = min;
                                                // Set the Selected Date in Select date Button
                                                btnSelectTime.setText("Time selected :"+hour+"-"+minute);
                                              }
                                        };


            // Method automatically gets Called when you call showDialog()  method
                                    @Override
                                    protected Dialog onCreateDialog(int id) {
                                        switch (id) {
                                        case DATE_DIALOG_ID:
                                 // create a new DatePickerDialog with values you want to show 
                                            return new DatePickerDialog(this,
                                                        mDateSetListener,
                                                        mYear, mMonth, mDay);
                                // create a new TimePickerDialog with values you want to show 
                                        case TIME_DIALOG_ID:
                                            return new TimePickerDialog(this,
                                                    mTimeSetListener, mHour, mMinute, false);
                                       
                                        }
                                        return null;
                                    }
                                    
}


TimePickerDialog In Android