2013-04-21 68 views
1

我正在使用PhoneStateListener來偵聽移動呼叫狀態的更改。我正在做的是在幾秒鐘後打一個電話,然後回到之前的活動。但是,每次我再次返回活動時,它都會再次運行CallThread,並陷入一次又一次呼叫之後發出呼叫的情況。 任何人都可以請幫忙嗎?謝謝!撥打電話後返回上一個活動

這是我在onCreate()方法中的活動。

Thread CallThread = new Thread(CallRunnable); 
    CallThread.start(); 

它會設置一個可運行的打電話。

Runnable CallRunable = new Runnable() { 

    @Override 
    public void run() { 
     try { 
      Thread.sleep(5 * 1000); //wait for 5 secs and then make phone call 
     } catch (InterruptedException e) { 
     } 

     makePhoneCall(phoneNO); 

    } 
}; 

在我PhoneStateListener,

public class MyPhoneStateListener extends PhoneStateListener { 

    private boolean isCalling = false; 

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

     switch (state) { 
     case TelephonyManager.CALL_STATE_OFFHOOK: 
      isCalling = true; 
      break; 
     case TelephonyManager.CALL_STATE_IDLE: 
      Log.i("Call", "IDLE"); 
      if (isCalling) { 

       Intent i = new Intent(getIntent()); 
       i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); 
       startActivity(i); 

       isCalling = false; 

      } 
      break; 
     default: 
      break; 
     } 
    } 
} 

回答

0
public class MyPhoneStateListener extends PhoneStateListener { 

private boolean isCalling = true; 
private int mCurrentState = TelephonyManager.CALL_STATE_IDLE; 

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

if (state != mCurrentState) {  
    switch (state) { 
     case TelephonyManager.CALL_STATE_OFFHOOK: 
      break; 
     case TelephonyManager.CALL_STATE_IDLE: 
      Log.i("Call", "IDLE"); 
      if (isCalling) { 

       Intent i = new Intent(getIntent()); 
       i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); 
       startActivity(i); 

       isCalling = false; 

      } 
      else { 
       isCalling = true; 
      } 
      break; 
     default: 
      break; 
     } 
    mCurrentState = state; 
    } 
} 

}

0

當然它會再次撥打電話,因爲每次你從電話呼叫空閒狀態回你,重新推出的活動,所以它觸發再次創建, 把額外的參數,所以你可以檢查它是否新創建或從電話回撥或保存到SharedPreference