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();
}
}
};}
Related
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.
I have splash activity and 1 thread. Thread starts timer and after some time main activity will start.
Unlike on other apps I don't want to disable backPressed button in Splash Activity. I want when backpressed is pressed to cancel thread and finish activity. But I can't get it to work.
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.starter);
Thread Logo = new Thread() {
public void run() {
try {
sleep(1 * 1500);
Intent i = new Intent(getBaseContext(),
MainActivity.class);
startActivity(i);
finish();
} catch (Exception exception) {
}
}
};
Logo.start();
}
...
#Override
public void onBackPressed() {
Thread.currentThread().interrupt();
super.onBackPressed();
this.finish();
}
}
But this doesn't stop thread, it only finish activity and thread keeps running in background(and ofc starts activity)
Make Thread Logo Object Globally and do Logo.interrupt();
You should stop the thread that you already Started before. and also as #TmKVU answer's Thread.currentThread(); return main UI/Main Thread but you have to Stop your Logo Thread.
Try this If you wish to stop the thread if Back button is pressed by the user:
#Override
public void onBackPressed()
{
// First check if the thread isAlive(). To avoid NullPointerException
if(Logo.isAlive())
{
Logo.interrupt();
}
super.onBackPressed();
}
Do like this:
private Thread thread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
thread = new Thread(new Runnable() {
#Override
public void run() {
try {
// your logic
SplashActivity.this.finish();
} catch (InterruptedException e) {
finish();
}
}
});
thread.start();
}
#Override
public void onBackPressed() {
thread.interrupt();
super.onBackPressed();
}
It will work as it works in my all apps. Because when you inturrept thread then InterruptedException will be called. At that time finish your activity.
Thread.currentThread() will refer to you Main thread, since it is the currently active Thread.
You should make a field from your thread, so you can access it in your onBackPressed()method. You can then call logo.interrupt()
Use a Handler and Runnable. Instead of the inner new Runnable, create it outside as an object then pass it as a parameter to the handler. When you press back, call this method handler.removeCallbacks(runnable); to cancel the execution. Make sure to keep the variables in a global scope so you can access them anywhere.
handler = new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
startActivity(new Intent(SplashScreenActivity.this, MainActivity.class));
finish();
}
}, SPLASH_SCREEN_TIMEOUT);
Try this code, it may help you.
private Thread Logo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.starter);
logo = new Thread() {
public void run() {
try {
if(!isInterrupted()){
sleep(1 * 1500);
Intent i = new Intent(getBaseContext(),
MainActivity.class);
startActivity(i);
finish();
}
} catch (Exception exception) {
}
}
};
Logo.start();
}
#Override
protected void onStop() {
super.onStop();
System.out.println("On Stop");
logo.interrupt();
}
...
#Override
public void onBackPressed() {
logo.interrupt();
super.onBackPressed();
}
}
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'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
I made a splash image to show at the start of my activity..
The image show perfectly.But the problem is when i call this
public class SplashImageActivity extends Activity {
protected boolean active = true;
protected int splashTime = 5000; // time to display the splash screen in ms
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
// thread for displaying the SplashScreen
Thread splashTread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
while(active && (waited < splashTime)) {
sleep(100);
if(active) {
waited += 100;
}
}
} catch(InterruptedException e) {
// do nothing
} finally {
startActivity(new Intent(SplashImageActivity.this,Myapps.class));
finish();
//startActivity(new Intent("com.splash.com.MyApps"));
//startActivity( new Intent(getApplicationContext(), Myapps.class));
}
}
};
splashTread.start();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
active = false;
}
return true;
}
}
go for next activity the stop() does not work. And it does not go to this activity. I add all activity in manifest. The stop() shows in code like this
what's the problem?
No need to call stop() and call finish() after starting activity
finally
{
startActivity(new Intent(currentclass.this,nextActivity.class);
finish();
}
I use thread to show the Splash screen, and it works for me:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
mSplashThread = new Thread(){
#Override
public void run(){
try {
synchronized(this){
wait(4000);
}
}catch(InterruptedException ex){
}
finish();
Intent i=new Intent(getApplicationContext(),NextActivity.class);
startActivity(i);
interrupt();
}
};
mSplashThread.start();
}
Please try below code..
public class Splashscreen extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Thread t2 = new Thread() {
public void run() {
try {
sleep(2000);
startActivity( new Intent(getApplicationContext(), Exercise.class));
finish();
} catch (Exception e) {
e.printStackTrace();
}
}
};
t2.start();
}
}
No need to call stop() just call finish() after starting activity
finally {
startActivity(new Intent(currentclass.this,nextActivity.class);
finish();
}
You can also use handler an postdelayed() to make a splash screen like below
public class SplashScreenActivity extends Activity{
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
final Runnable runnable = new Runnable() {
#Override
public void run() {
Intent intent=new Intent(SplashScreenActivity.this, nextActivity.class);
startActivity(intent);
finish();
}
};
handler = new Handler();
handler.postDelayed(runnable, 5000);
}
}
You will show your splash screen for 5 seconds and then move to next Activity
first thing it is not onStop of Activity so looks you are calling stop function of thread which is Deprecated that's why you are getting the strike line so use other way to stop the thread of use better way to implement the splash ........
as looks you try some thing like this link