我正在使用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 :(得分: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;
}
}
}
答案 1 :(得分:0)
当然它会再次拨打电话,因为每次你从电话呼叫IDLE状态回复你,重新启动活动,所以它再次触发onCreate, 在那里添加一个额外的参数,以便您可以检查它是新创建还是从电话回来或保存到SharedPreference