Android - 屏幕锁定后检测应用程序恢复

时间:2014-07-21 12:48:23

标签: android android-activity

如何判断当前Activity的OnResume是否已触发,因为应用程序在屏幕解锁后恢复,而不仅仅是因为它暂时在后台?

2 个答案:

答案 0 :(得分:2)

您可以使用BroadcastReceiver收听屏幕解锁Intent

实施此BroadcastReceiver

public class UnlockBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent intent) {
        final String action = intent.getAction();
        if(Intent.ACTION_USER_PRESENT.equals(action)){
            // Screen unlocked (Keyguard is gone)
        }
    }
}

然后您可以在BroadcastReceiveronResume()中注册和取消注册onPause(),如下所示:

private final UnlockBroadcastReceiver unlockReceiver = new UnlockBroadcastReceiver();

@Override
protected void onResume() {
    super.onResume();

    IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
    registerReceiver(unlockReceiver, filter);
}

@Override
protected void onPause() {
    super.onPause();

    unregisterReceiver(unlockReceiver);
}

您也可以在清单中注册,但 NOT 大部分时间都可以使用。

<receiver android:name="path.to.UnlockBroadcastReceiver">
    <intent-filter android:enabled="true" android:exported="false">
            <action android:name="android.intent.action.USER_PRESENT" />
        </intent-filter>
</receiver>

答案 1 :(得分:0)

在活动或服务中:

try {
                  IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);

                  filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_USER_PRESENT);

                  BroadcastReceiver mReceiver = new receiverScreen();

                  registerReceiver(mReceiver, filter);
             } catch (Exception e) {

             }

接收器代码,系统会通知您屏幕开/关是否发生:

public class receiverScreen extends BroadcastReceiver {

     @Override
     public void onReceive(Context context, Intent intent) {

         if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)){

         }
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){

         }
if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)){

         }
     }

    }

如果它被锁定,您只需写入SharedPreference即可。然后在您的活动的onResume()上,您可以检查sharedPreference的值

在manifest.xml中

   <receiver android:name="receiverScreen">
        <intent-filter> 
            <action android:name="android.intent.action.SCREEN_ON" />
            <action android:name="android.intent.action.SCREEN_OFF" />
<action android:name="android.Intent.action.USER_PRESENT" />
        </intent-filter> 
    </receiver>