I have many activities in my application(eg A->B->C->D)...A is a login activity...i have a countdowntimer that i am using for a session timeout.. What i want to do is....logout the user.. i.e put him back to activity A if there is no user interaction in the activities B,C,D... i have extended my application class and instantiated my timer in that...But in this activity i cant clear the stacktop of the previous activities i.e the line
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Throws a exception..Any idea how will i solve this problem...Here is my code...
public class MyApp extends Application {
MyCount count;
#Override
public void onCreate() {
// reinitialize variable
count = new MyCount(5000, 1000);
}
public void startcounter() {
count.start();
}
public void cancelcounter() {
count.cancel();
}
public class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
try{
Intent my = new Intent(getApplicationContext(), Login.class);
my.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(my);
Toast.makeText(getApplicationContext(), "Finsihed",
Toast.LENGTH_LONG).show();
}
catch(Exception e )
{
Toast.makeText(getApplicationContext(), String.valueOf(e),
Toast.LENGTH_LONG).show();
}
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
// Toast.makeText(getApplicationContext(), String.valueOf(millisUntilFinished/1000),
// Toast.LENGTH_LONG).show();
}
}
}
Related
I'm doing an app which will use CountDownTimer
I would like to use 1 countdowntimer for 2 count downs.
If the time finishes, then a new time starts immediately, and so on.
For now I have something like this:
cdt = new CounDownTimer(time,1000) {
public void onTick(…) {
//code
}
public void onFinish() {
//and here I'm thinking to add a new time, but it doesn't work
}
};
How to do that? Or maybe is there other easier option to solve that problem?
Thanks for help!
Somewhere in your class newMyCountdownTimer(time, interval).start();
private class MyCountdownTimer extends CountDownTimer
{
public MyCountdownTimer(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish()
{
if (somecondition is satisfied) // be carefull otherwise the countdown keeps running
{
// newTime and newInterval are variables in the outer class
new MyCountdownTimer(newTime, newInterval).start();
}
}
#Override
public void onTick(long millisUntilFinished)
{
// TODO Auto-generated method stub
}
}
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 am working on android applications. In my project I have 3 pages.
The first page consists of 1 button.
The second page is consists of the timer code.
The third page consists of again a button.
Now my requirement is when I click on the first page button the third page should open and the timer in second page should pause. Again when I click on the third page button
the second page timer should restart the time where it is stopped and should open the first page.
I am struggling to achieve this task.Guide me through it, Suggest what should have been done to do that.
Page1.java
rowTextView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(v.getContext(),Page3.class);
startActivity(myIntent);
finish();
}
});
Page2.java
public class TimeractivitybestActivity extends Activity {
EditText e1;
MyCount counter;
Long s1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
e1 = (EditText) findViewById(R.id.editText1);
counter = new MyCount(15000, 1000);
counter.start();
}
public void method(View v) {
switch (v.getId()) {
case R.id.button1:
counter.cancel();
break;
case R.id.button2:
counter = new MyCount(s1, 1000);
counter.start();
}
}
public class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
e1.setText("DONE");
}
#Override
public void onTick(long millisUntilFinished) {
s1 = millisUntilFinished;
e1.setText("left:" + millisUntilFinished / 1000);
}
}
}
Page3.java
public void gobacktopage1(View v)
{
Intent myIntent = new Intent(v.getContext(),Page1.class);
startActivity(myIntent);
finish();
}
You can always store the timeLeft which is s1 and use it again like this, Read the comments too
1) While calling timer,check if you have any stored time
Page1.java
rowTextView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
long time = sp.getLong("time", 0); // get saved time of times
Intent myIntent = new Intent(v.getContext(),Page3.class);
myIntent.putExtra("time", time); // send it to page2
startActivity(myIntent);
finish();
}
});
2) Use the time to start time if it's not 0.
Page2.java
public class TimeractivitybestActivity extends Activity {
EditText e1;
MyCount counter;
Long s1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
long time = this.getIntent().getLongExtra("time", 0); // get
// saved
// time
time = (time != 0) ? time : 1500;
e1 = (EditText) findViewById(R.id.editText1);
counter = new MyCount(time, 1000); // start with saved time
counter.start();
}
public void method(View v) {
switch (v.getId()) {
case R.id.button1:
counter.cancel();
break;
case R.id.button2:
counter = new MyCount(s1, 1000);
counter.start();
}
}
public class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
e1.setText("DONE");
}
#Override
public void onTick(long millisUntilFinished) {
s1 = millisUntilFinished;
e1.setText("left:" + millisUntilFinished / 1000);
}
}
public void onPause() {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
Editor et = sp.edit();
et.putLong("time", s1); // save time SharedPreference in onPause
et.commit();
}
}
3) no change in page 3, I suppose.
Page3.java
public void gobacktopage1(View v)
{
Intent myIntent = new Intent(v.getContext(),Page1.class);
startActivity(myIntent);
finish();
}
public class TimerActivity extends Activity{
EditText e1;
MyCount counter;
Long s1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
e1=(EditText)findViewById(R.id.editText1);
counter= new MyCount(5000,1000);
counter.start();
}
public void asdf(View v)
{
switch(v.getId())
{
case R.id.button1: counter.cancel();
break;
case R.id.button2: counter= new MyCount(s1,1000);
counter.start();
}
}
public class MyCount extends CountDownTimer
{
public MyCount(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
#Override public void onFinish()
{
e1.setText("DONE");
}
#Override public void onTick(long millisUntilFinished)
{
s1=millisUntilFinished;
e1.setText("left:"+millisUntilFinished/1000);
}
}
}
this is how it works...
MyCount counter;
Long s1;
counter= new MyCount(300000,1000);
counter.start();
public void asdf(View v){ <---- method for onclick of buttons pause and resuming timer
switch(v.getId()){
case R.id.button1:<-- for pause
counter.cancel();
break;
case R.id.button2:<--- for resume
counter= new MyCount(s1,1000);
counter.start();
}
}
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
mediaplayer.stop();
mediaplayer.release();
}
#Override
public void onTick(long millisUntilFinished) {
s1=millisUntilFinished;
}
}
case R.id.button1:<-- for pause
counter.cancel();
this the one which is used to pause the timer and start again...
and in ur case
public void gobacktopage1(View v)
{
Intent myIntent = new Intent(v.getContext(),Page1.class);
startActivity(myIntent);
finish();
}
write a method in that add counter.cancel(); in that method and call that method...
my application is question/answer application , the user ask for a question , then the server send question to a user, when user receives the question , a ShowQuestion button appears , when user click it , i want to start timer , because a user have to answer in just 36 Second
i build a textView in my xml like this
<TextView
android:id="#+id/tvRemaingTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"
/>
and in my Java activity i make this
TextView remaingTimer;
CountDownTimer timer;
private void initialize() {
remaingTimer=(TextView)findViewById(R.id.tvRemaingTime);
}
and when a user click ShowQuestion i make this
timer =new CountDownTimer(360000,100) {
public void onTick(long millisUntilFinished) {
remaingTimer.setText(millisUntilFinished+"");
}
public void onFinish() {
remaingTimer.setText("finish");
}
};
timer.start();
but it doesn't print anything, what am i doing wrong ?
NOTE
i am using AsyncTask to get question from server like this:
public class getQuestionFromServer extends
AsyncTask<String, Integer, String[]> {}
but i don't thing it effect on textView because the ShowQuestion button will not appear else a user have got a question from the server
you can use runOnUiThread for updateing TextView from Thread as:
TextView remaingTimer;
CountDownTimer timer;
private boolean mClockRunning=false;
private int millisUntilFinished=36;
private void initialize() {
remaingTimer=(TextView)findViewById(R.id.tvRemaingTime);
}
ShowQuestionbutn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mClockRunning==false)
{
mClockRunning=true;
millisUntilFinished=0;
myThread();
}
public void myThread(){
Thread th=new Thread(){
#Override
public void run(){
try
{
while(mClockRunning)
{
Thread.sleep(100L);// set time here for refresh time in textview
CountDownTimerActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if(mClockRunning)
{
if(millisUntilFinished<0)
{
mClockRunning=false;
millisUntilFinished=36;
}
else
{
millisUntilFinished--;
remaingTimer.setText(millisUntilFinished+"");//update textview here
}
}
};
}
}catch (InterruptedException e) {
// TODO: handle exception
}
}
};
th.start();
}
I'm trying to start a new activity "SMS.java", if I dont respond to my timer within 30secs. After 30secs, the new ativity should be started. Can anyone help me out??? The class Timer on line 5 extends a CountDownTimer..
Here's the code:
//TimerAct.java
public class TimerAct extends Activity
{
static TextView timeDisplay;
Timer t;
int length = 30000;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.time);
timeDisplay = (TextView) findViewById(R.id.timer);
timeDisplay.setText("Time left: " + length / 1000);
t = new Timer(length, 1000);
t.start();
View b1 = findViewById(R.id.abort);
b1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
t.cancel();
finish();
}
});
}
}
//Timer.java
public class Timer extends CountDownTimer
{
public Timer(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
public void onTick(long millisUntilFinished)
{
TimerAct.timeDisplay.setText("Time left: " + millisUntilFinished / 1000);
}
public void onFinish()
{
TimerAct.timeDisplay.setText("Time over!!!");
}
}
For a timer method, better you can use with threading. It will work.
This is the example for Show Timer in android using threads. It runs the thread every second. Change the time if you want.
Timer MyTimer=new Timer();
MyTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
TimerBtn=(Button) findViewById(R.id.Timer);
TimerBtn.setText(new Date().toString());
}
});
}
}, 0, 1000);
What I do is call a method from the Activity on my CountDownTimer class, like this:
//Timer Class inside my Activity
public class Splash extends CountDownTimer{
public Splash(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
nextActivity(Login.class, true);
}
#Override
public void onTick(long millisUntilFinished) {}
}
//Method on my Activity Class
protected void nextActivity(Class<?> myClass, boolean finish) {
Intent myIntent = new Intent(this, myClass);
myIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(myIntent);
if(finish)
finish();
}