有時需要在應用中根據系統電話的狀態進行應用相應的操作,公司有個有網絡電話的應用,使用網絡電話進行一個或多個號碼撥號的操作時,運營服務商網絡會回撥一個號碼過來來,接到回撥後,可以選擇接或者不接,另外如果調用了系統的掛斷後,應用也應該去網絡接口掛斷,如果調用系統的不接,那麼應用也應該是不會有撥出他人的電話的。不啰嗦了,直接上代碼
在後台的Activity有時無法調用,這個還有點問題,待解決
直接在Activity中的onCreate()調用
getCallPhoneListener();
private void getCallPhoneListener() {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(new PhoneListener(),
PhoneStateListener.LISTEN_CALL_STATE);
}
class PhoneListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:// 來電狀態
Log.i("lanjianlong","incomingNumber = "+incomingNumber);
Log.i("lanjianlong","incomingNumber.startsWith(\"950\") ="+incomingNumber.startsWith("950"));
if(null !=incomingNumber && incomingNumber.startsWith("950"))//這是來電的電話號碼,950開頭的
EightPartyApplication.isEightNum = true;
break;
case TelephonyManager.CALL_STATE_OFFHOOK:// 接聽狀態
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> runningTasks = manager.getRunningTasks(1);
RunningTaskInfo cinfo = runningTasks.get(0);
ComponentName component = cinfo.topActivity;
// className = com.android.phone.InCallScreen
// packageName = com.android.phone
View view = LayoutInflater.from(CallPhoneActivity.this).inflate(
R.layout.show_toast, null);
TextView showtv = (TextView) view.findViewById(R.id.showtv);
showtv.setTextSize(18.0f);
Toast toast = null;
toast = new Toast(CallPhoneActivity.this);
toast.setDuration(200);
toast.setView(view);
toast.show();
// Toast.makeText(AddNewActivity.this, "請按返回鍵回到通話界面看誰在線",
// Toast.LENGTH_LONG).show();
String packageName = component.getPackageName();
Log.e(TAG, "className = " + component.getClassName());
Log.e(TAG, "packageName = " + packageName);
return;
case TelephonyManager.CALL_STATE_IDLE:// 掛斷後回到空閒狀態
Log.e("lanjianlong", "這是系統的掛斷去調用應用的掛斷 , isComE = "+EightPartyApplication.isEightNum);
//要加一個標志,
if(null != incomingNumber && incomingNumber.startsWith("950") && EightPartyApplication.isEightNum){
Log.i("lanjianlong","掛斷");
closeMeeting();
EightPartyApplication.isEightNum = false;
}
break;
default:
break;
}
}
}