当手机在Android上响铃时如何让应用程序在后台运行

时间:2014-05-23 05:52:28

标签: android process background

目前,当我运行我的应用程序并且电话响铃时,手机会获得首选项并且我的应用程序被终止。是否有任何方式我的应用程序采取优先选择,即让电话打到语音邮件或短时间内将我的应用程序转移到后台,直到用户接听电话,并在完成后返回前台。感谢

3 个答案:

答案 0 :(得分:2)

你可以做一件事。您可以在来电期间暂停您的应用程序,之后,从同一个地方恢复应用程序。我知道这不是您问题的确切解决方案,但不知何故,它会减少您的工作量。希望这会有所帮助。

private class PhoneCallListener extends PhoneStateListener {

        private boolean isPhoneCalling = false;

        // needed for logging
        String TAG = "PhoneCallListener";

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

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

            if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
                // active
                Log.i(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(TAG, "IDLE");

                if (isPhoneCalling) {

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

                    // restart call application
                    Intent i = getBaseContext().getPackageManager()
                            .getLaunchIntentForPackage(
                                    getBaseContext().getPackageName());
                    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                            | Intent.FLAG_ACTIVITY_CLEAR_TOP
                            | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(i);

                    isPhoneCalling = false;
                }

            }


    }
    }

并将此权限添加到manifest.xml文件

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

答案 1 :(得分:1)

我认为这是任何应用程序的android的默认功能 如果来电处于活动状态,则不活动。我们无法改变这一点。

虽然用户正在打电话,但他们可以换到另一个 应用程序只需按下主页按钮并启动另一个应用程序 主屏幕,或者双击主页按钮并切换到另一个应用程序,包括你的应用程序。

答案 2 :(得分:1)

我遇到了类似的问题,通过重写onPause()和onResume()方法解决了这个问题,在onPause()中保存了所有必需的变量,并在onResume()中恢复它们。

@Override
protected void onResume(){
    super.onResume();
    load();
}

@Override
protected void onPause(){
    super.onPause();
    save();
}

private void save() {
    SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("DeviceName", deviceName);
    editor.putString("ConnectOption", connectOption.toString());
    editor.commit();
}

private void load() { 
    SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
    deviceName = sharedPreferences.getString("DeviceName","");
    String connectop = sharedPreferences.getString("ConnectOption","USB"); //You could provide a default value here

}

相关问题