電話控制

1 篇文章 / 0 new
author
電話控制
使用 phone service 可由兩方式進行, 一是透過 Intent(控制性少), 另一則是取得系統serivce(操作能力多)
►Service
權限
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
Class c = Class.forName(telephony.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
telephonyService = (ITelephony) m.invoke(telephony); // ITelephony 公用介面需宣告在 aidl
telephonyService.call("電話號碼"); //直接撥出
telephonyService.dial("電話號碼"); //跳出撥號畫面等候
telephonyService.endCall(); //掛斷
ITelephony.aidl
package com.android.internal.telephony; //package 固定不可變更
interface ITelephony {   //通用介面宣告
    void call(String number);
    void dial(String number);
    boolean endCall();  
    void answerRingingCall();   
    void silenceRinger();
}
►Intent
權限
<uses-permission android:name="android.permission.CALL_PHONE" />
Intent intent = new Intent();  
intent.setAction(Intent.ACTION_CALL);  
intent.setData(Uri.parse("tel:電話號碼"));  
startActivity(intent);
►監聽狀態
權限
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
// 接收電話狀態
tm.listen(new PhoneStateListener() {
    private boolean callFlag = false;
    @Override
    public void onCallStateChanged(int state, String phoneNumber) {
        switch (state) {
            case TelephonyManager.CALL_STATE_RINGING:// 電話響...
            break;
            case TelephonyManager.CALL_STATE_OFFHOOK:// 通話中
                callFlag = true;
            break;
            case TelephonyManager.CALL_STATE_IDLE:// 電話掛斷
                if (callFlag == true) {//可藉此項自己的app回到最上層畫面
                    callFlag = false;
                    Intent it = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
                    it.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(it);
                }    
            break;
        }
    }
},PhoneStateListener.LISTEN_CALL_STATE);
Free Web Hosting