如何在呼叫连接时启动计时器?

时间:2015-11-11 04:43:09

标签: java android call telephonymanager phone-state-listener

我需要在呼叫连接时启动计时器,但在我的情况下,它是在呼叫振铃时启动,我搜索了很多,但没有得到正确的解决方案。怀着希望,我正在重复这一点。至少我需要一个建议来实现这一目标。

我的代码:

public void onReceive(Context context, Intent intent) {

    String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);

    if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {    
        Log.d("Status", "Phone is Ringing");
    } else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {    
        Log.d("Status", "Phone is on call");
    } else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
        // Call Dropped or rejected   

        System.exit(0);
        Log.d("Status", "Phone is dropped");
    }    
}

1 个答案:

答案 0 :(得分:0)

你可以尝试一下。 在BroadCastReceiver中

static boolean flag = false;
static long start_time, end_time;

onReceive函数将是这样的,

public void onReceive(Context arg0, Intent intent) {
        String action = intent.getAction();
        if (action.equalsIgnoreCase("android.intent.action.PHONE_STATE")) {
            if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
            TelephonyManager.EXTRA_STATE_RINGING)) {
                start_time = System.currentTimeMillis();
            }
            if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
            TelephonyManager.EXTRA_STATE_IDLE)) {
                end_time = System.currentTimeMillis();
                //Total time talked =
                long total_time = end_time - start_time;
                //Store total_time somewhere or pass it to an Activity using intent
            }
        }

此外,您还需要在Manifest中为此授予权限。

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

在你的Manifest中注册接收器,如下所示:

 <receiver android:name=".CallDurationReceiver">
       <intent-filter>
           <action android:name="android.intent.action.PHONE_STATE" />
       </intent-filter>
    </receiver>