onIncomingCall()
是来自第三方库pjsip
中的类的重写方法。使用SIP进行来电时会调用此方法。不知何故,只有当呼叫应答代码在同一方法内或在同一方法中调用时,此方法才能使应答呼叫成为可能。但我希望在用户按下按钮时接听电话。我已经创建了一个回叫并让用户在呼叫到来时按下按钮,但如果呼叫应答代码在onIncomingCall()
方法之外调用,则该呼叫应答代码不起作用。所以我决定将Thread.sleep(10000)
放在onIncomingCall()
中,当用户按下按钮时,我想取消该线程,以便可以执行呼叫应答代码。
我使用Thread.currentThread().interrupt()
,但Thread.sleep
根本没有取消。我写了一个单独的活动来测试这个功能,但它失败了,这意味着Thread.currentThread.interrupt
根本不适合我。实现这一目标的最佳选择是什么?请更新我......我真的很挣扎。
@Override
public void onIncomingCall(OnIncomingCallParam prm) {
onIncomingCallParam = prm;
try {
Thread.sleep(10000);
} catch(InterruptedException ie) {
ie.printStackTrace();
}
answerCall();
}
更新:
我用以下方法解决了这个问题
resetThread();
while (testThread) {
try {
Log.d(TAG,"testThread true");
Thread.sleep(1000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
Log.d(TAG,"Call Answering code");
private void resetThread() {
Thread newThread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10000);
testThread = false;
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
});
try {
newThread.start();
} catch (Exception ie) {
ie.printStackTrace();
}
}
答案 0 :(得分:2)
这里的问题与你不会中断右Thread
的事实有关,如果你打电话给Thread.currentThread().interrupt()
,你会打断当前的线程而不是它正在睡觉的那个。
这是一个显示主要想法的明显例子:
// Here is the thread that will only sleep until it will be interrupted
Thread t1 = new Thread(
() -> {
try {
Thread.sleep(10_000L);
System.err.println("The Thread has not been interrupted");
} catch (InterruptedException e) {
System.out.println("The Thread has been interrupted");
}
}
);
// Start the thread
t1.start();
// Make the current thread sleep for 1 sec
Thread.sleep(1_000L);
// Try to interrupt the sleeping thread with Thread.currentThread().interrupt()
System.out.println("Trying to call Thread.currentThread().interrupt()");
Thread.currentThread().interrupt();
// Reset the flag to be able to make the current thread sleep again
Thread.interrupted();
// Make the current thread sleep for 1 sec
Thread.sleep(1_000L);
// Try to interrupt the sleeping thread with t1.interrupt()
System.out.println("Trying to call t1.interrupt()");
t1.interrupt();
<强>输出:强>
Trying to call Thread.currentThread().interrupt()
Trying to call t1.interrupt()
The Thread has been interrupted
正如您在输出中看到的那样,只有当我们调用t1.interrupt()
时,线程才会被中断,换言之,只有在我们中断右Thread
时才会中断。
答案 1 :(得分:0)
也许所有调用都必须在创建库实例的同一个线程上完成。尝试使用HandlerThread发布消息并在自定义处理程序中处理这些消息,而不是挂起线程。