0

I am currently working on an Android App which informs the number of screen unlocks he/she has done over a day. This example can be seen on stock android devices with API Level P or higher in the feature named Digital Wellbeing. I would like to know how does it work.

Anuj Kumar
  • 1,092
  • 1
  • 12
  • 26

2 Answers2

1

You can use Event stats to get unlock count. Try the following code snippet

  void getdailyUsageStatistics(long start_time, long end_time){
    int unlockcount=0;
    
    UsageEvents.Event currentEvent;
    
    UsageStatsManager mUsageStatsManager = (UsageStatsManager)
            getApplicationContext().getSystemService(Context.USAGE_STATS_SERVICE);

    if (mUsageStatsManager != null) {
 
        UsageEvents usageEvents = mUsageStatsManager.queryEvents(start_time, end_time);


        while (usageEvents.hasNextEvent()) {
            currentEvent = new UsageEvents.Event();
            usageEvents.getNextEvent(currentEvent);


            if (currentEvent.getEventType() == UsageEvents.Event.KEYGUARD_HIDDEN)
            {
              ++unlockcount;
            }
        }

    } else {
        Toast.makeText(getApplicationContext(), "Sorry...", Toast.LENGTH_SHORT).show();
    }
    Log.e("UNLOCK COUNT",unlockcount+" ");
}
Kishore K
  • 11
  • 2
0

You can add reciever like this in your Activity :

private LockScreenStateReceiver mLockScreenStateReceiver;
int count = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mLockScreenStateReceiver = new LockScreenStateReceiver();
    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_USER_PRESENT);

    registerReceiver(mLockScreenStateReceiver, filter);
}

public class LockScreenStateReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            // screen is turn off
            //("Screen locked");
        } else {
            //Handle resuming events if user is present/screen is unlocked
            count++;
            textView.setText(""+count);
            //("Screen unlocked");
        }
    }
}

@Override
public void onDestroy() {
    unregisterReceiver(mLockScreenStateReceiver);
    super.onDestroy();
}
NehaK
  • 2,639
  • 1
  • 15
  • 31
  • Store the count in SharedPreferences instead of a variable inside the class. – Mohammed Bakr Sikal Apr 10 '17 at 10:21
  • or may be instead of receiving the broadcasts in the activity i'd prefer using a service, which will be better. and putting return START_STICKY will make sure the service is restarted if killed by the OS. – Simo Apr 10 '17 at 10:37