How To Make Android Wait?
Solution 1:
you can achieve that by using handler
int time=3000// in milliseconds
Handler h=new Handler();
h.postDelayed(new Runnable() {
@Override
publicvoidrun() {
//here you can do the job
}
},time);
if you want to update the UI from the handler you will end up with an error but you can userunOnUiThread
runOnUiThread(newRunnable() {
@Overridepublicvoidrun() {
//code to update the ui
}
});
good luck
Solution 2:
i not recommend you handler,you can use Interface here. where you get all values use pass it to your activity and use that one.
Here i have posted example just try to follow and use this way.
You can pass interval here according to your need.
publicstaticfinallong UPDATE_INTERVAL_IN_MILLISECONDS = 30000
and one more thing you can pass fastest interval that is also help you.
Thanks
Solution 3:
I have been creating a simple Waiter class for it. It is really easy to understand and does the job very well. I post it for those who need it. just copy Waiter class and WaitListener interface and use it like I show.
Here is the Class:
import android.os.Handler;
import android.os.Looper;
publicclassWaiter {
WaitListener waitListener;
intwaitTime=0;
Handler handler;
intwaitStep=1000;
intmaxWaitTime=5000;
booleancondition=false;
publicWaiter(Looper looper, finalint waitStep, finalint maxWaitTime){
handler = newHandler(looper);
this.waitStep = waitStep;
this.maxWaitTime = maxWaitTime;
}
publicvoidstart(){
handler.post(newRunnable() {
@Overridepublicvoidrun() {
waitListener.checkCondition();
if (condition) {
waitListener.onConditionSuccess();
} else {
if (waitTime <= maxWaitTime) {
waitTime += waitStep;
handler.postDelayed(this, waitStep);
} else {
waitListener.onWaitEnd();
}
}
}
});
}
publicvoidsetConditionState(boolean condition){
this.condition = condition;
}
publicvoidsetWaitListener(WaitListener waitListener){
this.waitListener = waitListener;
}
}
And here is the Interface :
publicinterfaceWaitListener {
publicvoidcheckCondition();
publicvoidonWaitEnd();
publicvoidonConditionSuccess();
}
You can for example use it like that for a connection check:
ConnectivityManagermConnMgr= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
finalintresult= mConnMgr.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, "enableMMS");
finalWaiterwaiter=newWaiter(getMainLooper(), 1000, 5000);
waiter.setWaitListener(newWaitListener() {
@OverridepublicvoidcheckCondition() {
Log.i("Connection", "Checking connection...");
NetworkInfonetworkInfo= mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
waiter.setConditionState(networkInfo.isConnected());
}
@OverridepublicvoidonWaitEnd() {
Log.i("Connection", "No connection for sending");
//DO
}
@OverridepublicvoidonConditionSuccess() {
Log.i("Connection", "Connection success, sending...");
//DO
}
});
waiter.start();
Post a Comment for "How To Make Android Wait?"