Use so many Handler with postDelay method in android java - java

i'm working on kind animation program that i'm showing gif with Glide library but i'm using handlers too much for example showing loader and with another handler sync my sequence of showing others gif , i create like this
Handler handler2 = new Handler();
handler2.postDelayed(new Runnable() {
#Override
public void run() {
//showing gif file
}
}, 1000);
Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
}
}, 5000);
Handler handler3 = new Handler();
handler3.postDelayed(new Runnable() {
#Override
public void run() {
}
}, 6000);
and every one this handler are inside each other not exactly like above my question is :
Should i only create one instance from handler and use it ? like bloew
Handler handler = new Handler();
handler .postDelayed(new Runnable() {
#Override
public void run() {
}
}, 1000);
handler.postDelayed(new Runnable() {
#Override
public void run() {
}
}, 5000);
handler.postDelayed(new Runnable() {
#Override
public void run() {
}
}, 6000);
or i should do smoething else ?
i guess my application lagging a little not too much but i want to know the correct way to do it and if there is better way to handle this i appreciate any suggestion.
Should i destroy each handler and runnable after the task finished or not ?
Thanks in advance

Related

Android - Nested Handler / Runnable

My application content part had too much code. There were about 3000 lines of XML code. This caused my application to startup slowly. (launch in about 8 seconds) I placed the content in 6 viewstub objects. and I created a lot of handlers. Is it a problem? Is it hierarchically correct? How can I do all these handler operations asynctask.
Also how can I make my content lighter and faster.
Thanks in advance!
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
viewStubPager.setLayoutResource(R.layout.viewstubpager);
coachStubPager = viewStubPager.inflate();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
viewStub1.setLayoutResource(R.layout.viewstub1);
coachStub1 = viewStub1.inflate();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
viewStub2.setLayoutResource(R.layout.viewstub2);
coachStub2 = viewStub2.inflate();
viewStub3.setLayoutResource(R.layout.viewstub3);
coachStub3 = viewStub3.inflate();
viewStub4.setLayoutResource(R.layout.viewstub4);
coachStub4 = viewStub4.inflate();
viewStub5.setLayoutResource(R.layout.viewstub5);
coachStub5 = viewStub5.inflate();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Objects.requireNonNull(notificationManager).cancelAll();
sharedPreferencesKeys();
initialize();
calculate();
sharedPrefStartup();
alertDialogClickListener();
changeListener();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
layouts = new int[]{R.layout.vki_slide1, R.layout.vki_slide2, R.layout.vki_slide3, R.layout.vki_slide4, R.layout.vki_slide5, R.layout.vki_slide6, R.layout.vki_slide7, R.layout.vki_slide8, R.layout.vki_slide9};
VKIPagerAdapter = new MyViewPagerAdapter();
vkipager.setAdapter(VKIPagerAdapter);
VKIPagerAdapter.notifyDataSetChanged();
vkipager.setOffscreenPageLimit(10);
vkipager.addOnPageChangeListener(viewPagerPageChangeListener);
pageIndicator.setCount(layouts.length);
pageIndicator.setSelection(0);
bottombar.setVisibility(View.VISIBLE);
}
}, 100);
}
}, 100);
}
}, 100);
}
}, 100);
}
}, 150);
It's a bit late, but this might help others...
I don't know if the code in the question will start faster with my proposed solution (I doubt this will be the case), however, it's way more readable and uses only one Runnable. This can also be used for animations.
I derived this example from the following answer:
https://stackoverflow.com/a/11198037/6423246
Handler mHandler = new Handler();
int inflater = YOUR_CONSTANT_1;
void yourFunction() {
// ...your first inflater code here...
mHandler.postDelayed(mRunnable, your_delay_in_millis);
}
Runnable mRunnable = new Runnable() {
#Override
public void run() {
switch(inflater) {
case YOUR_CONSTANT_1 : {
// ...your second inflater code here...
inflater = YOUR_CONSTANT_2;
mHandler.postDelayed(mRunnable, your_delay_in_millis);
break;
}
case YOUR_CONSTANT_2 : {
// ...your third inflater code here...
inflater = YOUR_CONSTANT_3;
mHandler.postDelayed(mRunnable, your_delay_in_millis);
break;
}
// etcetera
case YOUR_CONSTANT_LAST : {
// ...your last inflater code here...
// in your final case, you could opt to remove callbacks
mHandler.removeCallbacks(mRunnable);
break;
}
}
}
};

Can I use startForeground(id, notification) in a service to update notification progress bar properly?

I have a situation where I need to update the notification progress bar after some few more milliseconds. If I use notification manager to update the progress, then the notification will show up even after calling stopForground(true) which is not what I need.
Here is the sample code using the notification manager to update.
private void doStuff() {
// starting in foreground
startForeground(123, notification.build());
final Thread thread = new Thread(new Runnable() {
#Override
public void run() {
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
timer++;
if(timer > 10){
stopForeground(true);
stopSelf();
return;
}
if(!bound){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
notificationManager.notify(123, notification.setProgress(10, timer, false).build());
}
}, 2000);
}
handler.postDelayed(this, 1000);
}
}, 1000);
}
});
thread.start();
}
otherwise, if I use startForground() way, the notification won't show up after the 2000 milliseconds and I get the desired behavior as shown below:
private void doStuff() {
// starting in foreground
startForeground(123, notification.build());
final Thread thread = new Thread(new Runnable() {
#Override
public void run() {
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
timer++;
if(timer > 10){
stopForeground(true);
stopSelf();
return;
}
if(!bound){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startForeground(123, notification.setProgress(10, timer, false).build());
}
}, 2000);
}
handler.postDelayed(this, 1000);
}
}, 1000);
}
});
thread.start();
}
My question is if there would be something wrong I'm not aware of using this way because I have never seen anyone doing it. Please help! Thanks!

Delay is not working after 1 hour

I am using a hanfler within the service to call a method after a delay in android. Its not working for long delays but the same code works for small delay.
Handler mHandler;
Runnable runnable;
mHandler = new Handler();
runnable=new Runnable() {
#Override
public void run() {
Log.i("START SERVICE", "START SERVICE:3 Call to Check Status is called");
callToCheckStatus();
mHandler.postDelayed(this, 1000*60*60);
}
};
mHandler.postDelayed(runnable, 1000*60*60);
On some blogs i find that when device goes deep sleep then it does not work. SO whats the right way to call a method within in Android.
Try This
public static void intertiAdsStartTimer(Context cnxt) {
timer = new Timer();
initializeTimerTask(cnxt);
//timer.schedule(timerTask, delayTime, repeatedTime);
timer.schedule(timerTask, 0, Integer.parseInt("7") * 60 * 1000); //
}
public static void initializeTimerTask(final Context cnxt) {
try {
final Handler handler = new Handler(Looper.getMainLooper());
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
try {
//call your method
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
} catch (Exception e) {
e.printStackTrace();
}
}
OR
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 10s = 10000ms
}
}, 10000);

Call function with timeout

i have a function
protected void updateLogs()
in my activity (MainActivity).
I need to call this function with delay. I cann't use this method https://stackoverflow.com/a/9166354/3883330 because i can't call function from other class, because it's not static function. Code with error:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
MainActivity.updateLogs();
}
}, 100);
How can i solve this?
This should work:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
updateLogs();
}
}, 100);
If it doesn't, declare a final object containing this:
final MainActivity main = this; // Just need to make it final
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
main.updateLogs();
}
}, 100);
As Carnal pointed out, it would be cleaner to declare an interface making the method to call public, however since you're calling it from an inner class, I think it's OK that way.

How to stop series of postDelayed handlers

I have a series of postDelayed handlers. I'm having trouble to set a mathode that stops the handlers when the user is tapping on the stop button at any time I he wants.
I'll appreciate any help someone able to provide.
Thanks
while (!lessonIsRunning) {
Handler handler0 = new Handler();
handler0.postDelayed(new Runnable() {
#Override
public void run() {
plate1.setVisibility(ImageView.VISIBLE);
plate2.setVisibility(ImageView.VISIBLE);
plate3.setVisibility(ImageView.VISIBLE);
}
}, 6000);
Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
apples1.setVisibility(ImageView.VISIBLE);
}
}, 9000);
Handler handler2 = new Handler();
handler2.postDelayed(new Runnable() {
#Override
public void run() {
plus1.setVisibility(TextView.VISIBLE);
}
}, 9250);
}
public void stopLesson(View V){
}
instead of writing the Runnable task in an anonymous way you must define it with a name, so that later you will have a link to it to remove:
//there is no need for multiple handlers
//handler must be declared outside all functions, in order for you to use it everywhere.
Handler handler = new Handler();
Runnable myFirstTask = new Runnable (){
#Override
public void run() {
plate1.setVisibility(ImageView.VISIBLE);
plate2.setVisibility(ImageView.VISIBLE);
plate3.setVisibility(ImageView.VISIBLE);
} };
Runnable mySecondTask = new Runnable(){
#Override
public void run() {
plus1.setVisibility(TextView.VISIBLE);
}
};
Runnable myThirdTask = new Runnable(){
#Override
public void run() {
apples1.setVisibility(ImageView.VISIBLE);
} }
//you can put different tasks on the same handler object
while (!lessonIsRunning) {
handler.postDelayed(myFirstTask,6000);
handler.postDelayed(mySecondTask,9250);
handler.postDelayed(myThirdTask,9000);
}
public void stopLesson(View V){
//notice that you don't need these, because the handlers are not recursive
//you don't have lines "handler.postDelayed(sameTask,someTime);"
//in your run Method of the runnable
if(handler!=null){
handler.removeCallbacks(myFirstTask);
handler.removeCallbacks(mySecondTask);
handler.removeCallbacks(myThirdTask);
//if this method is inside onPause or onDestroy add this line as well:
handler=null;
}
}
you can give
handler0.removeCallbacksAndMessages(null);
handler1.removeCallbacksAndMessages(null);
handler2.removeCallbacksAndMessages(null);
a try. The doc says when you submit a null token all callbacks and message are removed.

Categories

Resources