2013-04-21 97 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