synchronized blocks containing method calls, will this work? - android

Is the code below legit for synchronizing myIntArray?
Will it prevent the three bottom methods from changing myIntArray out of order?
I Want things to happen in the order delayedMethod1, delayedMethod2, method3 and not have one of them screwed up by running before the previous one has finished its changes to myIntArray.
Do the bottom 3 method declarations need the synchronized keywords?
Do the bottom 3 methods need to contain synchronized(myIntArray) blocks?
Should my synchronized block be around the Runnable rather than inside it?
Do I neet notify, wait, or join commands?
public class HelpPlease {
public int myIntArray[] = new int[100];
public void chooseSquare() {
...
Handler handler=new Handler();
final Runnable r = new Runnable()
{
public void run()
{
synchronized(myIntArray) {
delayedMethod1();
}
}
};
handler.postDelayed(r, 1000);
...
Handler handler2=new Handler();
final Runnable r2 = new Runnable()
{
public void run()
{
synchronized(myIntArray) {
delayedMethod2();
}
}
};
handler2.postDelayed(r2, 1000);
...
synchronized(myIntArray) {
method3();
}
}
public void delayedMethod1() {
...
change myIntArray;
otherMethodsABC();
{
public void delayedMethod2() {
...
change myIntArray;
otherMethodsDEF();
}
public void method3() {
...
change myIntArray;
otherMethodsGHI();
}
}
More details: Handler/Runnable delays producing events that are out of sync sometimes
EDIT:
Does this make sense? To run a thread a wait for it to finish? Not sure how to add the delay tho, and that was the whole point.
//Handler handler=new Handler();
final Runnable r = new Runnable()
{
public void run()
{
delayedMethod();
}
};
//handler.postDelayed(r, COMPUTER_MOVE_DELAY);
ExecutorService es = Executors.newFixedThreadPool(1);
final Future f1 = es.submit(r);
try
{
f1.get();
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
catch (ExecutionException e)
{
throw new RuntimeException(e);
}

Don't try doing this with synchronized blocks. It will only guarantee that no two blocks will run simultaneously, not which order they run. You'd be better off writing a "parent" runnable that executes the delayed methods in the order you want. Alternatively, you can have the first method, when it is finished, post a runnable to run the second, etc., chaining them together.
To be more specific, if you want a delay and then for the three methods to run in sequence, I'd code it like this:
public class HelpPlease {
public int myIntArray[] = new int[100];
Handler handler=new Handler();
public void chooseSquare() {
...
final Runnable r = new Runnable()
{
public void run()
{
delayedMethod1();
delayedMethod2();
method3();
}
};
handler.postDelayed(r, 1000);
}
public void delayedMethod1() {
...
change myIntArray;
otherMethodsABC();
}
public void delayedMethod2() {
...
change myIntArray;
otherMethodsDEF();
}
public void method3() {
...
change myIntArray;
otherMethodsGHI();
}
}
No need for synchronization at all. It's important to use a single Handler to guarantee that multiple calls to chooseSquare() will result in serialized execution of the runnables.
EDIT:
Based on your latest comments, here's how I'd proceed. First, have a single Handler object that is accessible by all your action scheduling code. To use your two examples, these could then be implemented as follows:
public void chooseSquare() {
. . .
if (point_scored) {
makeSquaresGlow(list_of_squares);
playSound(sound_to_play);
handler.postDelayed(new Runnable() {
public void run() {
makeSquaresNotGlow(list_of_squares);
}
}, 1000L);
}
if (time_for_attack(purple)) {
handler.postDelayed(new Runnable() {
public void run() {
launchAttack(purple);
}
}, 1000L);
}
}
Assuming that chooseSquare() is called on the event thread, everything (including the delayed method calls) will also run on the same thread, so no synchronization is needed. There may be race conditions (launchAttack and makeSquaresNotGlow will be scheduled at the same time), but handler will execute one at a time. If the sequencing of these delayed actions is vital, you can define a "meta" action Runnable that accepts a sequence of actions and executes them in a prescribed order at a future time.

Related

Can I pause a program for a while? [duplicate]

I want to make a pause between two lines of code, Let me explain a bit:
-> the user clicks a button (a card in fact) and I show it by changing the background of this button:
thisbutton.setBackgroundResource(R.drawable.icon);
-> after let's say 1 second, I need to go back to the previous state of the button by changing back its background:
thisbutton.setBackgroundResource(R.drawable.defaultcard);
-> I've tried to pause the thread between these two lines of code with:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
However, this does not work. Maybe it's the process and not the Thread that I need to pause?
I've also tried (but it doesn't work):
new Reminder(5);
With this:
public class Reminder {
Timer timer;
public Reminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}
class RemindTask extends TimerTask {
public void run() {
System.out.format("Time's up!%n");
timer.cancel(); //Terminate the timer thread
}
}
}
How can I pause/sleep the thread or process?
One solution to this problem is to use the Handler.postDelayed() method. Some Google training materials suggest the same solution.
#Override
public void onClick(View v) {
my_button.setBackgroundResource(R.drawable.icon);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
my_button.setBackgroundResource(R.drawable.defaultcard);
}
}, 2000);
}
However, some have pointed out that the solution above causes a memory leak because it uses a non-static inner and anonymous class which implicitly holds a reference to its outer class, the activity. This is a problem when the activity context is garbage collected.
A more complex solution that avoids the memory leak subclasses the Handler and Runnable with static inner classes inside the activity since static inner classes do not hold an implicit reference to their outer class:
private static class MyHandler extends Handler {}
private final MyHandler mHandler = new MyHandler();
public static class MyRunnable implements Runnable {
private final WeakReference<Activity> mActivity;
public MyRunnable(Activity activity) {
mActivity = new WeakReference<>(activity);
}
#Override
public void run() {
Activity activity = mActivity.get();
if (activity != null) {
Button btn = (Button) activity.findViewById(R.id.button);
btn.setBackgroundResource(R.drawable.defaultcard);
}
}
}
private MyRunnable mRunnable = new MyRunnable(this);
public void onClick(View view) {
my_button.setBackgroundResource(R.drawable.icon);
// Execute the Runnable in 2 seconds
mHandler.postDelayed(mRunnable, 2000);
}
Note that the Runnable uses a WeakReference to the Activity, which is necessary in a static class that needs access to the UI.
You can try this one it is short
SystemClock.sleep(7000);
WARNING: Never, ever, do this on a UI thread.
Use this to sleep eg. background thread.
Full solution for your problem will be:
This is available API 1
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View button) {
button.setBackgroundResource(R.drawable.avatar_dead);
final long changeTime = 1000L;
button.postDelayed(new Runnable() {
#Override
public void run() {
button.setBackgroundResource(R.drawable.avatar_small);
}
}, changeTime);
}
});
Without creating tmp Handler. Also this solution is better than #tronman because we do not retain view by Handler.
Also we don't have problem with Handler created at bad thread ;)
Documentation
public static void sleep (long ms)
Added in API level 1
Waits a given number of milliseconds (of uptimeMillis) before returning. Similar to sleep(long), but does not throw InterruptedException; interrupt() events are deferred until the
next interruptible operation.
Does not return until at least the specified number of milliseconds has elapsed.
Parameters
ms to sleep before returning, in milliseconds of uptime.
Code for postDelayed from View class:
/**
* <p>Causes the Runnable to be added to the message queue, to be run
* after the specified amount of time elapses.
* The runnable will be run on the user interface thread.</p>
*
* #param action The Runnable that will be executed.
* #param delayMillis The delay (in milliseconds) until the Runnable
* will be executed.
*
* #return true if the Runnable was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the Runnable will be processed --
* if the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*
* #see #post
* #see #removeCallbacks
*/
public boolean postDelayed(Runnable action, long delayMillis) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.postDelayed(action, delayMillis);
}
// Assume that post will succeed later
ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
return true;
}
I use this:
Thread closeActivity = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(3000);
// Do some stuff
} catch (Exception e) {
e.getLocalizedMessage();
}
}
});
I use CountDownTime
new CountDownTimer(5000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
// do something after 1s
}
#Override
public void onFinish() {
// do something end times 5s
}
}.start();
You probably don't want to do it that way. By putting an explicit sleep() in your button-clicked event handler, you would actually lock up the whole UI for a second. One alternative is to use some sort of single-shot Timer. Create a TimerTask to change the background color back to the default color, and schedule it on the Timer.
Another possibility is to use a Handler. There's a tutorial about somebody who switched from using a Timer to using a Handler.
Incidentally, you can't pause a process. A Java (or Android) process has at least 1 thread, and you can only sleep threads.
This is what I did at the end of the day - works fine now :
#Override
public void onClick(View v) {
my_button.setBackgroundResource(R.drawable.icon);
// SLEEP 2 SECONDS HERE ...
final Handler handler = new Handler();
Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
my_button.setBackgroundResource(R.drawable.defaultcard);
}
});
}
}, 2000);
}
In addition to Mr. Yankowsky's answers, you could also use postDelayed(). This is available on any View (e.g., your card) and takes a Runnable and a delay period. It executes the Runnable after that delay.
This is my example
Create a Java Utils
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
public class Utils {
public static void showDummyWaitingDialog(final Context context, final Intent startingIntent) {
// ...
final ProgressDialog progressDialog = ProgressDialog.show(context, "Please wait...", "Loading data ...", true);
new Thread() {
public void run() {
try{
// Do some work here
sleep(5000);
} catch (Exception e) {
}
// start next intent
new Thread() {
public void run() {
// Dismiss the Dialog
progressDialog.dismiss();
// start selected activity
if ( startingIntent != null) context.startActivity(startingIntent);
}
}.start();
}
}.start();
}
}
Or you could use:
android.os.SystemClock.sleep(checkEvery)
which has the advantage of not requiring a wrapping try ... catch.
If you use Kotlin and coroutines, you can simply do
GlobalScope.launch {
delay(3000) // In ms
//Code after sleep
}
And if you need to update UI
GlobalScope.launch {
delay(3000)
GlobalScope.launch(Dispatchers.Main) {
//Action on UI thread
}
}
I know this is an old thread, but in the Android documentation I found a solution that worked very well for me...
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
https://developer.android.com/reference/android/os/CountDownTimer.html
Hope this helps someone...
class MyActivity{
private final Handler handler = new Handler();
private Runnable yourRunnable;
protected void onCreate(#Nullable Bundle savedInstanceState) {
// ....
this.yourRunnable = new Runnable() {
#Override
public void run() {
//code
}
};
this.handler.postDelayed(this.yourRunnable, 2000);
}
#Override
protected void onDestroy() {
// to avoid memory leaks
this.handler.removeCallbacks(this.yourRunnable);
}
}
And to be double sure you can be combined it with the "static class" method as described in the tronman answer

Android- Updating UI elements with threading

I have a textview which i want to change with a thread and do it again and again (Like a digital clock). But i'm having problems with setting time between 2 changes. Here, the code:
display1 = (TextView) findViewById(R.id.textView1);
Thread timer2 = new Thread(){
#Override
public void run() {
synchronized (this){
runOnUiThread(new Runnable() {
#Override
public void run() {
int i = 0;
display1.setText("" + i);
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
display1.setText("" + (i+1));
}
});
}
}
};
timer2.start();
This sleep(2000); function makes textview invisible for the given time but i want it stand still till the next change. How can i do that?
But i'm having problems with setting time between 2 changes
Do NOT do sleep() on your UI thread. If you want to chain some actions with the delay, split your code into two runnables and the first one should set display1 and then post second runnable with the delay using postDelayed()
EDIT
want one of them to increase 3 per sec, and the other 5 per sec until they reach 1000 for instance
You can make your Runnable post itself until some criteria are met (i.e. time, counter value etc). Just at the end your Runnable check your conditions and if not met, call postDelayed(this, delay); and you are good.
You should use a Handler instead and dispatch your changes to the UI thread.
Handler mHandler = new Handler();
mHandler.post(new Runnable() {
#Override
public void run() {
// Code to be run right away
}
});
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
// Code to be run after 2 seconds
}
}, 2000);
Maybe split up what you need to do into separate methods. Here you have a UI method and a sleep method split up. Hope it helps
private void myMethod() {
new Thread() {
#Override
public void run() {
int i = 0;
doWorkOnUI(String.valueOf(i));
pause(2000);
doWorkOnUI(String.valueOf(i++));
}
}.start();
}
private void pause(int pauseTime) {
try {
Thread.sleep(pauseTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void doWorkOnUI(final String string) {
runOnUiThread(new Runnable() {
#Override
public void run() {
display1.setText(string);
}
});
}

Android Timer Tasks

I'm trying to make a timer that will do a certain thing after a certain amount of time:
int delay = 1000;
int period = 1000;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
//Does stuff
}
}, delay, period);
However, the app crashes after the wait period. This is Java code, so it might not be entirely compatible with Android (like while loops). Is there something I'm doing wrong?
Something like this should work, create a handler, and wait 1 second :) This is generally the best way of doing it, its the most tidy and also probably the best on memory too as its not really doing too much, plus as it's only doing it once it is the most simple solution.
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// do your stuff
}
}, 1000);
If you would like something to run every one second then something like this would be best:
Thread thread = new Thread()
{
#Override
public void run() {
try {
while(true) {
sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
If you want a GUI thread then something like this should work:
ActivityName.this.runOnUiThread(new Runnable()
{
public void run(){
try {
while(true) {
sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
If your app is crashing after the wait period, then your timer task is doing its job and executing your code on schedule. The problem must then be in your code where run() occurs (for example, you may be trying to update UI elements in a background thread).
If you post more code and your logcat, I can probably be more specific about the error you are getting, but your question was in regards to TimerTask.
Timer and also you can run your code on UI thread:
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
timerMethod();
}
}, 0, 1000);
}
private void timerMethod(){
// This method is called directly by the timer
// and runs in the same thread as the timer.
// We call the method that will work with the UI
// through the runOnUiThread method.
this.runOnUiThread(timerTick);
}
private Runnable timerTick = new Runnable() {
public void run() {
// This method runs in the same thread as the UI.
// Do something to the UI thread here
}
};

Updating UI using a Handler freezes my app

I am trying to make a clock, using a TextView :)
Someone here told me that I couldn't use normal threads to change the UI, but Handler or AsyncTask. I managed to get it working a few days ago, but was not a consistent thread.
Now what I want is a consistent thread that is always changing the text of my Textview. I tried using this, but didn't work, any help?
private void startClock() {
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
while (true) {
final long millis = System.currentTimeMillis() - MainActivity.startedAt;
clock.setText("" + millis);
runOnUiThread (new Runnable() {
#Override
public void run() {
clock.setText("" + millis);
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}, 2000);
}
you should get rid of:
while(true) {
....
sleep(1000);
...
}
because this get your thread stuck forever. your program should work like this:
private Handler mHandler = new Handler();
#Override
public void onResume() {
super.onResume();
mHandler.removeCallbacks(mUpdateClockTask);
mHandler.postDelayed(mUpdateCLockTask, 100);
}
#Override
public void onPause() {
super.onPause();
mHandler.removeCallbacks(mUpdateClockTask);
}
private Runnable mUpdateClockTask = new Runnable() {
public void run() {
updateClock();
mHandler.postDelayed(mUpdateClockTask, 2000);
}
};
and inside updateClock() you do all your UI updates.
Look here for an example https://stackoverflow.com/a/11140429/808940
Also note that you have a duplicate line in your code:
clock.setText(""+millis);
It appears both in the runOnUiThread and in the main handler, it should only appear in the runOnUiThread runnable

Handler.postdelayed

I am using handler.postDelayed method to create some delay for some animation stuff.
With that i am playing some song as well using Mediaplayer. User can exit this action class by clicking next. But on next screen the same song is continuing even though i called stop method in the next button's onclicklistener.
Is it due to the timedelay that is added which gets executed after the next activity is loaded. Any idea?
handler.postDelayed(new Runnable() {
public void run() {
mp = MediaPlayer.create(getApplicationContext(), R.raw.num2);
mp.start();
imageView1.setImageResource(R.drawable.countcat2);
}
}, 2000);
Did you add a Log to see if run() gets called? I would assume that your handler gets unregistered; after all, postDelayed will wait until the looper kicks in again.
I assume your animation is faster than those 2000ms? You wouldn't be able to have your handler called anyway after your activity is gone, it's accessing imageView1 which I presume is destroyed in onDestroy.
You could consider adding a flag that will force the operation to be called immediately in onDestroy, and/or you could use a Timer. In case of the timer, be sure to not use something like imageView1 after it has been destroyed.
Use threads. And then stop it with an interruption:
Public Thread getThread(final Handler handle, int delay)
{
return new Thread()
{
#Override
public void run()
{
try
{
synchronized(this)
{
Thread.sleep(delay);
handle.post(new Runnable()
{
#Override
public void run()
{
"the code to be exec."
}
});
}
}
catch(Exception e)
{
e.printStackTrace();
}
};
};
}
Or you can use use the postDelayed function
Public Thread getThread(final Handler handle, int delay)
{
return new Thread()
{
#Override
public void run()
{
try
{
synchronized(this)
{
handle.postDelayed(new Runnable()
{
#Override
public void run()
{
"the code to be exec."
}
}, delay);
}
}
catch(Exception e)
{
e.printStackTrace();
}
};
};
}
you will find that there's a little difference between this two methods. To interrupt it, do something like this:
Thread t = getThread(handle, delay);
t.start();
if(t != null)
{
if (t.isAlive())
{
t.interrupt();
}
}
Hope I have helped.

Categories

Resources