Android change Activity after few seconds - android

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.

Related

how to stop open activity while splash screen killed

I have splash screen .
once i open my application the splash screen will appears after completion of splash screen passed intent to HomeActivity.
but when i kill this app while splash screen running after some time HomeScreen will automatically open , but i want to kill the app.
but the HomeScreen should not show when i killed the app .
public class SplashAnimation extends Activity {
ImageView imageViewSplash;
TextView txtAppName;
RelativeLayout relativeLayout;
Thread SplashThread;
MediaPlayer mySong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_view);
mySong=MediaPlayer.create(SplashAnimation.this,R.raw.monn);
mySong.start();
imageViewSplash = (ImageView) findViewById(R.id.imageViewSplash);
txtAppName = (TextView) findViewById(R.id.txtAppName);
relativeLayout = (RelativeLayout) findViewById(R.id.relative);
startAnimations();
}
private void startAnimations() {
Animation rotate = AnimationUtils.loadAnimation(this, R.anim.translate);
Animation translate = AnimationUtils.loadAnimation(this, R.anim.translate);
rotate.reset();
translate.reset();
relativeLayout.clearAnimation();
imageViewSplash.startAnimation(rotate);
txtAppName.startAnimation(translate);
SplashThread = new Thread() {
#Override
public void run() {
super.run();
int waited = 0;
while (waited < 3500) {
try {
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
waited += 100;
}
SplashAnimation.this.finish();
Intent intent = new Intent(SplashAnimation.this, LibraryView.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
mySong.stop();
}
};
SplashThread.start();
}
#Override
protected void onStop() {
SplashAnimation.this.finish();
finish();
mySong.stop();
super.onStop();
}
#Override
protected void onDestroy() {
finish();
mySong.stop();
super.onDestroy();
}
}
Once you have called SplashThread.start() it will do its job as long as it can do. I would recommend to use a Handler instead, tho you can remotely cancel the task, the Handler runs:
//init and declare the handler instance
private Handler delayHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (delayHandler == null) {
delayHandler = new Handler();
}
//your code
}
//define the task the handler should do
private void startAnimations() {
//replace the code beginning at 'Thread SplashThread = new Thread()' with the following
delayhandler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashAnimation.this, LibraryView.class);
//these flags will prevent to 'redo' the transition by hitting the back button, that also makes calling 'finish()' obsolete
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
//instead of the while loop just execute the runnable after below given amount of milliseconds
}, 3500)
//to remotely cancel the runnable, if the app, respectively the Activity gets killed override 'onDestroy()'
#Override
public void onDestroy() {
super.onDestroy();
mySong.stop();
//calling 'finish()' is obsolete, tho 'finish()' calls 'onDestroy()' itself
//tell the handler to quit its job
delayHandler.removeCallbacksAndMessages(null);
}
Call in onStop() method
SplashThread.interrupt()
You can use Timer instead of instantiating the Thread class.
Refer the code below to start the Activity after 4 seconds. Use this in onCreate() of SplashActivity.
timer = new Timer().schedule(new TimerTask() {
#Override
public void run() {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
}, 4000);
In your onPause() method use:
timer.cancel()
This will terminate the timer and disregards any currently scheduled tasks.

Cyclic restart my application in 3h intervals. How to?

I need to write an application to open the browser (sample site www.onet.pl), which will restart every 3 hours. The commotion of restart was displayed. I managed to create such a layout, but I can not handle the cyclical restart. Please help where to add and what code? One class is enough.
This is my code:
public class MainActivity extends AppCompatActivity {
private Object v;
Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start(null);
m_Runnable.run();
}
public void start(View v) {
Uri uri = Uri.parse("http://onet.pl");
Intent i = new Intent(Intent.ACTION_VIEW, uri);
startActivity(i);
this.mHandler = new Handler();
}
private final Runnable m_Runnable = new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "odświezenie strony", Toast.LENGTH_SHORT).show();
MainActivity.this.mHandler.postDelayed(m_Runnable, 15000);
}
};
}
You could use a timer instead of Runnable.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "odświezenie strony", Toast.LENGTH_SHORT).show();
//and put the rest of your code here
}
},0,5000);

how to check if an application is killed during an animation in android

i have to make an application in which it starts with an animation and if we click the back button then it should return back to application manager.But what i have made in it if u click back button during that animation then it goes to application manager but after a second or two the first page(the one after this animation comes up).
Can anyone help??
This is the animation..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.load);
im = (ImageView) findViewById(R.id.load_icon);
rotate = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.load_page);
rotate.setInterpolator(new LinearInterpolator());
im.startAnimation(rotate);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent nextPageIntent = new Intent(getApplicationContext(),
P1.class);
startActivity(nextPageIntent);
}
}, 3000);
}
The first page opens because you have added
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent nextPageIntent = new Intent(getApplicationContext(),
P1.class);
startActivity(nextPageIntent);
}
}, 3000);
This launches the activity.For knowing if the animation has stopped use AnimationListener. More details here about animation listener
Android, How to set animation listener for view group?
You just added animation to one image view thats all, you do not doing anything with animation. The problem is, you started one thread to start activity P1 after 3 seconds. That thread only starting P1 activity. Try this and try to avoid killProcess(),
public class LauncherActivity extends Activity {
private Handler mHandler;
private Runnable mRunnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
mHandler = new Handler();
mRunnable = new Runnable() {
#Override
public void run() {
Intent nextPageIntent = new Intent(getApplicationContext(),
XmlParserActivity.class);
startActivity(nextPageIntent);
}
};
mHandler.postDelayed(mRunnable, 3000);
}
/* #Override
public void onBackPressed() {
super.onBackPressed();
mHandler.removeCallbacks(mRunnable);
}*/
#Override
protected void onDestroy() {
super.onDestroy();
mHandler.removeCallbacks(mRunnable);
}
}
public void onBackPressed() {
android.os.Process.killProcess(android.os.Process.myPid());
}
This is the answer

Switch from One Activity to Another Activity After a Time Interval

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);
}

Splash screen: using handler

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();
}
}
};}

Categories

Resources