How to Detect User Inactivity in Android? - GeeksforGeeks

11 Aug, 2021
It is important to detect user inactivity in applications that display or contain private credentials, such as social apps, banking apps, wallet apps, etc. In such applications, there is a login session that authenticates log-in credentials. Once the session starts, the user can perform desired actions. However, if the screen is unused for a long time, it is necessary for the application to start displaying alerts or log the user out of the current session, user inactivity being the grounds for logging out. So, there must have been a timer or counter running in the background, that counted the user inactivity for some specified time.
So, through this article, we will show you how you could detect user inactivity by knowing when the user last touched the screen and instantly starting a counter for a specific time.
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Change the background of the layout to a darker color. We changed the background to black as we wanted to show touch impressions on the screen.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="@color/black"    tools:context=".MainActivity"></RelativeLayout>
Step 3: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.os.Handlerimport android.os.Looperimport android.view.MotionEventimport android.widget.Buttonimport android.widget.EditTextimport android.widget.Toast  class MainActivity : AppCompatActivity() {      // Declaring handler, runnable and time in milli seconds    private lateinit var mHandler: Handler    private lateinit var mRunnable: Runnable    private var mTime: Long = 2000      override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)          // Initializing the handler and the runnable        mHandler = Handler(Looper.getMainLooper())        mRunnable = Runnable {            Toast.makeText(applicationContext, "User inactive for ${mTime/1000} secs!", Toast.LENGTH_SHORT).show()        }          // Start the handler        startHandler()    }      // When the screen is touched or motion is detected    override fun onTouchEvent(event: MotionEvent?): Boolean {          // Removes the handler callbacks (if any)        stopHandler()          // Runs the handler (for the specified time)        // If any touch or motion is detected before         // the specified time, this override function is again called        startHandler()          return super.onTouchEvent(event)    }      // start handler function    private fun startHandler(){        mHandler.postDelayed(mRunnable, mTime)    }      // stop handler function    private fun stopHandler(){        mHandler.removeCallbacks(mRunnable)    }}
Output:
You can see that if the screen is untouched for 2 seconds, the application displays a message regarding user inactivity.
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Android Listview in Java with Example
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
Kotlin Setters and Getters