Until now I have been using the Timer that's in javax.swing.timer - all I had to do was to choose the speed and have a method with a specific name that executes what I want the timer to do every time.
I have now started programming an Android application recently and I have faced a couple of problems...
It wouldn't let me use or import javax.swing.timer
I tried using java.util.timer but I couldnt figure out how it works
All I want my timer for is so I can display my logo for 3 seconds and then proceed to the main menu - even if there is an easier solution for this, I'd still like to know how to use the timer
For the person who told me to try using a thread - here is my code - it doesnt paint the first screen at all, it just stays blank for 3 seconds then moves on to the next line of code...
public class logo extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.logoview);
Thread.sleep(3000);
}
catch (InterruptedException e){
e.printStackTrace();
}
setContentView(R.layout.main);
}
public void startup (View view){
Intent intent0 = new Intent (this,ExpiramantingActivity.class);
startActivity(intent0);}
}
}
in onCreate() function of your SplashActivity class, schedule a handler to display your main menu activity after 3 seconds. this should be done after setContentView(R.layout.splashscreen);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(SplashActivity.this,
YourMainMenuActivity.class));
finish();
}
}, 3000);
I believe that what you are trying to do is similar to the exhibition Splash Screen. If so, please check this Oracle tutorial.
try this:
// logo
Thread timer = new Thread(){
public void run(){
try{
sleep(3000);
} catch (InterruptedException e){
e.printStackTrace();
}
};
};
timer.start();
//next code
Maybe you can use a Thread? I think it's the simplest way to do what you want:
Where you display your logo:
try {
//show your logo here
Thread.sleep(3000); //3 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
Surrounding the code in a try/catch block is very important, because of the posibility of an Exception.
Related
I have a button on an activity, when I click it I want the button to change colour, wait some time and then change colour again.
I have tried the following two versions of the sleep:
Attempt 1:
public void buClick(View view) {
Button buCard = (Button) view;
buCard.setBackgroundColor(Color.GREEN);
TimeUnit time = TimeUnit.SECONDS;
try {
time.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
buCard.setBackgroundColor(Color.RED);
}
Attempt 2:
public void buClick(View view) {
Button buCard = (Button) view;
buCard.setBackgroundColor(Color.GREEN);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
buCard.setBackgroundColor(Color.RED);
}
With both methods the result is the same:
button is clicked
button's background remains as the default
the app waits for 2 seconds
the button's background changes to red
At no point does the button turn green; what am I doing wrong?
Thanks
Do not block your UI thread. Use a handler instead.
If you are trying to block your main thread the whole UI thread would stop causing your app to freeze, once your sleep is over you are calling setBackgroundColor(Color.RED). And the red color gets applied that is why you are not able to see the change of green color.
If you use a handler like the below case which wont block the UI thread you should be able to see the color change.
Read about why you should not block your UI thread here https://developer.android.com/guide/components/processes-and-threads.html
Button buCard = (Button) view;
buCard.setBackgroundColor(Color.GREEN);
Handler handler = new Handler();
Runnable r=new Runnable() {
public void run() {
buCard.setBackgroundColor(Color.RED);
}
};
handler.postDelayed(r, 2000);
This is my first question so sorry if I don't provide all the needed info. Just comment and I'll add it.
Onto the problem itself. I'm trying to make a splash screeen of sorts which consists of a short video. I want the app to start the following activity after the video ends, but after I start the app it just starts the second activity right away (Menu.class in the code). Once I'm in the Menu activity I can go back but all i see is a black VideoView. Also, the VideoView worked before I added the Handler. Not sure if it even could have been the problem (new to android studio) but doesn't work even after removing #Override (probably a stupidity, right?). Or can it be caused by the Menu.java activity? (It's just the standard pre-generated preset, I didn't make any changes to it)
public class splash_screen extends AppCompatActivity {
static long duration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.activity_splash_screen);
VideoView videoView = this.findViewById(R.id.videoView);
String path = "android.resource://" + getPackageName() + "/" + R.raw.splash;
videoView.setVideoURI(Uri.parse(path));
videoView.start();
duration = videoView.getDuration();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(splash_screen.this, Menu.class));
}
}, duration);
}
}
Thanks for any and every advice, and like I said let me know if you need more info on the problem.
VideoView need some time to warm up, so here:
videoView.start();
duration = videoView.getDuration();
duration could be 0, that is why handler fires immediately. To switch to the second activity you should remove handler part and use:
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
startActivity(new Intent(splash_screen.this, Menu.class));
finish();//close activity
}
});
You Can Also Use Thread.sleep(millisecond); If you are adding animation to your splash screen
The Full C O D E:
Thread t=new Thread(){
#Override
public void run() {
try{
sleep(3000);
}
catch (InterruptedException e){
}
finally {
startActivity(i);
}
}
};
t.start();
It Gives a delay of 3 seconds,you can do animation part within it
I am developing a board game that user plays with android. Since android is quite fast, I want to fake that android is performing some tough calculations and thus needs time for its next move.
What I want to do:-
User turn - he moves.
Android turn - android shows text "I am thinking" for 2 seconds
Android hides that text and and only after that moves his turn.
I tried doing:-
onAndroidTurn(){
textView1.setVisibility(View.VISIBLE);
Thread.sleep(2000);
textView2.setVisibility(View.GONE);
}
But what happens is that thread sleeps but text is not shown (okay I know why).
Then searching on stackoverflow, I learnt a way:-
onAndroidTurn(){
textView1.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable(){
void run() {
textView1.setVisibility(View.GONE);
}
}, 2000);
}
Now what this does is that it runs that text in another thread and android's turn is updated on screen and after moving it's turn android showing "Thinking" is total stupidity.
What can I do for this?
Try the following:
Show "I'm thinking"
Calculate your move but don't actually do the move, just store it for a while
Schedule timer
When timer runs out remove the text and do the move
Something like this:
onAndroidTurn(){
textView1.setVisibility(View.VISIBLE);
saveMove(calculateNextMove());
new Handler().postDelayed(new Runnable(){
void run() {
textView1.setVisibility(View.GONE);
doNextMove(restoreMove());
}
}, 2000);
}
Maybe you could just use an AsyncTask (like this pseudo-code):
private class ShowTextTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute(Void... result) {
textView.setText("Initital");
}
protected Long doInBackground(Void... urls) {
Thread.sleep(2000);
}
protected void onPostExecute(Void... result) {
textView.setText("After 2 seconds");;
}
}
Okay i did it like this:-
public void androidThinking(){
textView1.setVisibility(View.VISIBLE);
androidThinking = true; //explained below
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
droidThink.setVisibility(View.GONE);
//CODE for android's turn
androidThinking = false; //explained below
}
}, 2000);
androidThinking when set to true prevents the user from moving his turn by forcing the listener for user's button to return prematurely
btn.setOnClickListener(new View.onClickListener(){
#Override
public void onClick(View v) {
if(androidThinking)
return;
Thanx everyone for your reply.
I have an Androd application that talks to a back-end web service. As part of the testing, I need to simulate different lengths of client-side delay when a submit button is pressed.
Right now, I am using a Thread.sleep() in my OnClickListener for my submit button, but sleeping the UI thread like this has the unintended consequence of causing the app to appear to "freeze" completely - the button stays highlighted until the thread wakes up and my ProgressBar is likewise completely frozen. Here is my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkout);
pBar = (ProgressBar) findViewById(R.id.progressBar1);
pBar.setVisibility(View.INVISIBLE);
Button submitButton = (Button) findViewById(R.id.btnSubmit);
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
pBar.setVisibility(View.VISIBLE);
try {
Thread.sleep(3000); //eventually this delay will be random
//right now it obviously hangs the UI
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
performMyAppSpecificWorkHere();
pBar.setVisibility(View.INVISIBLE);
CheckoutActivity.this.finish();
}
});
}
I'm looking for ways I could simulate a delay without hanging the entire UI. Any ideas are welcome. Thanks!
edit
Some clarification here! Part of what I need to do is make simulate a delay and allow the user interface to handle it cleanly (which is what's NOT happening now).
ie...if there is a delay on either the client or the web service, the client should handle it by letting the spinner spin while it waits. The ability to simulate a back-end delay is already done and that works the way I want it to, but I want to simulate a delay on the client without hanging the UI thread.
here we go:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkout);
pBar = (ProgressBar) findViewById(R.id.progressBar1);
pBar.setVisibility(View.INVISIBLE);
Button submitButton = (Button) findViewById(R.id.btnSubmit);
submitButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Thread t=new Thread(new Runnable(){
#Override
public void run(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
performMyAppSpecificWorkHere();
runOnUiThread(new Runnable() {
#Override
public void run() {
pBar.setVisibility(View.INVISIBLE);
CheckoutActivity.this.finish();
}
}
}
});
pBar.setVisibility(View.VISIBLE);
t.start();
}
});
}
So, you are starting a new thread in the onClick event. This new thread should do the application work after sleeping for 3 seconds. After that, you want to update some ui objects, and you can not do that from inside a thread that isn't the UI Thread. That's why there is a runOnUiThread(..) after performing the work. Hope it helps!
First of all, don't block the main thread (the ui-thread), or else the gui will be freezed! Instead, use AsyncTask, where you put Thread.sleep(3000) inside doInBackground(), and then do whatever you want inside onPostExecute() (onPostExecute() is running in the main thread). Check my last answer on related question.
I think you should clarify here, you want to simulate server side delays and not the client side delay. You should put the sleep code in your server side code and not the client side code.
If it is not so, you can use asyncTask and execute the application code. You can put the sleep code inside it to simulate a client side delay.
I have written a function to create a splash screen with a 5 second timeout for my app.
The code works fine, but when the timeout reaches zero and I want to redirect to my main activity, the app crashes with the following error:
Only the original thread that created a view hierarchy can touch its views.
So I looked around a bit and someone suggested nesting this inside my function. It seems like a good Idea, but now methods like sleep / stop won't work.
My code is below, I can provide more / explain more in details if it isn't clear enough just let me know. Thanks for the help.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showSplashScreen();
}
protected boolean _active = true;
protected int _splashTime = 5000; // Splash screen is 5 seconds
public void showSplashScreen() {
setContentView(R.layout.splash_layout);
// Thread splashThread = new Thread() {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
int waited = 0;
while (_active && (waited < _splashTime)) {
Thread.sleep(100);
if (_active) {
waited += 100;
}
}
} catch (InterruptedException e) {
// do nothing
} finally {
showApplication();
}
}
});
}
Probably not what you want to hear, but you should never put a splash screen on your mobile app. With the exception of games, when people use a mobile app they want to get in, do what ever it is they need to do, and get out. If you make that process take longer, people are just going to get frustrated with you app. You should probably reconsider just not using a splash screen.
This will perform sleep on the UI thread. That's never a good idea.
Why not something like this?
new Handler().postDelayed(new Runnable() {
public void run() {
// start application ...
}
}, _splashTime);
But this answer has a good point. Displaying a splash screen for 5 seconds can be very annoying.
I believe you want AsyncTask for this. The method called on completion of the task will be called on your UI thread, making modifying UI elements much easier.
Use a Handler to post an event to the UI thread that will remove the splash.
Code should be something like...
splash.show()
new Handler().postDelayed(
new Runnable() {
void run() {
splash.remove();
},
delayTime);
I suggest you to make new activity for your spalsh screen, show it in a regular way (with startActivityForResult) and place in it such code (in it, not in your main activity):
new Handler().postDelayed( new Runnable()
{
public void run()
{ finish(); }
}, 5000 );
Also you can handle in this new activity click events for giving opportunity to user to close it faster, tapping on it.