简体   繁体   中英

Is it possible to detect when the screen turns on by the user (Android)?

I found post from two year ago that somebody said that it can't be done. I also found that I can use ACTION_USER_PRESENT to detect when a user unlock the screen, but can I detect when the user turns on the screen (by any action)?

EDIT: I want to know when the user press any button or do anything else that can turn on the screen

The system will broadcast Intent.ACTION_SCREEN_ON which you can use to catch the event when the screen turns on.

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            // your code here

        }
    }
}

Note that you can't broadcast this event yourself.

I started writing this as a comment but it turned out too big.

I couldn't find anything either. You can't have a key listener on services and you apparently can't register a broadcast receiver for the power button, only for media buttons . Maybe you can do this on the broadcast receiver for the screen on and check which is the current activity)? Like this , for example:

ActivityManager am = (ActivityManager) this .getSystemService(ACTIVITY_SERVICE);
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
Log.d(WebServiceHelper.TAG, "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClassName()+"   Package Name :  "+ componentInfo.getPackageName());

If you can get detect that the activity with the focus is the lockscreen, you increase the chances of being the user who turned on his/her phone. Maybe an alternative method on the broadcast receiver is to detect if the phone is locked but I guess this will be usually the case no matter the current activity being displayed:

KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
boolean locked = km.inKeyguardRestrictedInputMode();

Hope this can help somehow. It's an interesting question.

Are you looking for this?

@Override
public void onConfigurationChanged (Configuration newConfig)

and put this in your manifest for each activity that you want orientation notification:

android:configChanges="orientation" >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM