How would you identify the user isn't using the mobile for 30 mins?
Using Jiro to see it's in horizontal position?
Is there any Android built-in flag for that?
Listen for ACTION_SCREEN_OFF
to start timer, and clear timer only if you receive ACTION_USER_PRESENT
, so you won't accidentally clear your timer when the screen is turned on by some apps.
For above method you can include the following when you start your timer. This way you take the auto-lock delay into account when the screen is off.
Settings.Secure.getLong(getContentResolver(), "lock_screen_lock_after_timeout", 5000);
Alternatively, you can use KeyguardManager
to check if the lock screen is enabled every 1ms or so after screen is off.
In general, the idea is lock screen --> idle; no lock screen --> not idle
You should try working with events based on the display and when it has been enabled the last time.
Register a Broadcast Receiver for ACTION_SCREEN_ON
, ACTION_SCREEN_OFF
and ACTION_USER_PRESENT
and save the timestamp properly.
Please note, that the Screen-Events could be also fired by applications like WhatsApp if they automatically enable the display to show a new message. Due to this fact should you rather stick to ACTION_USER_PRESENT.
Here is some code:
Android-Manifest.xml
<receiver android:name=".UserPresentBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
Broadcast Receiver
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class UserPresentBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent intent) {
/*Sent when the user is present after
* device wakes up (e.g when the keyguard is gone)
* */
if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){
}
}
}
Credits for the code go to Chathura Wijesinghe
Note: You will need a seperate thread (preferably a daemon-thread) to compare that timestamp with the current time.
You can check if the screen is turned off by calling isScreenOn method.
Note: This only can be used for 2.1 and above
Also you can also use Intent.ACTION_SCREEN_OFF to determine the status of your screen. Check this link for an example.
Reference: isScreenOn and this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With