Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a Phone instance in android?

I have to use android ITelephony the internal classes on android telephony. I am using ITelephony to make calls by getting its instance as

ITelephony phone = ITelephony.Stub.asInterface(
    ServiceManager.getService(Context.TELEPHONY_SERVICE)
);

and then calling with

phone.call(destNum);

Now I need to perform other actions like holding a call. ITelephony does not provide an API for this, but I found a Phone class that has switchHoldingAndActive(), but to call this I need a Phone instance to the currently running active call. I tried

Phone PhoneActive = PhoneFactory.getDefaultPhone();

but its giving me an exception saying

Caused by: java.lang.RuntimeException: 
  Can't create handler inside thread that has not called Looper.prepare()

What is the correct way to get a Phone Instance?

like image 935
user954299 Avatar asked Aug 16 '26 03:08

user954299


1 Answers

There is no correct way to get Phone instance. AFAIK, getDefaultPhone() returns the instance of the current active Phone sub-class (GSM/CDMA) only if it is created by your thread (via PhoneFactory.makeDefaultPhone()). However, I believe that the instance is created by pre-installed Call application, so if you try it won't work. Long time ago I tried to use reflection to sign up for precise call state updates and stuck because of security exception. My application had to be running in system process... My code was like this:

mPhoneFactory = Class.forName("com.android.internal.telephony.PhoneFactory");
Method mMakeDefaultPhone = mPhoneFactory.getMethod("makeDefaultPhone", new Class[] {Context.class});
mMakeDefaultPhone.invoke(null, getContext());

Method mGetDefaultPhone = mPhoneFactory.getMethod("getDefaultPhone", null);
mPhone = mGetDefaultPhone.invoke(null);

Method mRegisterForStateChange = mPhone.getClass().getMethod("registerForPreciseCallStateChanged",
new Class[]{Handler.class, Integer.TYPE, Object.class});            

mRegisterForStateChange.invoke(mPhone, mHandler, CALL_STATE_CHANGED, null);
like image 78
avepr Avatar answered Aug 18 '26 17:08

avepr