Android Question How to implement App session timeout

quansofts

Member
Hi All,
I'm developing a business app, for security reason I need to request user to re-logon after 10 minutes continuously inactive. Thanks in advance for any help

Quan
 

Andrew (Digitwell)

Well-Known Member
Licensed User
Longtime User
Depending on whether you are using Android or iOS.

The iOS solution is here: https://www.b4x.com/android/forum/t...fter-period-of-inactivity.133562/#post-844326

for Android, add the following code to your Main activity (assuming B4xPages of course)

B4X:
private Sub Session_timeout(b As Boolean)
    Log("user timedout at @ "& DateTime.Time(DateTime.Now))
    
    ' Do whatever you need to handle the time out, e.g.
    B4xpages.MainPage.UserTimeout
    
End Sub
private Sub session_restart(b As Boolean)
' This event is unecessary, but shows you that the system is working
    Log("User did something @ "& DateTime.Time(DateTime.Now))
    
End Sub

#if java
import android.os.Handler;

@Override
public void onUserInteraction() {
    super.onUserInteraction();
// This is where you set the duration of the timeout - 10 - 10 minutes
    delayedIdle(10);
}

Handler _idleHandler = new Handler();
Runnable _idleRunnable = new Runnable() {
    @Override
     public void run() {
          processBA.raiseEventFromUI(this,"session_timeout",true);
    }
};

private void delayedIdle(int delayMinutes) {
    _idleHandler.removeCallbacks(_idleRunnable);
    _idleHandler.postDelayed(_idleRunnable, (delayMinutes * 60 * 1000));
    processBA.raiseEventFromUI(this,"session_restart",true);
    
}
#end if

also in B4xMainPage I have

B4X:
public Sub UserTimeout
' Do what you need to do on timeout, e.g. request user logs in again
End Sub

Private Sub B4xPage_Background
' Use this to force a timeout if the app moves to the background
    UserTimeout
End Sub
 
Upvote 0

quansofts

Member
Thanks Andrew, I will try this approach. Before see your code I implement the following
  • In Stater service
    • Declare a global variable named gTicks to hold the latest DateTime Ticks
    • Declare a timer to check for timeout
      B4X:
      If DateUtils.PeriodBetween(gTicks,DateTime.Now).Minutes>10 Then ShowLogin()
  • In every activity I captured the onUserInteraction event to store latest DateTime Ticks to gTicks
  • B4X:
    Public Sub User_Interaction   
        Starter.gTicks=DateTime.Now
    End Sub
 
Upvote 0
Top