I set a timer on AccountActivity.class to ensure that user does not press home button if not will start the countdown to logout the user or if the user locks his screen.
But now I am facing an issue because of the onPause method. When my user clicks on a button which invokes the getaccounttask() method and it will redirect my user to AccountInformationActivity.class, the onPause method is activated as well and the timer starts to countdown.
Is there any solution to prevent the onPause method from counting down or the timer to be cancelled on my AccountInformationActivity.class?
I tried to do the cancelling of timer before my intent starts but still does not work.
I have tried using handler as well but encountered the same problem, I am still trying to grasp how Android fully works, so your help or solution is deeply appreciated.
public class AccountActivity extends AppCompatActivity {
private Timer timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
}
private class getaccounttask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urlaccount)
{
StringBuilder result = new StringBuilder();
try
{
//My Codes
}
catch (Exception e)
{
e.printStackTrace();
}
return result.toString();
}
#Override
protected void onPostExecute(String result)
{
Intent intent = new Intent();
intent.setClass(getApplicationContext(), AccountInformationActivity.class);
startActivity(intent);
}
}
#Override
protected void onPause() {
super.onPause();
timer = new Timer();
Log.i("Main", "Invoking logout timer");
LogOutTimerTask logoutTimeTask = new LogOutTimerTask();
timer.schedule(logoutTimeTask, 300000); //auto logout in 5 minutes
}
#Override
protected void onResume() {
super.onResume();
if (timer != null) {
timer.cancel();
Log.i("Main", "cancel timer");
timer = null;
}
}
private class LogOutTimerTask extends TimerTask {
#Override
public void run() {
//redirect user to login screen
Intent i = new Intent(AccountActivity.this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
}
}
Well, the implementation architecture you choose could be improved. I shall come to that later. First apply this quick fix to fix your architecture.
Clearly you want to start a Timer when you go out of Activity using home screen. But user can also go out of Activity by using Intent to switch to AccountActivity. This you can track. So keep a boolean flag like shouldNavigate, initially it should be false. when onResume, it should be set to false, but when getcounttask goes to onPostExecute it should be set to true. So in onPause, if you are going out via getcounttask,shouldNavigate is going to be true and if is true, cancel your Timer else, start your Timer.
Code:
public class AccountActivity extends AppCompatActivity {
private Timer timer;
private volatile boolean shouldNavigate = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
}
private class getaccounttask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urlaccount)
{
StringBuilder result = new StringBuilder();
try
{
//My Codes
}
catch (Exception e)
{
e.printStackTrace();
}
return result.toString();
}
#Override
protected void onPostExecute(String result)
{
shouldNavigate = true;
Intent intent = new Intent();
intent.setClass(getApplicationContext(), AccountInformationActivity.class);
startActivity(intent);
}
}
#Override
protected void onPause() {
super.onPause();
if (!shouldNavigate){
timer = new Timer();
Log.i("Main", "Invoking logout timer");
LogOutTimerTask logoutTimeTask = new LogOutTimerTask();
timer.schedule(logoutTimeTask, 300000);
}else{
if (timer != null){
timer.cancel();
timer = null;
}
}
}
#Override
protected void onResume() {
super.onResume();
shouldNavigate = false;
if (timer != null) {
timer.cancel();
Log.i("Main", "cancel timer");
timer = null;
}
}
private class LogOutTimerTask extends TimerTask {
#Override
public void run() {
//redirect user to login screen
shouldNavigate = false;
Intent i = new Intent(AccountActivity.this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
}
}
Now a better approach could be keep a Service and a Singleton class.
The Singleton class would be
public Singleton{
private static Singleton instance = null;
private Singleton(){
activityMap = new HashMap<String, Activity>();
}
public static Singleton getInstance(){
if (instance == null) instance = new Singeton();
return instance;
}
public HashMap<String, Activity> activityMap;
}
Now each activity will have a Tag (like its name), so each activity when resumes will do
Singleton.getInstance().activityMap.put(tag, this);
and when goes to onPause will do
Singleton.getInstance().activityMap.remove(tag, this);
So when the service finds that size of Singleton.getInstance().activityMap is zero then clearly no activity is on foreground, so it starts a timer. when the timer expires check again if the count is still zero, if zero then perform your logout.
Make some modifications in onPause() and add this permission
<uses-permission android:name="android.permission.GET_TASKS" />
#Override
protected void onPause() {
if (isApplicationSentToBackground(this)) {
// Do what you want to do on detecting Home Key being Pressed
timer = new Timer();
Log.i("Main", "Invoking logout timer");
LogOutTimerTask logoutTimeTask = new LogOutTimerTask();
timer.schedule(logoutTimeTask, 300000); //auto logout in 5 minutes
Log.i("Main", "Invoking Home Key pressed");
}
super.onPause();
}
public boolean isApplicationSentToBackground(final Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}
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'm having some trouble with an AsyncTask subclass.
I have a main activity as below that displays a button and a number that counts up on the screen. Clicking the button launches an Edit activity where a number can be entered.
The number displayed on the Main activity should update with the timer which it does but the trouble I'm having is that I can't stop the timer. It should stop when entering the Edit activity and returning from it as well, as well as restart with the a new value too but it doesn't, the timer is always running with the first entered value, it never stops, even when I leave the program and return to the home screen.
I've looked at posts here such as Can't cancel Async task in android but they all just mention checking for isCancelled() which I'm doing. Can anyone see/explain why I can't stop this AsyncTask ?
public class MainActivity extends Activity {
#Override
UpdateTimer ut;
TextView tvn;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onResume() {
super.onResume();
tvn = (TextView) findViewById(R.id.numDisplay);
if(ut != null )//&& ut.getStatus() == AsyncTask.Status.RUNNING) {
ut.cancel(true);
ut.cancelled = true;
Log.d("-----M_r","called cancel: "+ut.isCancelled()+" "+cancelled);
}
if (updateRequired) {
ut = new UpdateTimer();
ut.execute(number);
updateRequired = false;
}
}
public void onEditButtonPressed(View caller) {
// kill any running timer
if(ut != null )
{
ut.cancel(true);
ut.cancelled = true;
}
// start the edit screen
Intent e_intent = new Intent(this, EditActivity.class);
startActivity(e_intent);
}
private void updateScreen(long number) {
// update screen with current values
tvn.setText("" + number);
}
private class UpdateTimer extends AsyncTask<Long, Long, Integer> {
long number;
public boolean cancelled;
#Override
protected Integer doInBackground(Long... params) {
number = params[0];
cancelled = false;
while(true) {
number += 1;
//sleep for 1 second
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// tell this AsyncTask to update the time on screen
publishProgress(number);
// check if timer needs to stop
if (isCancelled()) break;
if(cancelled) break;
}
return null;
}
protected void onProgressUpdate(Long... progress) {
Log.d("-----M_ut","updated: "+number+" "+this.isCancelled()+" "+cancelled);
updateScreen(progress[0]);
}
protected void onCancelled(Integer result) {
cancelled = true;
Log.d("-----M_ut","-- cancelled called: "+this.isCancelled());
}
}
protected void onStop()
{
super.onStop();
// kill any running timer
if(ut != null) {
ut.cancel(true);
}
}
}
Try this...
remove the variable..cancelled and change to this..
#Override
protected void onCancelled() {
super.onCancelled();
}
call the super.onCancelled instead..
And in the doInBackground check
if (isCancelled()) {
break;
}
Try calling from your activity ut.cancel(true);
Hope it works:)
private YourAsyncTask ut;
declare your asyncTask in your activity.
ut = new YourAsyncTask().execute();
instantiate it like this.
ut.cancel(true);
kill/cancel it like this.
How to use timer in android for auto logout after 15 minutes due to inactivity of user?
I am using bellow code for this in my loginActivity.java
public class BackgroundProcessingService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
timer = new CountDownTimer(5 *60 * 1000, 1000) {
public void onTick(long millisUntilFinished) {
//Some code
//inactivity = true;
timer.start();
Log.v("Timer::", "Started");
}
public void onFinish() {
//Logout
Intent intent = new Intent(LoginActivity.this,HomePageActivity.class);
startActivity(intent);
//inactivity = false;
timer.cancel();
Log.v("Timer::", "Stoped");
}
};
return null;
}
}
and onclick of login button I have called intent for service.
Intent intent1 = new Intent(getApplicationContext(),
AddEditDeleteActivity.class);
startService(intent1);
Please advice......
This type of error message is shown after 15 mins
Use CountDownTimer
CountDownTimer timer = new CountDownTimer(15 *60 * 1000, 1000) {
public void onTick(long millisUntilFinished) {
//Some code
}
public void onFinish() {
//Logout
}
};
When user has stopped any action use timer.start() and when user does the action do timer.cancel()
I am agree with Girish in above answer. Rash for your convenience i am sharing code with you.
public class LogoutService extends Service {
public static CountDownTimer timer;
#Override
public void onCreate(){
super.onCreate();
timer = new CountDownTimer(1 *60 * 1000, 1000) {
public void onTick(long millisUntilFinished) {
//Some code
Log.v(Constants.TAG, "Service Started");
}
public void onFinish() {
Log.v(Constants.TAG, "Call Logout by Service");
// Code for Logout
stopSelf();
}
};
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Add the following code in every activity.
#Override
protected void onResume() {
super.onResume();
LogoutService.timer.start();
}
#Override
protected void onStop() {
super.onStop();
LogoutService.timer.cancel();
}
First Create Application class.
public class App extends Application{
private static LogoutListener logoutListener = null;
private static Timer timer = null;
#Override
public void onCreate() {
super.onCreate();
}
public static void userSessionStart() {
if (timer != null) {
timer.cancel();
}
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if (logoutListener != null) {
logoutListener.onSessionLogout();
log.d("App", "Session Destroyed");
}
}
}, (1000 * 60 * 2) );
}
public static void resetSession() {
userSessionStart();
}
public static void registerSessionListener(LogoutListener listener) {
logoutListener = listener;
}
}
This App Class add into manifest
<application
android:name=".App"
android:allowBackup="false"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="#style/AppTheme">
<activity android:name=".view.activity.MainActivity"/>
</application>
Then Create BaseActivity Class that is use in whole applications
class BaseActivity extends AppCompatActivity implements LogoutListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
//setTheme(App.getApplicationTheme());
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
//Set Listener to receive events
App.registerSessionListener(this);
}
#Override
public void onUserInteraction() {
super.onUserInteraction();
//reset session when user interact
App.resetSession();
}
#Override
public void onSessionLogout() {
// Do You Task on session out
}
}
After that extend Base activity in another activity
public class MainActivity extends BaseActivity{
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
You can start a service and start a timer in it. Every 15 minutes, check if a flag, let's say inactivity flag is set to true. If it is, logout form the app.
Every time the user interacts with your app, set the inactivity flag to false.
you may need to create a BaseActivity class which all the other Activities in your app extend. in that class start your timer task (TimerTask()) in the onUserInteraction method:
override fun onUserInteraction() {
super.onUserInteraction()
onUserInteracted()
}
. The onUserInteracted class starts a TimerTaskService which will be an inner class for my case as below:
private fun onUserInteracted() {
timer?.schedule(TimerTaskService(), 10000)
}
The TimerTaskService class will be asfollows. Please note the run on UI thread in the case you want to display a DialogFragment for an action to be done before login the user out:
inner class TimerTaskService : TimerTask() {
override fun run() {
/**This will only run when application is in background
* it allows the application process to get high priority for the user to take action
* on the application auto Logout
* */
// val activityManager = applicationContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
// activityManager.moveTaskToFront(taskId, ActivityManager.MOVE_TASK_NO_USER_ACTION)
runOnUiThread {
displayFragment(AutoLogoutDialogFragment())
isSessionExpired = true
}
stopLoginTimer()
}
}
You will realise i have a stopTimer method which you have to call after the intended action has be envoked, this class just has timer?.cancel() and you may also need to include it in the onStop() method.
NB: this will run in 10 seconds because of the 10000ms
Use the build-in function called: onUserInteraction() like below:
#Override
public void onUserInteraction() {
super.onUserInteraction();
stopHandler(); //first stop the timer and then again start it
startHandler();
}
I hope this will help
I found it on github https://gist.github.com/dseerapu/b768728b3b4ccf282c7806a3745d0347
public class LogOutTimerUtil {
public interface LogOutListener {
void doLogout();
}
static Timer longTimer;
static final int LOGOUT_TIME = 600000; // delay in milliseconds i.e. 5 min = 300000 ms or use timeout argument
public static synchronized void startLogoutTimer(final Context context, final LogOutListener logOutListener) {
if (longTimer != null) {
longTimer.cancel();
longTimer = null;
}
if (longTimer == null) {
longTimer = new Timer();
longTimer.schedule(new TimerTask() {
public void run() {
cancel();
longTimer = null;
try {
boolean foreGround = new ForegroundCheckTask().execute(context).get();
if (foreGround) {
logOutListener.doLogout();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}, LOGOUT_TIME);
}
}
public static synchronized void stopLogoutTimer() {
if (longTimer != null) {
longTimer.cancel();
longTimer = null;
}
}
static class ForegroundCheckTask extends AsyncTask < Context, Void, Boolean > {
#Override
protected Boolean doInBackground(Context...params) {
final Context context = params[0].getApplicationContext();
return isAppOnForeground(context);
}
private boolean isAppOnForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List < ActivityManager.RunningAppProcessInfo > appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = context.getPackageName();
for (ActivityManager.RunningAppProcessInfo appProcess: appProcesses) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}
}
}
Use above code in Activity as below :
public class MainActivity extends AppCompatActivity implements LogOutTimerUtil.LogOutListener
{
#Override
protected void onStart() {
super.onStart();
LogOutTimerUtil.startLogoutTimer(this, this);
Log.e(TAG, "OnStart () &&& Starting timer");
}
#Override
public void onUserInteraction() {
super.onUserInteraction();
LogOutTimerUtil.startLogoutTimer(this, this);
Log.e(TAG, "User interacting with screen");
}
#Override
protected void onPause() {
super.onPause();
Log.e(TAG, "onPause()");
}
#Override
protected void onResume() {
super.onResume();
Log.e(TAG, "onResume()");
}
/**
* Performing idle time logout
*/
#Override
public void doLogout() {
// write your stuff here
}
}
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
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.