package com.postpc.easyrider.Notification;
import java.lang.reflect.Method;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.android.internal.telephony.ITelephony;
import com.postpc.easyrider.settings.Settings;
public class QuickCallNotifier implements RiderNotifier {
private Context _context;
private final static int RETURN_TO_IDLE_POLL_INTERVAL_MILLIS = 100;
public QuickCallNotifier(Context context) {
_context = context;
}
public boolean notifyContact(String contactNumber) throws NotificationException {
// get the TM
TelephonyManager telephonyManager = (TelephonyManager)_context.getSystemService(Context.TELEPHONY_SERVICE);
AudioManager audioManager = (AudioManager)_context.getSystemService(Context.AUDIO_SERVICE);
ITelephony telephonyService = null;
// use reflection to get ITelephony interface
try {
Class<?> tmClass = Class.forName(telephonyManager.getClass().getName());
Method getITelephonyMethod = tmClass.getDeclaredMethod("getITelephony");
getITelephonyMethod.setAccessible(true);
telephonyService = (ITelephony)getITelephonyMethod.invoke(telephonyManager);
} catch (Exception e) {
throw new NotificationException("Cannot access ITelephony interface", e);
}
// call only if we're idle
if (telephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
return false;
}
// construct phone number and call intent
Uri phoneNumberURI = Uri.fromParts("tel", contactNumber, null);
Intent callIntent = new Intent(Intent.ACTION_CALL, phoneNumberURI);
// we start the intent from a service
callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// set speakers to on
audioManager.setSpeakerphoneOn(true);
// do the call
Log.i(getClass().getSimpleName(), "Starting QuickCall...");
_context.startActivity(callIntent);
try {
// wait a bit
Thread.sleep(new Settings(_context).getQuickCallLength() * 1000);
} catch (InterruptedException e) {}
try {
// then hang up
telephonyService.endCall();
} catch (RemoteException e) {
throw new NotificationException("Cannot hang-up call.", e);
}
// turn off speakers
audioManager.setSpeakerphoneOn(false);
// wait until state is changed to idle
while (telephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
try {
Thread.sleep(RETURN_TO_IDLE_POLL_INTERVAL_MILLIS);
} catch (InterruptedException e) {
}
}
Log.i(getClass().getSimpleName(), "QuickCall ended.");
return true;
}
}
|