I'm making an activity where I'm planning to display a progress bar and move to a second activity after five seconds. I used Thread.sleep to do this.
Here is the code for the activity with the spinner.
public class WaitScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.waitscreen);
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
try{
for(int i=0;i<5;i++){
Thread.sleep(1000);
}
Toast.makeText(getApplicationContext(), "Spinner complete!", Toast.LENGTH_LONG).show();
}
catch(InterruptedException e){
}
Intent i = new Intent("emergency.app.NEWACTIVITY");
startActivity(i);
}
}
My main activity only has a button that leads to this page on being clicked. Problem is, it displays the main activity for five seconds, then this activity very briefly and then the third activity. How do I make the thread start after WaitScreen is fully loaded? As you can see, I tried using the onStart method to do the trick. Or if you could tell me another way to introduce a five second delay, that would be helpful too!
Use a Handler to post a Runnable, like so:
public class WaitScreen extends Activity {
private Runnable task = new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Spinner complete!", Toast.LENGTH_LONG).show();
Intent i = new Intent("emergency.app.NEWACTIVITY");
startActivity(i);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.waitscreen);
Handler handler = new Handler();
handler.postDelayed(task, 5000);
}
}
The Runnable task will execute after 5 seconds.
http://developer.android.com/reference/android/os/Handler.html
Related
I am creating a New Android application
I d like to switch from one activity to another activity after a time interval, How can i do this?
Kindly guide me
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app Next activity
Intent i = new Intent(CurrentActivity.this, NextActivity.class);
startActivity(i);
// close this activity
finish();
}
}, TIME_OUT);
There are numerous ways to do this.
You could use postDelayed(), however that is not advised since you cannot STOP it, or control it reliably, between various phases of activity lifecycle, to prevent for example wierd behaviour when the user exits the activity, before the delay has passed.
You would need some locks, or other mechanism.
Most proper approach would be to simply start a timer on the 1st activity onPostResume() which will start another activity after some delay.
TimerTask mStartActivityTask;
final Handler mHandler = new Handler();
Timer mTimer = new Timer();
#Override
private protected onPostResume() { // You can also use onResume() if you like
mStartActivityTask = new TimerTask() {
public void run() {
mHandler.post(new Runnable() {
public void run() {
startNewActivity(new Intent(MyClass.class));
}
});
}};
// This will start the task with 10 seconds delay with no intervals.
mTimer.schedule(mStartActivityTask, 100000, 0);
}
private void startNewActivity(Intent i) {
mTimer.cancel(); // To prevent multiple invocations
startActivity(i); // Start new activity
// finish(); // Optional, depending if you want to return here.
}
Try this code
private Thread thread;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
thread = new Thread(this);
thread.start();
}
#Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent userName = new Intent(this, UserNameActivity.class);
startActivity(userName);
}
I need some help with my first Android project.
I want to write a app which is showing you a picture with a ImageView for a few seconds I would say so about 4 seconds and after that it change to a second activity which shows a button(only for testing).
My Problem is that my app after I started it in my AVD jump over the picture and shows immediately the button.
How can I fix it? I looked up so long and tried so many things I hope someone of you have a idea :)
Thanks for helping
Here my Code of my MainActivity:
package com.example.parkourspots;
public class MainActivity extends Activity {
private ViewTreeObserver vto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final View myLayout = findViewById(R.id.startscreen);
vto = myLayout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
#Override
public void onGlobalLayout(){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(MainActivity.this, select_activity_class.class);
startActivity(intent);
}
});
}}
Check this code.
package com.example.parkourspots;
public class MainActivity extends Activity {
private static int TIME_OUT = 4000; //Time to launch the another activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final View myLayout = findViewById(R.id.startscreen);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(MainActivity.this, ActivityTwo.class);
startActivity(i);
finish();
}
}, TIME_OUT);
}
});
You can try:
public class MainActivity extends Activity {
private Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler.postDelayed(new Runanble() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this, select_activity_class.class);
startActivity(intent);
}
}, 4000); // 4 seconds
}
}
In addiction, you may add this for your second activity declaration in AndroidManifest: android:finishOnTaskLaunch="true"
never stall the UI thread. The UI thread is responsible for keeping your app feeling responsive.
But this is an fast and alternative solution for your problem.
public class MyActivity extends Activity {
private Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler.postDelayed(new Runnable() {
public void run() {
doStuff();
}
}, 5000);
}
private void doStuff() {
Intent intent = new Intent(MainActivity.this, select_activity_class.class);
startActivity(intent);
}
}
Then 5 seconds after the intent must start.
But i recommend async task
1)Sleeping 500 only sleeps for .5 seconds. So it would blink quickly anyway
2)Sleeping doesn't allow the thread to get back to the looper, so it freezes your UI. This means it won't update and draw anyway. Use a timer instead. Or posting a message to a handler would be acceptable here.
The problem is you're only sleeping for 500 milliseconds (half of one second), so it makes sense that it happens seemingly-immediately. You're also going to want to remove the OnGlobalLayoutListener after it's called. Here's an example of an approach that should work for you:
final Handler handler = new Handler(); // Create a Handler on the main Thread
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
#Override
public void onGlobalLayout(){
removeOnGlobalLayoutListener(vto, this);
handler.postDelayed(new Runnable(){
public void run(){
Intent intent = new Intent(MainActivity.this, select_activity_class.class);
startActivity(intent);
}
}, 4000); //Post back to the main Thread after 4000 mils (4 seconds)
}
});
#SuppressLint("NewApi")
public static void removeOnGlobalLayoutListener(View v, ViewTreeObserver.OnGlobalLayoutListener listener){
if (Build.VERSION.SDK_INT < 16) v.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
else v.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
}
Proper and short solution
Make a handler and give them a delay to call back itself:
final Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 1s
}
}, 1000);
Remember that 1 sec = 1000 milliseconds
Adjust time with that formula.
Happy Coding.
I have a problem, I make a simple application to show you my problem.
I want that setContentView executes and displays the .xml BEFORE the Sleep is executed. I thought everything will be execute in order?
Is there anyone how can say me why it doesn't do that?
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// do something
}
Thanks a lot!
EDIT:
Here is the real OnCreate, seems to be a bigger problem.
Everything with the sleep worked fine, but with the Connect method there are problems.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectBluetooth();
}
In the ConnectBluetooth() method, I just create a new Socket and try a connection.
With a ned thread or a handler it doesn't seems to work, what should I do then? Use something like an asynctask?
Thanks a lot in common!
The layout isn't displayed until after the creation process has finished, after onResume() is called. However there is no callback for when the layout is displayed, but you can use a Handler and Runnable to do this.
Create a couple field variables:
Handler handler = new Handler();
Runnable delay = new Runnable() {
#Override
public void run() {
// Do something
}
};
And onCreate() call:
handler.postDelayed(delay, 10000);
When you call sleep, you are pausing the UI thread. This will prevent onCreate from returning, which will prevent the framework from completing initialization of your activity, including displaying your view hierarchy.
You should never pause the UI thread like that. If you want to do something after 10 seconds, you can start a separate thread that will do it at the right time:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread() {
#Override
public void run() {
try {
Thread.sleep(10000);
doSomething();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
A cleaner approach would be to use a Handler:
Handler mHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
doSomething();
}
}, 10000);
}
I have a button in one page and when I click on that button I
am able to go another activity through Intent(), but onbuttonclick()
in which activity I am going in that activity data in spinner
coming from server means on button click
I load that data on spinner from server.so it takes times for moving my button click activity
to other activity so I want to show progress bar when my button is clicked
and untill data is not coming from server...how to achieve this..and I want to show progress bar
on buttonclick page means on my first activity when I click the button.
My code of of on button click is given below.
cuurentloc.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Intent i = new Intent(MainMenu.this, currentlocmap.class);
startActivity(i);
}
});
Actually I know asynchronous task but using this I will be able to show progress bar on 2nd activity, I want to show it on my first activity until data is not loaded in second activity, so I want progree bar above the button on first activity, and when data is loaded on second activity it moves to second.
You need to use AsyncTask as the way I am guiding here.
Create Async Task in first activity. On button click event call that AsyncTask. In background do loading data from server. and onPostExecute start second activity
cuurentloc.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
new ProgressTask(MyClassName.class).execute(null);
}
});
Async Task
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
List<Message> titles;
private ListActivity activity;
//private List<Message> messages;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
Intent i = new Intent(MainMenu.this, currentlocmap.class);
startActivity(i);
}
protected Boolean doInBackground(final String... args) {
try{
//load data from server
} catch (Exception e){
Log.e("tag", "error", e);
return false;
}
}
}
}
Thanks
Deepak
have a look at this code
package com.exercise.AndroidBackgroundThread;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class AndroidBackgroundThread extends Activity {
Thread backgroundThread;
TextView myText;
boolean myTextOn = true;
boolean running = false;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
if (myTextOn){
myTextOn = false;
myText.setVisibility(View.GONE);
}
else{
myTextOn = true;
myText.setVisibility(View.VISIBLE);
}
}
};
void setRunning(boolean b){
running = b;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myText = (TextView)findViewById(R.id.mytext);
Toast.makeText(this, "onCreate()", Toast.LENGTH_LONG).show();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Toast.makeText(this, "onStart()", Toast.LENGTH_LONG).show();
backgroundThread = new Thread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
while(running){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.sendMessage(handler.obtainMessage());
}
}
});
setRunning(true);
backgroundThread.start();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
boolean retry = true;
setRunning(false);
while(retry){
try {
backgroundThread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Toast.makeText(this, "onStop()", Toast.LENGTH_LONG).show();
}
}
and for more detail look at this guide http://tech-aamir.blogspot.in/2012/06/how-to-make-progress-bar-when.html
Best of luck
aamirkhan i.
To build on the first answer, since you are familiar with AsyncTask. You can have the AsyncTask perform the work to retrieve whatever data you'll need in your first activity. And during that process, you display your progress bar. Once the AsyncTask completes, you remove the progress bar, put your data in a bundle (by calling putExtras), and send it off with your intent to start the 2nd Activity.
You can use the ProgressBar or ProgressDialog in the currentlocmap class.
Use AsyncTask class for that and when the data is fetched, set the layout using setContentView() and dismiss the ProgressDialog.
Refer to these links:
Fetch data from server and refresh UI when data is fetched?
How to start and finish progressBar dynamically in android
Am I doing it right?
I have a Splash screen (just an image), and onCreate() I start the main activity after running a heavy function:
SPLASH_DISPLAY_LENGHT=2500;
new Handler().postDelayed(new Runnable(){
public void run() {
LONG_OPERATING_FUNCTION();
Intent mainIntent = new Intent(this, MainActivity.class);
Splash.this.startActivity(mainIntent);
Splash.this.finish();
}
}, SPLASH_DISPLAY_LENGHT);
I think I have a memory leak, and I'm trying to find it.
I don't think the Splash really is finishing.
LONG_OPERATING_FUNCTION() should not be done on the main application thread, as you have it here.
Ideally, you do not use a splash screen, but rather only enable selected features of MainActivity while do your LONG_OPERATING_FUNCTION() in an AsyncTask or something.
If somebody is pointing a gun at your head and forcing you to implement a splash screen lest it be your brains that get, er, splashed, I would do this:
Eliminate your Handler and postDelayed() call
Replace that with an AsyncTask
In doInBackground() of AsyncTask, do your LONG_OPERATING_FUNCTION()
If, when LONG_OPERATING_FUNCTION() is done, SPLASH_DISPLAY_LENGHT [sic] time has not elapsed, use SystemClock.sleep() to sleep for the remaining time (or not)
In onPostExecute(), start MainActivity and call finish()
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
openingSound = MediaPlayer.create(Splash.this, R.raw.applause);
openingSound.start();
setContentView(R.layout.firstanimal);
Thread timer = new Thread(){
public void run(){
try{
sleep(5000);
} catch (InterruptedException e){
e.printStackTrace();
}finally{
Intent openingSplash = new Intent("com.softech.LearnAnimal1.STARTINGPOINT");
startActivity(openingSplash);
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
openingSound.release();
finish();
}
This is a complete java code in this u'll have openingSound with 5 seconds break and then u it'll move on your menu or second activity but remeber one thing u also have to put activity with intent filters in your manifest :)
Enjoy :)
Intent intent = new Intent(getApplicationContext(), AActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(intent);
通过使用getApplicationContext()的context就不会内存溢出;
public class RunnableActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("RunnableActivity onCreate");
setContentView(R.layout.activity_main);
mHandler.postDelayed(mRunnable, 3000);
}
#Override
protected void onResume() {
super.onResume();
System.out.println("RunnableActivity onResume");
}
#Override
protected void onPause() {
super.onPause();
System.out.println("RunnableActivity onPause");
}
#Override
protected void onDestroy() {
super.onDestroy();
System.out.println("RunnableActivity onDestroy");
}
private Handler mHandler = new Handler(Looper.getMainLooper());
private Runnable mRunnable = new Runnable() {
private WeakReference<Activity> weak = new WeakReference<Activity>(RunnableActivity.this);
#Override
public void run() {
Activity a = weak.get();
if (a != null) {
Intent intent = new Intent(a.getApplicationContext(), AActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
a.getApplicationContext().startActivity(intent);
a.finish();
}
}
};}