Android - 如何限制一段时间的通话?

时间:2014-10-04 03:49:12

标签: android broadcastreceiver phone-call telephony telephonymanager

我正在创建一个调用它的android应用程序。我只是想在一段时间后放弃或取消一个电话,就像我想打一个电话,它会在60秒后自动掉线。这在Android中是否可行?这是我的代码:

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // add PhoneStateListener
    PhoneCallListener phoneListener = new PhoneCallListener();
    TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
    telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);

    Intent callIntent = new Intent(Intent.ACTION_CALL);

    callIntent.setData(Uri.parse("tel:*03362111904"));

    startActivity(callIntent);
}

private class PhoneCallListener extends PhoneStateListener {

    private boolean isPhoneCalling = false;

    String LOG_TAG = "LOGGING 123";

    @Override
    public void onCallStateChanged(int state, String incomingNumber) {

        if (TelephonyManager.CALL_STATE_RINGING == state) {
            // phone ringing
            Log.i(LOG_TAG, "RINGING, number: " + incomingNumber);
        }

        if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
            // active
            Log.i(LOG_TAG, "OFFHOOK");

            isPhoneCalling = true;
        }

        if (TelephonyManager.CALL_STATE_IDLE == state) {
            // run when class initial and phone call ended, need detect flag
            // from CALL_STATE_OFFHOOK
            Log.i(LOG_TAG, "IDLE");

            if (isPhoneCalling) {

                Log.i(LOG_TAG, "restart app");

                // restart app
                Intent i = getBaseContext().getPackageManager()
                        .getLaunchIntentForPackage(
                                getBaseContext().getPackageName());
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);

                isPhoneCalling = false;
            }

        }
    }
}

}

1 个答案:

答案 0 :(得分:1)

已经提到在BroadcastReceiver中捕获拨出电话,如果您想在拨号前结束通话,这绝对是最好的方式。

到目前为止我遇到的唯一挂断方式是通过Java Reflection这样做。由于它不是公共API的一部分,因此您应该小心使用它,而不是依赖它。对Android内部组成的任何更改都将有效地破坏您的应用程序。

Prasanta Paul's blog demonstrates如何实现,我在下面进行了总结。

获取ITelephony对象:

TelephonyManager tm = (TelephonyManager) context
        .getSystemService(Context.TELEPHONY_SERVICE);
try {
    // Java reflection to gain access to TelephonyManager's
    // ITelephony getter
    Log.v(TAG, "Get getTeleService...");
    Class c = Class.forName(tm.getClass().getName());
    Method m = c.getDeclaredMethod("getITelephony");
    m.setAccessible(true);
    com.android.internal.telephony.ITelephony telephonyService =
            (ITelephony) m.invoke(tm);
} catch (Exception e) {
    e.printStackTrace();
    Log.e(TAG,
            "FATAL ERROR: could not connect to telephony subsystem");
    Log.e(TAG, "Exception object: " + e);
}

结束通话:

telephonyService.endCall();