B4J Question Auto shutdown app after idle

le_toubib

Active Member
Licensed User
Longtime User
Hi all
I'm trying to exit application when the user is not using it for a set time.
I tried to reset a timer on mouse move .. but the app crash ...
Is there a better way?
 

Daestrum

Expert
Licensed User
Longtime User
Small example uses javaobject lib

B4X:
Sub Process_Globals
    Private fx As JFX
    Private MainForm As Form
    Dim t As Timer
    Dim cnt As Int = 0
    Dim lastevent As Long = 0
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.SetFormStyle("UNIFIED")
    MainForm.Show
    MainForm.RootPane.RequestFocus
    t.Initialize("t",1000) ' use timer to check every second
    t.Enabled = True
    lastevent = DateTime.Now
    ' add listen to rootpane to monitor all controls on form
    asJO(Me).RunMethod("listen",Array(MainForm.RootPane))   
End Sub
Sub t_Tick
    Log(cnt)
    Dim ttime As Long = DateTime.Now
    If (ttime - lastevent) > 10000 Then  ' do something after 10 seconds of idle
        Log("close app")
        t.Enabled  = False
    Else
        Log("last event was "& (ttime - lastevent)& "ms ago") ' optional for debugging
        cnt = (ttime - lastevent)/1000
    End If
End Sub
Sub asJO(o As JavaObject) As JavaObject
    Return o
End Sub
#if java
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Node;

public static void listen(Node n){
    n.addEventFilter(Event.ANY, 
                    new EventHandler() {
                    @Override
                        public void handle(Event e) {
                        _lastevent = System.currentTimeMillis(); // _lastevent is lastevent in the b4j globals.
                        };
                    });
}
#end if

The java adds an eventfilter to the node, in this case the rootpane, this listens for any event.
When an event is triggered, it resets the 'lastevent' to the current time.
The timer routine just checks if the last event was over 10 seconds (in this example), if it is, it just prints a message "close app".
The cnt is there to see the time increment by seconds in the timer routine.
 
Upvote 0
Top