/**
* intervals of loop
*/
private final long HEART_BEAT_DELAY = 1000L;
private long lastTime = 0;
/**
* whether user is chatting with other(true:isChatting; false: not chatting)
*/
private boolean mIsChatting = false;
/**
* mainThread
*/
private Thread mThread = new Thread() {
@Override
public void run() {
mThread.setPriority(Thread.MAX_PRIORITY);
Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO);
//if user is chatting and activity is not finishing, keep cycling
while (mIsChatting && !VideoChatViewActivity.this.isFinishing()) {
try {
sleep(HEART_BEAT_DELAY);
//get current time
long thisTime = System.currentTimeMillis();
//get interval between current time and last request time
long duration = thisTime - lastTime;
//every 60 seconds do network request
if (mIsChatting && duration >= 60 * 1000) {
//set last heartbeat time to current time
lastTime = thisTime;
//network request
mModel.sendHeartBeat(mUserId, mCallId);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
/**
* start heartbeat thread
*/
public void startHearBeat() {
if (!mIsChatting) {
mIsChatting = true;
lastTime = System.currentTimeMillis();
mThread.start();
} else {
LogUtil.e("ralph", "start second time, ignore it");
}
}
/**
* stop heartbeat thread
*/
public void endHeartBeat() {
mIsChatting = false;
}
我已经有了这段代码,心跳应该每60秒钟请求一次网络连接,但有时它将等待90秒钟才能进行下一次重复。 为了解决这个问题,我设置了processPriority和threadPriority,但是它们仍然无法正常工作。 如何按时解决该发出的请求?
答案 0 :(得分:-1)
如果将threadPriority设置为最高,则意味着您希望此线程先运行。
尝试在startHearBeat()方法中使用mThread.join()
。