问题
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.
回答1:
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();
}
来源:https://stackoverflow.com/questions/43316878/how-can-i-count-the-number-of-screen-unlocks-by-a-user-in-android