I am trying to get the server time from pubnub with the time method
mPubnub.time(callback);
I suppose it is an asynchronous call then I have a waiting loop just after so I can wait for the result
time = -1;
mPubnub.time(callback);
while(time == -1);
In the call back I have
Callback callback = new Callback() {
public void successCallback(String channel, Object response) {
try {
JSONArray jsonArray = new JSONArray(response.toString());
time = jsonArray.getLong(0) / 10000;
return;
} catch (JSONException e) {
e.printStackTrace();
}
time = 0;
}
public void errorCallback(String channel, PubnubError error) {
Log.wtf("error/" + channel, error.toString());
time = 0;
}
};
All these calls are from doInBackground
of an AsyncTask
. Why is it blocking my ui thread. Also calls to publish are also blocking my UI thread and I only call them from an AsyncTask
Many people say the while loop blocks the UI thread but I don't understand why that loop in an AsyncTask would block the UI thread. It wasn't in the onPostExecute
or onProgressExecute
. It was in doInBackground
and it shouldn't block the UI.
On the other hand removing the loop still blocks the UI thread
mPubnub.time(callback);
mPubnub.publish(channel, message, true, callback);
these simple calls block the UI thread and the application stops responding.
This is blocking your UI thread:
while(time == -1);
Instead of doing that, you should handle the success/failure via the callback. If the pubnub API takes a callback like this, it would appear as though it is already handling doing it on a background thread. Just take the appropriate action inside the callback handlers.
while(time == -1);
This line blocks your UI Thread, because of this pointer will never updated by other thread, it's not a volatile variable. You can use Debug Bottle to detect UI Block codes in your project.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.