android.app.KeyguardManager Java Examples

The following examples show how to use android.app.KeyguardManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VolumePanel.java    From Noyze with Apache License 2.0 7 votes vote down vote up
/** Start an activity. Returns true if successful. */
@SuppressWarnings("deprecation")
protected boolean startActivity(Intent intent) {
    Context context = getContext();
    if (null == context || null == intent) return false;

    // Disable the Keyguard if necessary.
    KeyguardManager mKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
    if (mKM.isKeyguardLocked() && !mKM.isKeyguardSecure()) {
        mKeyguardLock = mKM.newKeyguardLock(getName());
        mKeyguardLock.disableKeyguard();
    }

    try {
        // Necessary because we're in a background Service!
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
            return true;
        }
    } catch (ActivityNotFoundException anfe) {
        LOGE("VolumePanel", "Error launching Intent: " + intent.toString(), anfe);
    } catch (SecurityException se) {
        LOGE("VolumePanel", "Error launching Intent: " + intent.toString(), se);
        Toast.makeText(context, R.string.permission_error, Toast.LENGTH_SHORT).show();
    }

    return false;
}
 
Example #2
Source File: SpoonInstrumentationTestRunner.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Override
public void onStart() {
    runOnMainSync(() -> {
        final Application app = (Application) getTargetContext().getApplicationContext();
        final String simpleName = SpoonInstrumentationTestRunner.class.getSimpleName();

        // Unlock the device so that the tests can input keystrokes.
        ((KeyguardManager) app.getSystemService(Context.KEYGUARD_SERVICE))
                .newKeyguardLock(simpleName)
                .disableKeyguard();

        // Wake up the screen.
        ((PowerManager) app.getSystemService(Context.POWER_SERVICE))
                .newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager
                        .ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, simpleName)
                .acquire();
    });

    super.onStart();
}
 
Example #3
Source File: MainActivity.java    From android-ConfirmCredential with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
    Button purchaseButton = (Button) findViewById(R.id.purchase_button);
    if (!mKeyguardManager.isKeyguardSecure()) {
        // Show a message that the user hasn't set up a lock screen.
        Toast.makeText(this,
                "Secure lock screen hasn't set up.\n"
                        + "Go to 'Settings -> Security -> Screenlock' to set up a lock screen",
                Toast.LENGTH_LONG).show();
        purchaseButton.setEnabled(false);
        return;
    }
    createKey();
    findViewById(R.id.purchase_button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Test to encrypt something. It might fail if the timeout expired (30s).
            tryEncrypt();
        }
    });
}
 
Example #4
Source File: OverlayServiceCommon.java    From heads-up with GNU General Public License v3.0 6 votes vote down vote up
private void dismissKeyguard() {
    if (Build.VERSION.SDK_INT >= 16) {
        if (!preferences.getBoolean("dismiss_keyguard", false)) return;

        KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
        if (keyguardManager.isKeyguardLocked()) {
            Mlog.d(logTag, "attempt exit");
            Intent intent = new Intent();
            intent.setClass(getApplicationContext(), KeyguardRelock.class);
            intent.setAction(Intent.ACTION_SCREEN_ON);
            startService(intent);
        }
    }
}
 
Example #5
Source File: ShadowsocksRunnerActivity.java    From Maying with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
    boolean locked = km.inKeyguardRestrictedInputMode();
    if (locked) {
        IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (Intent.ACTION_USER_PRESENT.equals(intent.getAction())) {
                    mServiceBoundContext.attachService();
                }
            }
        };
        registerReceiver(receiver, filter);
    } else {
        mServiceBoundContext.attachService();
    }
    finish();
}
 
Example #6
Source File: VideoActivity.java    From BambooPlayer with Apache License 2.0 6 votes vote down vote up
@Override
public void onResume() {
	super.onResume();
	if (!mCreated)
		return;
	if (isInitialized()) {
		KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
		if (!keyguardManager.inKeyguardRestrictedInputMode()) {
			startPlayer();
		}
	} else {
		if (mCloseComplete) {
			reOpen();
		}
	}
}
 
Example #7
Source File: AndroidSecurityBridge.java    From CrossMobile with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
    public boolean supportsFingerprint(StrongReference<NSError> error) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            KeyguardManager keyguardManager
                    = (KeyguardManager) MainActivity.current().getSystemService(KEYGUARD_SERVICE);
            fingerprintManager
                    = (FingerprintManager) MainActivity.current().getSystemService(FINGERPRINT_SERVICE);

            if (!fingerprintManager.isHardwareDetected()) {
                error.set(new NSError(LAErrorDomain, LAError.TouchIDNotAvailable, getUserInfo("Device has no fingerprint sensor")));
                return false;
            }

            if (!fingerprintManager.hasEnrolledFingerprints()) {
                error.set(new NSError(LAErrorDomain, LAError.TouchIDNotEnrolled, getUserInfo("No identities are enrolled")));
                return false;
            }

            if (!keyguardManager.isKeyguardSecure()) {
                error.set(new NSError(LAErrorDomain, LAError.PasscodeNotSet, getUserInfo("A passcode isn’t set on the device.")));
//                return false;
            }
            return true;
        }
        return false;
    }
 
Example #8
Source File: JWebSocketClientService.java    From WebSocketClient with Apache License 2.0 6 votes vote down vote up
/**
 * 检查锁屏状态,如果锁屏先点亮屏幕
 *
 * @param content
 */
private void checkLockAndShowNotification(String content) {
    //管理锁屏的一个服务
    KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
    if (km.inKeyguardRestrictedInputMode()) {//锁屏
        //获取电源管理器对象
        PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        if (!pm.isScreenOn()) {
            @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |
                    PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
            wl.acquire();  //点亮屏幕
            wl.release();  //任务结束后释放
        }
        sendNotification(content);
    } else {
        sendNotification(content);
    }
}
 
Example #9
Source File: SecureCredentialsManagerTest.java    From Auth0.Android with MIT License 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Test
@Config(sdk = 21)
public void shouldNotRequireAuthenticationIfAPI21AndLockScreenDisabled() {
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 21);
    Activity activity = spy(Robolectric.buildActivity(Activity.class).create().start().resume().get());

    //Set LockScreen as Disabled
    KeyguardManager kService = mock(KeyguardManager.class);
    when(activity.getSystemService(Context.KEYGUARD_SERVICE)).thenReturn(kService);
    when(kService.isKeyguardSecure()).thenReturn(false);
    when(kService.createConfirmDeviceCredentialIntent("title", "description")).thenReturn(null);

    boolean willAskAuthentication = manager.requireAuthentication(activity, 123, "title", "description");

    assertThat(willAskAuthentication, is(false));
}
 
Example #10
Source File: ShadowsocksNotification.java    From ShadowsocksRR with Apache License 2.0 6 votes vote down vote up
public ShadowsocksNotification(Service service, String profileName, boolean visible) {
    this.service = service;
    this.profileName = profileName;
    this.visible = visible;

    keyGuard = (KeyguardManager) service.getSystemService(Context.KEYGUARD_SERVICE);
    nm = (NotificationManager) service.getSystemService(Context.NOTIFICATION_SERVICE);
    pm = (PowerManager) service.getSystemService(Context.POWER_SERVICE);

    // init notification builder
    initNotificationBuilder();
    style = new NotificationCompat.BigTextStyle(builder);

    // init with update action
    initWithUpdateAction();

    // register lock receiver
    registerLockReceiver(service, visible);
}
 
Example #11
Source File: DeviceAvailability.java    From react-native-keychain with MIT License 6 votes vote down vote up
/** Check is permissions granted for biometric things. */
public static boolean isPermissionsGranted(@NonNull final Context context) {
  // before api23 no permissions for biometric, no hardware == no permissions
  if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
    return false;
  }

  final KeyguardManager km =
    (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
  if( !km.isKeyguardSecure() ) return false;

  // api28+
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
    return context.checkSelfPermission(Manifest.permission.USE_BIOMETRIC) == PERMISSION_GRANTED;
  }

  // before api28
  return context.checkSelfPermission(Manifest.permission.USE_FINGERPRINT) == PERMISSION_GRANTED;
}
 
Example #12
Source File: ButlerService.java    From test-butler with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    Log.d(TAG, "ButlerService starting up...");

    try {
        shellBinder = new ShellButlerServiceBinder(this);
        butlerApi = shellBinder.bind(5, TimeUnit.SECONDS);

        locks = new CommonDeviceLocks();
        locks.acquire(this);

        // CommonDeviceLocks doesn't enable the Keyguard Lock on Q due to compatibility issues.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
            keyguardLock = keyguardManager.newKeyguardLock("ButlerKeyguardLock");
            keyguardLock.disableKeyguard();
        }
        accessibilityServiceWaiter = new AccessibilityServiceWaiter();

        Log.d(TAG, "ButlerService startup completed...");
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}
 
Example #13
Source File: KS.java    From trust-wallet-android-source with GNU General Public License v3.0 6 votes vote down vote up
public static void showAuthenticationScreen(Context context, int requestCode) {
	// Create the Confirm Credentials screen. You can customize the title and description. Or
	// we will provide a generic one for you if you leave it null
	Log.e(TAG, "showAuthenticationScreen: ");
	if (context instanceof Activity) {
		Activity app = (Activity) context;
		KeyguardManager mKeyguardManager = (KeyguardManager) app.getSystemService(Context.KEYGUARD_SERVICE);
		if (mKeyguardManager == null) {
			return;
		}
		Intent intent = mKeyguardManager
				.createConfirmDeviceCredentialIntent(
						context.getString(R.string.unlock_screen_title_android),
						context.getString(R.string.unlock_screen_prompt_android));
		if (intent != null) {
			app.startActivityForResult(intent, requestCode);
		} else {
			Log.e(TAG, "showAuthenticationScreen: failed to create intent for auth");
			app.finish();
		}
	} else {
		Log.e(TAG, "showAuthenticationScreen: context is not activity!");
	}
}
 
Example #14
Source File: SmoothieApplicationModule.java    From toothpick with Apache License 2.0 6 votes vote down vote up
private void bindSystemServices(Application application) {
  bindSystemService(application, LocationManager.class, LOCATION_SERVICE);
  bindSystemService(application, WindowManager.class, WINDOW_SERVICE);
  bindSystemService(application, ActivityManager.class, ACTIVITY_SERVICE);
  bindSystemService(application, PowerManager.class, POWER_SERVICE);
  bindSystemService(application, AlarmManager.class, ALARM_SERVICE);
  bindSystemService(application, NotificationManager.class, NOTIFICATION_SERVICE);
  bindSystemService(application, KeyguardManager.class, KEYGUARD_SERVICE);
  bindSystemService(application, Vibrator.class, VIBRATOR_SERVICE);
  bindSystemService(application, ConnectivityManager.class, CONNECTIVITY_SERVICE);
  bindSystemService(application, WifiManager.class, WIFI_SERVICE);
  bindSystemService(application, InputMethodManager.class, INPUT_METHOD_SERVICE);
  bindSystemService(application, SearchManager.class, SEARCH_SERVICE);
  bindSystemService(application, SensorManager.class, SENSOR_SERVICE);
  bindSystemService(application, TelephonyManager.class, TELEPHONY_SERVICE);
  bindSystemService(application, AudioManager.class, AUDIO_SERVICE);
  bindSystemService(application, DownloadManager.class, DOWNLOAD_SERVICE);
  bindSystemService(application, ClipboardManager.class, CLIPBOARD_SERVICE);
}
 
Example #15
Source File: WXClient.java    From Anti-recall with GNU Affero General Public License v3.0 6 votes vote down vote up
public void wakeUpAndUnlock() {
    // TODO: 24/05/2018 解锁密码
    // 获取电源管理器对象
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    if (pm == null)
        return;
    boolean screenOn = pm.isScreenOn();
    if (!screenOn) {
        // 获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
        PowerManager.WakeLock wl = pm.newWakeLock(
                PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
        wl.acquire(1000); // 点亮屏幕
        wl.release(); // 释放
    }
    // 屏幕解锁
    KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(KEYGUARD_SERVICE);
    KeyguardManager.KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("unLock");
    // 屏幕锁定
    keyguardLock.reenableKeyguard();
    keyguardLock.disableKeyguard(); // 解锁
}
 
Example #16
Source File: SecureCredentialsManager.java    From Auth0.Android with MIT License 6 votes vote down vote up
/**
 * Require the user to authenticate using the configured LockScreen before accessing the credentials.
 * This feature is disabled by default and will only work if the device is running on Android version 21 or up and if the user
 * has configured a secure LockScreen (PIN, Pattern, Password or Fingerprint).
 * <p>
 * The activity passed as first argument here must override the {@link Activity#onActivityResult(int, int, Intent)} method and
 * call {@link SecureCredentialsManager#checkAuthenticationResult(int, int)} with the received parameters.
 *
 * @param activity    a valid activity context. Will be used in the authentication request to launch a LockScreen intent.
 * @param requestCode the request code to use in the authentication request. Must be a value between 1 and 255.
 * @param title       the text to use as title in the authentication screen. Passing null will result in using the OS's default value.
 * @param description the text to use as description in the authentication screen. On some Android versions it might not be shown. Passing null will result in using the OS's default value.
 * @return whether this device supports requiring authentication or not. This result can be ignored safely.
 */
public boolean requireAuthentication(@NonNull Activity activity, @IntRange(from = 1, to = 255) int requestCode, @Nullable String title, @Nullable String description) {
    if (requestCode < 1 || requestCode > 255) {
        throw new IllegalArgumentException("Request code must be a value between 1 and 255.");
    }
    KeyguardManager kManager = (KeyguardManager) activity.getSystemService(Context.KEYGUARD_SERVICE);
    this.authIntent = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? kManager.createConfirmDeviceCredentialIntent(title, description) : null;
    this.authenticateBeforeDecrypt = ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && kManager.isDeviceSecure())
            || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && kManager.isKeyguardSecure()))
            && authIntent != null;
    if (authenticateBeforeDecrypt) {
        this.activity = activity;
        this.authenticationRequestCode = requestCode;
    }
    return authenticateBeforeDecrypt;
}
 
Example #17
Source File: MainActivity.java    From programming with GNU General Public License v3.0 6 votes vote down vote up
private void inicializarSeguranca() {

        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {

            Toast.makeText(this,
                    getString(R.string.fingerprint_error_no_permission),
                    Toast.LENGTH_LONG).show();

            return;
        }

        keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
        fingerprintManager = (FingerprintManager) getSystemService(FINGERPRINT_SERVICE);

        keystoreManager = new AndroidKeystoreManager(KEY_NAME);
        keystoreManager.generateKey();

        if (keystoreManager.cipherInit()) {
            cryptoObject = new FingerprintManager.CryptoObject(keystoreManager.getCipher());
        }
    }
 
Example #18
Source File: PickerFragmentTest.java    From boxing with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Throwable {
    // espresso need the screen on
    final Activity activity = mRule.getActivity();
    mRule.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            KeyguardManager km = (KeyguardManager) activity.getSystemService(Context.KEYGUARD_SERVICE);
            KeyguardManager.KeyguardLock lock = km.newKeyguardLock(Context.KEYGUARD_SERVICE);
            lock.disableKeyguard();

            //turn the screen on
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                    | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                    | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
        }
    });
}
 
Example #19
Source File: SecureCredentialsManagerTest.java    From Auth0.Android with MIT License 5 votes vote down vote up
@Test
public void shouldNotGetCredentialsWhenCredentialsHaveExpired() {
    Date credentialsExpiresAt = new Date(CredentialsMock.CURRENT_TIME_MS + 123456L * 1000);
    Date storedExpiresAt = new Date(CredentialsMock.CURRENT_TIME_MS - 60L * 1000);
    insertTestCredentials(true, true, false, credentialsExpiresAt);
    when(storage.retrieveLong("com.auth0.credentials_expires_at")).thenReturn(storedExpiresAt.getTime());

    //Require authentication
    Activity activity = spy(Robolectric.buildActivity(Activity.class).create().start().resume().get());
    KeyguardManager kService = mock(KeyguardManager.class);
    when(activity.getSystemService(Context.KEYGUARD_SERVICE)).thenReturn(kService);
    when(kService.isKeyguardSecure()).thenReturn(true);
    Intent confirmCredentialsIntent = mock(Intent.class);
    when(kService.createConfirmDeviceCredentialIntent("theTitle", "theDescription")).thenReturn(confirmCredentialsIntent);
    boolean willRequireAuthentication = manager.requireAuthentication(activity, 123, "theTitle", "theDescription");
    assertThat(willRequireAuthentication, is(true));

    manager.getCredentials(callback);

    //Should fail because of expired credentials
    verify(callback).onFailure(exceptionCaptor.capture());
    CredentialsManagerException exception = exceptionCaptor.getValue();
    assertThat(exception, is(notNullValue()));
    assertThat(exception.getMessage(), is("No Credentials were previously set."));

    //A second call to checkAuthenticationResult should fail as callback is set to null
    final boolean retryCheck = manager.checkAuthenticationResult(123, Activity.RESULT_OK);
    assertThat(retryCheck, is(false));
}
 
Example #20
Source File: FingerprintAuthenticationDialogFragment.java    From keemob with MIT License 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Do not create a new Fragment when the Activity is re-created such as orientation changes.
    setRetainInstance(true);
    setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Material_Light_Dialog);

    mKeyguardManager = (KeyguardManager) getContext().getSystemService(Context.KEYGUARD_SERVICE);
    mFingerprintUiHelperBuilder = new FingerprintUiHelper.FingerprintUiHelperBuilder(
            getContext(), getContext().getSystemService(FingerprintManager.class));

}
 
Example #21
Source File: FingerprintAuthenticationDialogFragment.java    From keemob with MIT License 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Do not create a new Fragment when the Activity is re-created such as orientation changes.
    setRetainInstance(true);
    setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Material_Light_Dialog);

    mKeyguardManager = (KeyguardManager) getContext().getSystemService(Context.KEYGUARD_SERVICE);
    mFingerprintUiHelperBuilder = new FingerprintUiHelper.FingerprintUiHelperBuilder(
            getContext(), getContext().getSystemService(FingerprintManager.class));

}
 
Example #22
Source File: SuntimesSettingsActivity.java    From SuntimesWidget with GNU General Public License v3.0 5 votes vote down vote up
protected static boolean isDeviceSecure(Context context)
{
    KeyguardManager keyguard = (KeyguardManager)context.getSystemService(Context.KEYGUARD_SERVICE);
    if (keyguard != null)
    {
        if (Build.VERSION.SDK_INT >= 23) {
            return keyguard.isDeviceSecure();

        } else if (Build.VERSION.SDK_INT >= 16) {
            return keyguard.isKeyguardSecure();

        } else return false;
    } else return false;
}
 
Example #23
Source File: FingerAuth.java    From FingerAuth with Apache License 2.0 5 votes vote down vote up
public static boolean hasFingerprintSupport(Context context) {
    FingerprintManagerCompat fingerprintManager = FingerprintManagerCompat.from(context);
    boolean hardwareSupport = fingerprintManager.isHardwareDetected();

    boolean secureSupport = true;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
        KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
        if (keyguardManager!=null)
            secureSupport = keyguardManager.isKeyguardSecure();
    }

    boolean hasPwd = fingerprintManager.hasEnrolledFingerprints();
    return hardwareSupport && secureSupport && hasPwd;
}
 
Example #24
Source File: Air.java    From stynico with MIT License 5 votes vote down vote up
private void wakeAndUnlock2(boolean b)
{
    if(b)
    {
        //获取电源管理器对象
        pm=(PowerManager) getSystemService(Context.POWER_SERVICE);

        //获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是调试用的Tag
        wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");

        //点亮屏幕
        wl.acquire();

        //得到键盘锁管理器对象
        km= (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE);
        kl = km.newKeyguardLock("unLock");

        //解锁
        kl.disableKeyguard();
    }
    else
    {
        //锁屏
        kl.reenableKeyguard();

        //释放wakeLock,关灯
        wl.release();
    }

}
 
Example #25
Source File: PopupNotificationActivity.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
private void handleIntent(Intent intent) {
    isReply = intent != null && intent.getBooleanExtra("force", false);
    popupMessages.clear();
    if (isReply) {
        int account = intent != null ? intent.getIntExtra("currentAccount", UserConfig.selectedAccount) : UserConfig.selectedAccount;
        popupMessages.addAll(NotificationsController.getInstance(account).popupReplyMessages);
    } else {
        for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
            if (UserConfig.getInstance(a).isClientActivated()) {
                popupMessages.addAll(NotificationsController.getInstance(a).popupMessages);
            }
        }
    }
    KeyguardManager km = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
    if (km.inKeyguardRestrictedInputMode() || !ApplicationLoader.isScreenOn) {
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_DIM_BEHIND |
                        WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                        WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
                        WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
    } else {
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                        WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
                        WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }

    if (currentMessageObject == null) {
        currentMessageNum = 0;
    }
    getNewMessage();
}
 
Example #26
Source File: VoIPService.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
protected void startRinging() {
	if(currentState==STATE_WAITING_INCOMING){
		return;
	}
	if(USE_CONNECTION_SERVICE && systemCallConnection!=null)
		systemCallConnection.setRinging();
       if (BuildVars.LOGS_ENABLED) {
           FileLog.d("starting ringing for call " + call.id);
       }
	dispatchStateChanged(STATE_WAITING_INCOMING);
	startRingtoneAndVibration(user.id);
	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !((KeyguardManager) getSystemService(KEYGUARD_SERVICE)).inKeyguardRestrictedInputMode() && NotificationManagerCompat.from(this).areNotificationsEnabled()) {
		showIncomingNotification(ContactsController.formatName(user.first_name, user.last_name), null, user, null, 0, VoIPActivity.class);
           if (BuildVars.LOGS_ENABLED) {
               FileLog.d("Showing incoming call notification");
           }
	} else {
           if (BuildVars.LOGS_ENABLED) {
               FileLog.d("Starting incall activity for incoming call");
           }
		try {
			PendingIntent.getActivity(VoIPService.this, 12345, new Intent(VoIPService.this, VoIPActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0).send();
		} catch (Exception x) {
               if (BuildVars.LOGS_ENABLED) {
                   FileLog.e("Error starting incall activity", x);
               }
		}
		if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
			showNotification();
		}
	}
}
 
Example #27
Source File: MainActivity.java    From linphone-android with GNU General Public License v3.0 5 votes vote down vote up
public void requestPermissionIfNotGranted(String permission) {
    if (!checkPermission(permission)) {
        Log.i("[Permission] Requesting " + permission + " permission");

        String[] permissions = new String[] {permission};
        KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        boolean locked = km.inKeyguardRestrictedInputMode();
        if (!locked) {
            // This is to workaround an infinite loop of pause/start in Activity issue
            // if incoming call ends while screen if off and locked
            ActivityCompat.requestPermissions(this, permissions, FRAGMENT_SPECIFIC_PERMISSION);
        }
    }
}
 
Example #28
Source File: SignTransactionDialog.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
private void showAuthenticationScreen()
{
    KeyguardManager mKeyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
    Intent intent = mKeyguardManager.createConfirmDeviceCredentialIntent(unlockTitle, unlockDetail);
    if (intent != null) {
        context.startActivityForResult(intent, REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS + callBackId.ordinal());
    }
}
 
Example #29
Source File: KeyStoreAES.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static void showAuthenticationScreen(final Activity act, final String network) throws RuntimeException {
    final KeyguardManager keyguardManager = (KeyguardManager) act.getSystemService(Context.KEYGUARD_SERVICE);
    final boolean isSaveActivity = (act instanceof PinSaveActivity);
    final String authTitle = !isSaveActivity ? act.getString(R.string.id_blockstream_green) : "";
    final String authDesc = !isSaveActivity ? act.getString(R.string.id_log_in_into_your_s_wallet, network) : "";
    final Intent intent = keyguardManager.createConfirmDeviceCredentialIntent(authTitle, authDesc);
    if (intent == null)
        throw new RuntimeException();
    act.startActivityForResult(intent, ACTIVITY_REQUEST_CODE);
}
 
Example #30
Source File: DeviceAvailability.java    From react-native-keychain with MIT License 5 votes vote down vote up
public static boolean isDeviceSecure(@NonNull final Context context) {
  final KeyguardManager km =
    (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);

  return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
    km != null &&
    km.isDeviceSecure();
}