2014-11-24 23 views
8

我想知道:如何做一個Android的「OS」檢測來電

  1. Android操作系統如何檢測來電(號碼),並顯示聯繫人姓名和爲我們提供了一個選項來參加電話。
  2. 當點擊「END CALL BUTTON」時,操作系統內部會發生什麼。

當我搜索有關這個我只得到類和方法來創建我自己的應用程序。請求解釋。

回答

16

在Android中,可以使用內置的TelephonyManager API檢測呼叫事件。 TelephonyManager類可以訪問有關設備上的電話服務的信息。

實施例:

創建名爲MyCallReceiver

新類
package com.example; 

import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.telephony.TelephonyManager; 
import android.widget.Toast; 

public class MyCallReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 

     if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)) { 
      // This code will execute when the phone has an incoming call 

      // get the phone number 
      String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER); 
      Toast.makeText(context, "Call from:" +incomingNumber, Toast.LENGTH_LONG).show(); 

     } else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
       TelephonyManager.EXTRA_STATE_IDLE) 
       || intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
         TelephonyManager.EXTRA_STATE_OFFHOOK)) { 
      // This code will execute when the call is disconnected 
      Toast.makeText(context, "Detected call hangup event", Toast.LENGTH_LONG).show(); 

     } 
    } 
} 

廣播接收器類,將監視手機狀態和每當在電話狀態的變化,所述的onReceive()的方法BroadcastReceiver將被調用。

添加READ_PHONE_STATE許可,您的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-sdk 
     android:minSdkVersion="8" 
     android:targetSdkVersion="18" /> 

    <uses-permission android:name="android.permission.READ_PHONE_STATE" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name="com.example.MainActivity" 
      android:label="@string/app_name" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 
       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 

     <receiver android:name="com.example.MyCallReceiver" > 
      <intent-filter> 
       <action android:name="android.intent.action.PHONE_STATE" /> 
      </intent-filter> 
     </receiver> 
    </application> 

</manifest> 

檢查此爲參考:BroadcastReceiver

+0

感謝這個代碼。使用BroadCast和PhoneStateListener [onCallStateChanged()]之間有什麼區別。期待您的指導 – Pravin 2014-11-25 06:44:56

+0

只需簡單地說,廣播就可以在所有情況下都能正常工作。電話狀態將只與電話相關的事情一起工作。 ;-) – 2014-11-26 13:29:25

+0

是否會調用onPause? – 2015-12-14 04:01:18