In my application I need to make a call by an intent several times. This is the scenario. 1. User enters a phone number, delay time and number of attempts in the interface. 2. Once user press the dial button in my UI it will make a call and will hang up after the specified delay. 3. Once hung up, the app needs to make a call again until the entered number of attempts is satisfied.
I have used android ITelephony.aidl and java reflection to call hangup function. For one attempt I can successfully terminate the call. The problem occurs when I need to make several attempts. This is my code:
private void sendCommand(String number, int delay, int tries){
for(int i=0;i<tries;i++){
callPhone(number);
delayTimer(delay);
}
}
private void callPhone(String number){
String num = "0776355524";
Intent callIntent = new Intent(Intent.ACTION_CALL);
if(!(number.equalsIgnoreCase(""))){
num = number;
}
callIntent.setData(Uri.parse("tel:"+num));
startActivity(callIntent);
}
private void delayTimer(int delay){
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Do something after delay
if(isOffhook()){
cancelCall();
}
}
}, delay);
}
private boolean isOffhook(){
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try {
Log.v(TAG, "Get getTeleService...");
Class c = Class.forName(tm.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
telephonyService = (ITelephony) m.invoke(tm);
return telephonyService.isOffhook();
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "Error in accessing Telephony Manager: "+ e.toString());
telephonyService = null;
}
return false;
}
private void cancelCall(){
Log.d(TAG, "Ending call..."+ incomingNumber);
try {
if(telephonyService != null)
telephonyService.endCall();
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "Error in accessing Telephony Manager: "+ e.toString());
}
}
What am I doing wrong in my code. Thanks in advance, Hasala