Open an activity after a certain amount of time? - android

I would like to implement a SplashScreen in my app. I found the best and easiest way is to launch an activity that shows a layout with an image view at the launch of the app and then adding android:noHistory="true" attribute to the manifest.
Now, how do I set the splashscreen activity to launch the MainActivity class after a certain amount of time? Lets say 2 seconds?
This is my splashscreen activity
public class SplashActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashscreen);
}
}

use
handler.postDelayed(runnable, delayinmilliseconds(2000 in your case));
final Runnable runnable = new Runnable()
{
public void run()
{
//start the new activity here.
}
};

Here is a complete sample.
package com.test.splash;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
public class splash extends Activity {
private static final int STOPSPLASH = 0;
//time in milliseconds
private static final long SPLASHTIME = 3000;a
private ImageView splash;
//handler for splash screen
private Handler splashHandler = new Handler() {
/* (non-Javadoc)
* #see android.os.Handler#handleMessage(android.os.Message)
*/
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case STOPSPLASH:
//remove SplashScreen from view
splash.setVisibility(View.GONE);
break;
}
super.handleMessage(msg);
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
splash = (ImageView) findViewById(R.id.splashscreen);
Message msg = new Message();
msg.what = STOPSPLASH;
splashHandler.sendMessageDelayed(msg, SPLASHTIME);
}
}

public class TrackMyMoneyActivity extends Activity {
//member fields
private ProgressBar pbar = null;
private TextView counter_txt = null;
Thread splash_thread = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pbar = (ProgressBar) findViewById(R.id.splashpbar);
counter_txt = (TextView) findViewById(R.id.countertxt);
//define thread
splash_thread = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
int i = 0;
for( i=0;i<100;i++){
pbar.setProgress(i);
// counter_txt.setText(i+" %");
try {
splash_thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(i==100){
Intent intent = new Intent(getBaseContext(), LoginApp.class);
startActivity(intent);
}
}
});
splash_thread.start();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
I hope it will be solved your solution.

You can also use java.util.Timer in this way:
new Timer().schedule(new TimerTask(){
public void run() {
startActivity(new Intent(SplashActivity.this, MainActivity.class));
}
}, 2000 /*amount of time in milliseconds before execution*/ );

public class Splashscreen extends Activity
{
private static final int SPLASH_TIME = 10 * 1000;// 3 seconds
Button logo;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splashscreen);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
try {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent intent = new Intent(Splashscreen.this,MainActivity.class);
startActivity(intent);
Splashscreen.this.finish();
//overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
}, SPLASH_TIME);
new Handler().postDelayed(new Runnable() {
public void run() {
}
}, SPLASH_TIME);
} catch(Exception e){}
// METHOD 1
/****** Create Thread that will sleep for 5 seconds *************/
Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 5 seconds
sleep(50*1000);
// After 5 seconds redirect to another intent
Intent i=new Intent(getBaseContext(),MainActivity.class);
startActivity(i);
//Remove activity
finish();
} catch (Exception e) {
}
}
};
background.start();
}

Related

change button image onClick android

I have a button and two images, i want the default image for the button to be btn1.jpg and when the button is clicked, the image should immediately change to btn2.jpg and after 3 seconds, it should again revert back to btn1.jpg. please tell me how do i achieve this?
package com.example.btn;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
private View ButtonName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void yolo(View v) {
switch (v.getId()) {
case R.id.buttonName:
ButtonName.setBackgroundResource(R.drawable.btn2);
//Disable click on Button
ButtonName.setEnabled(false);
try {
Thread.sleep(3000);
}
catch (Exception e) {
e.printStackTrace();
}
ButtonName.setBackground(getResources().getDrawable(R.drawable.btn1));
break;
case default:
ButtonName.setBackgroundResource(R.drawable.btn1);
}
}
}
You must change the button background image in the OnClick method to btn2.jpg. After that, you must start a timer to count down 3 seconds and, after that, change again the button image to btn1.jpg
private final int interval = 3000;
private Handler handler = new Handler();
private Runnable runnable
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
btn.setBackground(getResources().getDrawable(R.drawable.btn2))
//Start runnable after 3 seconds
handler.postDelayed(runnable, interval);
}
});
runnable = new Runnable(){
public void run() {
btn.setBackground(getResources().getDrawable(R.drawable.btn1))
}
};
finally figured it out myself!
Set background for button in xml
use this code:
package com.example.btn;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
public class MainActivity extends Activity {
Handler mHandler; // global instance
Runnable your_runnable; // global instance
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void yolo(final View view) {
if (view == view) {
view.setBackgroundResource(R.drawable.btn1);
mHandler = new Handler();
your_runnable = new Runnable() {
#Override
public void run() {
view.setBackgroundResource(R.drawable.btn2);
}
};
mHandler.postDelayed(your_runnable, 3000L);// 3sec timer
}
}
}
This may work for you!!
public class MainActivity extends Activity {
Button button;
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.yourbuttonid);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
button.setBackgroundResource(getresources().getDrawable(R.drawable.btn1));
handler=new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
button.setBackgroundResource(getresources().getDrawable(R.drawable.btn2));
}
}, 3000);
}
});
}
Ok so first, you have a mistake here :
ButtonName.setBackgroundResource(getresources().getDrawable(R.drawable.btn2));
And after, add a clickListener on your button :
private Thread t = new Thread(new Runnable {
#Override
public void run() {
ButtonName.setBackgroundResource(getresources().getDrawable(R.drawable.btn2));
//Disable click on Button
ButtonName.setEnabled(false);
try {
Thread.sleep(3000);
}
catch (Exception e) {
e.printstacktrace();
}
ButtonName.setBackgroundResource(getresources().getDrawable(R.drawable.btn1));
}
});
ButtonName.setOnClickListener (new OnClickListener (
#Override
public void onClick(View v) {
t.start();
}
));
I think it is what you want

I want to use handler instead of timer for my splash activity

currently I'm programming an Android application and I'm using timer for my splash. instead of using timer I want to use handle but I can't integrate that to my code:
package com.tesbih;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class Splash extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread timer = new Thread(){
public void run(){
try{
sleep(5000);
}catch(InterruptedException e){
e .printStackTrace();
}finally{
Intent openStartingPoint = new Intent ("com.tesbih.TESBIHMAINACTIVITY");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
}
public class Splash extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
final Intent openStartingPoint = new Intent(this, TESBIHMAINACTIVITY);
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
startActivity(openStartingPoint);
finish();
}
}, 5000);
}
}

How do I set a time limit to my splash screen? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am coding in Eclipse for an Android App. I have developed a splash screen which I need to display for 5 seconds before my app starts. How to do it?
Thread timer=new Thread()
{
public void run() {
try {
sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
Intent i=new Intent(SplashScreen.this,MainActivity.class);
finish();
startActivity(i);
}
}
};
timer.start();
Use the Async Class to perform the sleep operation in the doinbackground function and in the post function do the rest of the task
public class SplashScreenActivity extends Activity {
private final int SPLASH_DISPLAY_LENGHT = 5000;
#Override
public void onCreate(Bundle icicle)
{ super.onCreate(icicle);
try{
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splashscreen);
}catch(Exception e){
e.printStackTrace();
}
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute(){
// show your progress dialog
}
#Override
protected Void doInBackground(Void... voids){
try {
Thread.sleep(SPLASH_DISPLAY_LENGHT);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void params)
{
startActivity(new Intent(SplashScreenActivity.this, HomeActivity.class));
finish();
}
}
}
use like that
public class SplaceScreenActivity extends Activity {
private static final int SPLASH_DISPLAY_TIME = 2500;
// SplashScreen Splash;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splacescreen);
new Handler().postDelayed(new Runnable() {
public void run() {
Intent intent = new Intent();
intent.setClass(SplaceScreenActivity.this,
HomeScreenActivity.class);
SplaceScreenActivity.this.startActivity(intent);
SplaceScreenActivity.this.finish();
}
}, SPLASH_DISPLAY_TIME);
}
}
Try below code:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash);
final int welcomeScreenDisplay = 2000;
/** create a thread to show splash up to splash time */
Thread welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {
super.run();
/**
* use while to get the splash time. Use sleep() to increase
* the wait variable for every 100L.
*/
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
} finally {
startActivity(new Intent(MainActivity.this,
HomeActivity.class));
finish();
}
}
};
welcomeThread.start();
}
}
Handler handler = new Handler();
Runnable run = new Runnable() {
public void run() {
// TODO Auto-generated method stub
startActivity(new Intent(SplaceActivity.this, New.class));
overridePendingTransition(0, 0);
finish();
}
};
handler.postDelayed(run, 3000);
Use AsyncTask or thread for this purpose.
http://www.androidhive.info/2013/07/how-to-implement-android-splash-screen-2/
hope it helps
I use Timer:
Timer timer = new Timer();
timer.schedule(new TimerTask(){
#Override
public void run() {
// TODO Auto-generated method stub
Intent home_page = new Intent(Splash.class,HomePage.class);
startActivity(home_page);
finish();
}}, 5000);
you can use Sleep method like this in your Splash Activity onCreate method:
Thread timer1 = new Thread(){
#Override
public void run(){
try{
sleep(4000);
}
catch (InterruptedException e){
e.printStackTrace();
}
finally{
Intent intent = new Intent(SplashActivity.this, NextActivity.class);
startActivity(intent);
}
}
};
timer1.start();
this take 4 sec to load NextActivity.
Add these few lines of code in your splashActivity and it will start your second activity after 5seconds.
new Handler().postDelayed(new Runnable(){
public void run() {
Intent mainIntent = new Intent(splashScreen.this,MainActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
splashScreen.this.startActivity(mainIntent);
splashScreen.this.finish();
}
}, 5000);
PostDelayed Causes the Runnable to be added to the message queue, to
be run after the specified amount of time elapses. The runnable will
be run on the thread to which this handler is attached.
Use handler
public class SplashActivity extends Activity {
int secondsDelayed = 5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash);
Message msg = new Message();
msg.what = 0;
mHandler.sendMessage(msg);
}
Handler mHandler = new Handler()
{
public void handleMessage(android.os.Message msg) {
switch(msg.what)
{
case 1:
{
startActivity(new Intent(SplashActivity.this, MainActivity.class));
finish();
}
break;
case 0:
{
Message ms = new Message();
ms.what = 1;
mHandler.sendMessageDelayed(ms, secondsDelayed * 1000);
}
break;
}
};
};
protected void onDestroy() {
super.onDestroy();
mHandler.removeMessages(1);
};
}
Note:Donot make Splash screen for 5 sec user will get irritated make it for 2sec

how to display another activity

How to display another activity?
I want to display one activity which has one Image View splash displaying an image. I want to display that just for 5 seconds then move on to another activity.splash is displaying in emulator but another activity menu is not displaying.
Here is my code:
com.basic.android;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class androidbasics extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
}
public void toCallActivity() {
TimerTask startNewActivity;
final Handler handler = new Handler();
final Timer timer = new Timer();
startNewActivity = new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
handler.post(new Runnable() {
public void run() {
try {
timer.cancel();
startActivity(new Intent(androidbasics.this,menu.class));
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(startNewActivity, 0,5000);
}
}
You didn't call toCallActivity().So your new Activity is not coming in the front.Write like this.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
toCallActivity();
}
try this ....
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
BackgroundTask b = new BackgroundTask();
b.execute("Main");
}
/** Called when the activity is first created. */
class BackgroundTask extends AsyncTask<String , Void, Void>
{
#Override
protected void onPreExecute()
{
setContentView(R.layout.splash);
}
#Override
protected Void doInBackground(String... params)
{
// TODO Auto-generated method stub
int pause=5000;
int interval =1000;
int counter=0;
while(counter<pause)
{
try
{
Thread.sleep(interval);
counter+=interval;
}
catch(Exception e)
{
System.out.println(e);
}
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
startActivity( new Intent(androidbasics.this,menu.class));
androidbasics.this.finish();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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)
{
} finally {
finish();
startActivity(new Intent(firstactivity.class,secondActivity.class));
stop();
}
}
};
splashTread.start();
}

Let the splash activity wait a process

My app have a splash activity
It must display at least 5 seconds
But in this activity I have another thread to sync data from internet
Sync process may take more than 5 seconds or less than 5 second.
If less than 5 seconds, the Handler should wait until fifth second
If more then 5 seconds, the Handler should wait until process complete
How to make the Handler wait another thread?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
syncFromInternet(); // another thread may over 5 seconds
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent;
intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
}, 5000);
}
You have to make just simple logic Like
When handler completes then check for completion of syncFromInternet method, if it completed open main Activity
When syncFromInternet completes then check for completion of handler, if it completed open main Activity.
Above explanation in code:
boolean isHandlerCompleted = false, isAsyncCompleted = false;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
isHandlerCompleted = true;
if (isHandlerCompleted && isAsyncCompleted) {
openMainActivity();// both thread completed
}
}
}, 5000);
// in your async task add this condition when it completes its task
isAsyncCompleted = true;
if (isHandlerCompleted && isAsyncCompleted) {
openMainActivity();// both thread completed
} // till this line
// make this function to open main activity
openMainActivity() {
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
You can use an AsyncTask instance and measure the time for syncing with the remote server. If the time is greater than 5 minutes, start the new activity, otherwise - wait till the 5th second:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() {
private static final long FIVE_SECONDS = 5 * 1000;
private volatile Date mStartTime;
#Override
protected void onPreExecute() {
mStartTime = new Date();
}
#Override
protected Void doInBackground(Void... params) {
// Do the syncing here
syncFromInternet();
Date now = new Date();
long execTime = now.getTime() - mStartTime.getTime();
if(execTime < FIVE_SECONDS) {
Thread.sleep(FIVE_SECONDS - execTime);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Intent intent = new Intent(...);
startActivity(intent);
finish();
}
};
asyncTask.execute(null, null);
}
You can use this code :
package com.example.untitled;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.File;
import java.io.IOException;
public class MyActivity extends Activity {
private volatile boolean isAvailable = false;
private volatile boolean isOver = false;
private Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
if (isOver) {
Log.e("messageHandler","isOver");
transitToNewActivity();
}else {
Log.e("messageHandler","isOver false");
}
break;
}
}
};
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
syncFromInternet(); // another thread may over 5 seconds
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
isOver = true;
Log.e("mainHandler", "Main handler expired");
if (isAvailable) {
transitToNewActivity();
Log.e("mainHandler", "isAvailable");
}else {
Log.e("mainHandler","isAvailable false");
}
}
}, 50000);
public void transitToNewActivity() {
Log.e("transitToNewActivity","Activity transited");
Intent intent;
intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
public void syncFromInternet() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(80000);
isAvailable = true;
messageHandler.sendEmptyMessage(0);
Log.e("syncFromInternet", "internet data synced");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
and please modify it according to your requirement.
you should implement AsyncTask so that this will wait untill your syncFromInternet() is completed.
private class BackgroundSplashTask extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
// show progressbar
}
#Override
protected Object doInBackground(Object[] params) {
try {
syncFromInternet(); // sync in background
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
// dismiss progressbar
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent); // go to SecondActivity after syncFromInternet is completed
finish();
}
}
Call your handler inside syncFromInternet() after execution of thread.

Categories

Resources