Random CountDownTimer on 3 Activity - java

I am a new user and have a question
how to auto roll activity with random countdown time ?
example : ActivityScreen1 display time in 50s-60s -> ActivityScreen2 display time in 30s-40s -> ActivityScreen2 display time in 50s-60s.

Still I want you to learn Android first from some good tutorials. But I can guide you how you can achieve this.
You will make a Service. Which will run in background.
You will make a Handler in your service. That will call postDelayed() method.
Like this
final Runnable r = new Runnable() {
public void run() {
changeActivity(); // make this method & add your logic of checking current activity & setting new
}
};
handler.postDelayed(r, 1000); // 1000 is millisecond, you will set time here.

Related

CountDownTimer doesn't count down by the specified intervals

I'm trying to build a count-down timer function in my app, however, it doesn't run as expected.
timer = new CountDownTimer(100, 10) {
#Override
public void onTick(long l) {
Log.d(TAG, "onTick: " + l);
}
#Override
public void onFinish() {
}
}.start();
My expectations are that it would count down gradually from 100,90,80...till 0
Although the output timer is showing quite random times (34 then 18 then 8..etc).
How can I achieve what I want?
It's difficult to explain the exact idea I'm trying to achieve but basically, I'm using touch listeners to hover over an item which in turn loads a few other items in the view. For some reason, there should be an intentional delay of around 100ms before these items could be displayed. I'm trying to build a progress bar that tells the user that something is loading rather than giving the impression that the screen is just stuck. I hope that helps to give a better idea of what I'm trying to achieve

How do I make sure a toast is on screen for a specific time before another toast replaces it?

I've just started learning Android. I use my MIUI 10 device for debugging.
I've learned the very basic App Lifecycle Program. The problem is, I'm using toasts to show when each of the methods are being called. For eg: When I press the back button, onPause, onStop and onDestroy are 3 SEPERATE toasts that will be displayed.
The problem I'm facing is that MIUI will automatically cancel the current toast if another one is called. So I end up with only onDestroy toast displaying.
Is there a way to ensure I have the toast on screen for a set amount of time before the next one comes? This doesn't have to only apply to this scenario. I need a general solution that will help in the future as well.
If MIUI's version of Android has altered the default behaviour where Toasts are displayed sequentially, you can always post them with a delay yourself. The standard delay period for a long toast is 3500ms, and a short toast is 2000ms. With that in mind, you could try something along these lines (untested):
final Handler uiHandler = new Handler(Looper.getMainLooper());
void scheduleToasts(String... messages) {
final List<String> list = Arrays.asList(messages);
Collections.reverse(list);
final AtomicInteger countdown = new AtomicInteger(list.size());
final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleWithFixedDelay(() -> {
final int count = countdown.getAndDecrement();
if(count == 0) {
service.shutdown();
return;
}
uiHandler.post(() -> Toast.makeText(getContext(), list.get(count), Toast.LENGTH_LONG).show());
}, 0, 3500, TimeUnit.MILLISECONDS);
}
With usage:
scheduleToasts("message1", "message2", "message3");

MouseMoved Timer Countdown in Swing

i would like to ask how to make 60 sec countdown with Timer starting when first moving the mouse (and display it in the title). Then at the end i would like to display some jOptionPane.Message or something. Here's the code...
private void jPanel2MouseMoved(java.awt.event.MouseEvent evt) {
jPanel1.setBounds(evt.getX(), evt.getY(), jPanel1.getWidth(), jPanel1.getHeight());
int a = KEK.nextInt(jPanel2.getWidth()-15);
int b = KEK.nextInt(jPanel2.getHeight()-15);
if(jPanel1.getBounds().intersects(jPanel3.getBounds()) == true){
rurin++;
jPanel3.setBounds(a, b, jPanel3.getWidth(), jPanel3.getHeight());
this.setTitle("Number of red dots touched: " +rurin+" ");
}
}
Create an instance of the class that implements the ActionListener: Example EmilsListener list = new EmilsListener();
Create an instance of the Timer class, and pass object and the time for it to restart to it:Timer tym = new Timer(1000,list);
Add the listener to the timer and then start the timer: Eg
tym.addActionListener(list);
tym.start();//But before this make sure you defined the EmilsListener class which must also contain your `jPanel2MouseMoved()` method.
You can check out a complete example of the timer in the accepted answer from this stackoverflow page

Breaking recursion from listeners

I'm trying to break a special case that makes this code recursive.
I have a Javafx game where there are human and computer players each play when it's his turn and there can be many rounds.
A computer is supposed to play automatically and move to the next player immediately and show no direct indication to the UI (but it's possible to review what it did afterwards).
The problem is in the case where there are only computer players, we will come here the moment the currentBoardPane was loaded, enter the condition since all players are computers, set the board of the next player, and then without finishing the call, call this same function again:
currentBoardPane.addListener((e) -> {
if(gameManager.checkIfCurrentPlayerIsComputer()){
gameManager.playAutoMovesForCurrentPlayer();
gameManager.setNextPlayer(); // it does current player property = next player
//update board on scene
currentBoardPaneIndex = ((currentBoardPaneIndex + 1) % gameManager.getPlayers().size());
currentBoardPane.setValue(boardPanes.get((currentBoardPaneIndex))); //this is a recursive call
}
});
Instead of this, if I subscribe a listener to the currentPlayer property in GameManager then I still need to call setNextPlayer() from that listener which is again recursive.
I can make a special case if all players are a computer, then run the game from a while(true){} instead of listeners and binds but there has to be a better way to break this recursion.
Is there a way to not get into recursion while still having listeners and binds?
Notes:
currentBoardPane signifies the current game board on the screen and it's an ObjectProperty.
Making the following assumptions about your code:
Everything is currently running on the FX Application Thread
The currentBoardPane.setValue(...) causes the UI to update (so you update the UI each move)
then a "quick and dirty" way to do this is:
currentBoardPane.addListener((e) -> {
if(gameManager.checkIfCurrentPlayerIsComputer()){
gameManager.playAutoMovesForCurrentPlayer();
//update board on scene
Platform.runLater(() -> {
gameManager.setNextPlayer(); // it does current player property = next player
currentBoardPaneIndex = ((currentBoardPaneIndex + 1) % gameManager.getPlayers().size());
currentBoardPane.setValue(boardPanes.get((currentBoardPaneIndex))); //this is a recursive call
});
}
});
This delegates the updates to a new Runnable, schedules that runnable to execute on the FX Application Thread, and exits the handler immediately. Thus the call to currentBoardPane.setValue(...) is executed later and is no longer recursive.
In fact, if you do just a little more work:
private final Executor aiExecutor = Executors.newSingleThreadExecutor();
// ...
currentBoardPane.addListener((e) -> {
if(gameManager.checkIfCurrentPlayerIsComputer()){
Task<Void> makeMoveTask = new Task<Void>() {
#Override
protected Void call() {
gameManager.playAutoMovesForCurrentPlayer();
return null ;
}
};
makeMoveTask.setOnSucceeded(e -> {
//update board on scene
gameManager.setNextPlayer(); // it does current player property = next player
currentBoardPaneIndex = ((currentBoardPaneIndex + 1) % gameManager.getPlayers().size());
currentBoardPane.setValue(boardPanes.get((currentBoardPaneIndex))); //this is a recursive call
});
aiExecutor.execute(makeMoveTask);
}
});
then this is exactly the code you would use if computing the move took enough time that it would not be acceptable to block the UI while it was happening. (And if computing the move takes very little time, this will still work just fine.) This assumes that playAutoMovesForCurrentPlayer() doesn't update the UI.

Give an image a new X and Y postion every 1 second

I am trying change the image LayoutX and LayoutY positions ever 1 second. But I cant find any (timer) method suitable for this. I am looking for something similar to the JavaScript "setInterval" that simply lets me create a "timer cycle" using Java or JavaFX.
Any advice are widely appriciated!
With java.util.Timer you can schedule such a task.
The method timer.schedule() executes a task only ones. To repeat your task
use the method timer.scheduleAtFixedRate().
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
System.out.println("hello");
}
}, 1000, 1000);
The second parameter of scheduleAtFixedRate() is the delay before the first execution in milliseconds and the last parameter is the interval between the tasks being executed in milliseconds.
You can use a Timeline with INDEFINITE cycle count for this purpose.
Example:
Timeline tl = new Timeline(new KeyFrame(Duration.seconds(1), evt -> {
// toggle image postion
imageView.setLayoutX(200 - imageView.getLayoutX());
imageView.setLayoutY(200 - imageView.getLayoutY());
}));
tl.setCycleCount(Animation.INDEFINITE);
tl.play();
This guaranties the event handler runs on the JavaFX application thread.

Categories