2014-05-23 71 views
3

目前,當我運行我的應用程序時,如果手機響起,手機會獲取首選項,並且我的應用程序被終止。有沒有什麼辦法可以讓我的應用程序獲得一個首選項,即讓電話打到語音郵件或短時間將我的應用程序切換到背景,直到用戶接聽電話,並在完成後回到前臺。謝謝如何讓應用程序在後臺運行時在手機上響鈴android

+0

+1停止我的GPS過 – rpax

+0

名單phonestate在接收時,打電話給你上暫停活動()或做任何你需要 – Saqib

+1

saqib - 你能解釋一下這種方法 – Namit

回答

1

我認爲這是Android的默認功能,任何應用程序 如果傳入呼叫處於活動狀態將變爲非活動狀態。我們不能改變這一點。

當用戶在打電話,雖然,他們只需按home鍵和 開始另一個應用程序的主屏幕切換到另一個 的應用程序,或者通過雙按home鍵並切換到另包括你的應用程序。

+1

我的應用程序正在計算幾個數字。當您使應用程序處於非活動狀態時,所有會話特定變量都將重新初始化,因此數據會變得鬆散任何想法。 – Namit

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" /> 
+0

謝謝。我會試驗並讓你知道 – Namit

+0

你已經完成了你的實驗部分。 – Devraj

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 

}

相關問題