Android Studio Get Call State 2
Syntax
The TelephonyManager
class in Android provides a method getCallState()
to get the call state of the device. The syntax for using this method is as follows:
int callState = telephonyManager.getCallState();
Example
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
int callState = telephonyManager.getCallState();
String state = "";
switch (callState) {
case TelephonyManager.CALL_STATE_IDLE:
state = "Idle";
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
state = "Off Hook";
break;
case TelephonyManager.CALL_STATE_RINGING:
state = "Ringing";
break;
}
Log.i(TAG, "Call state: " + state);
Output
The output of the above example depends on the call state of the device. If the call state is idle, the output will be:
Call state: Idle
Explanation
In the example above, we first obtain an instance of the TelephonyManager
class using the getSystemService()
method. We then use the getCallState()
method to get the call state of the device. The getCallState()
method returns an integer that corresponds to the call state (0 for idle, 1 for off hook, 2 for ringing).
We then use a switch
statement to determine the call state based on the value returned by getCallState()
. Finally, we log the call state using Log.i()
.
Use
The call state can provide useful information to an Android application. For example, an app could use it to determine when to display an incoming call screen or to pause music playback during a call.
Important Points
- The
getCallState()
method requires theREAD_PHONE_STATE
permission to be granted in the manifest. - The call state returned by the
getCallState()
method is only valid when the device is in a voice call. - The
TelephonyManager.CALL_STATE_IDLE
constant corresponds to the device being in an idle state (i.e., not in a call).
Summary
In this lesson, we learned how to use the getCallState()
method of the TelephonyManager
class in Android to get the call state of the device. We also covered some important points to keep in mind when working with this method.