问题
My app uses the TelephonyManager.ACTION_PHONE_STATE_CHANGED
for some actions. But I want a different action while the phone rang when the user was present (screen was on) and different action when the user was not present (screen was off). I tried the isScreenOn()
method just in the beginning of onReceive
(because when screen is off and there is incoming call, the screen stays off for a short while). No luck however - sometimes it works, sometimes not. The broadcast is asynchronous with the screen state...
public void onReceive(Context context, Intent intent) {
pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
Boolean screenOn = pm.isScreenOn();
Log.w(TAG, "Screen on is " + screenOn.toString());
How could I change my code to truly determine if the phone was sleeping when the call arrived?
回答1:
Ok, I got the answer which satisfies me:
public void onReceive(Context context, Intent intent) {
KeyguardManager kg = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
Boolean screenBlocked = !kg.inKeyguardRestrictedInputMode();
Log.w(TAG, "Screen lock is " + screenBlocked.toString());
Such solution gives information if the screen is locked. And, in my case, it is enough - when screen is locked during the incoming call - it means that there was no user.
来源:https://stackoverflow.com/questions/6837916/how-to-distinguish-the-screen-on-off-status-while-incoming-call