Example usage for android.app KeyguardManager isKeyguardSecure

List of usage examples for android.app KeyguardManager isKeyguardSecure

Introduction

In this page you can find the example usage for android.app KeyguardManager isKeyguardSecure.

Prototype

public boolean isKeyguardSecure() 

Source Link

Document

Return whether the keyguard is secured by a PIN, pattern or password or a SIM card is currently locked.

Usage

From source file:Main.java

/**
 * Return whether the keyguard requires a password to unlock and may
 * have any privacy restrictions.//from   ww  w  .  j  av  a  2 s. c  o m
 */
public static boolean isSecure(@NonNull Context context) {
    KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
    return km.isKeyguardSecure() && km.isKeyguardLocked();
}

From source file:com.outsystemscloud.andrevieira.secureDevice.java

/**
 * @param context/*  ww w . j av a  2s . c  om*/
 * @return true if pass or pin set
 */
@SuppressLint("NewApi")
private static boolean isPassOrPinSet(Context context) {
    KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); //api 16+
    return keyguardManager.isKeyguardSecure();
}

From source file:eu.musesproject.client.contextmonitoring.sensors.DeviceProtectionSensor.java

public boolean isPasswordProtected() {
    KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);

    return keyguardManager.isKeyguardSecure();
}

From source file:com.owncloud.android.ui.activity.FingerprintActivity.java

private void startFingerprint() {
    TextView fingerprintTextView = (TextView) findViewById(R.id.scanfingerprinttext);

    FingerprintManager fingerprintManager = (FingerprintManager) MainApp.getAppContext()
            .getSystemService(Context.FINGERPRINT_SERVICE);

    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
        return;//from ww w.ja v  a 2  s.c om
    }
    KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);

    if (!keyguardManager.isKeyguardSecure()) {
        return;
    } else {
        generateKey();

        if (cipherInit()) {
            cryptoObject = new FingerprintManager.CryptoObject(cipher);
            FingerprintHandler.Callback callback = new FingerprintHandler.Callback() {
                @Override
                public void onAuthenticated() {
                    fingerprintResult(true);
                }

                @Override
                public void onFailed(String error) {
                    Toast.makeText(MainApp.getAppContext(), error, Toast.LENGTH_LONG).show();
                    ImageView imageView = (ImageView) findViewById(R.id.fingerprinticon);
                    int[][] states = new int[][] { new int[] { android.R.attr.state_activated },
                            new int[] { -android.R.attr.state_activated } };
                    int[] colors = new int[] { Color.parseColor("#FF0000"), Color.RED };
                    ColorStateList csl = new ColorStateList(states, colors);
                    Drawable drawable = DrawableCompat.wrap(imageView.getDrawable());
                    DrawableCompat.setTintList(drawable, csl);
                    imageView.setImageDrawable(drawable);
                }
            };

            helper = new FingerprintHandler(fingerprintTextView, callback);
            cancellationSignal = new CancellationSignal();
            if (ActivityCompat.checkSelfPermission(MainApp.getAppContext(),
                    Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            fingerprintManager.authenticate(cryptoObject, cancellationSignal, 0, helper, null);
        }
    }
}

From source file:org.thoughtcrime.securesms.PassphrasePromptActivity.java

private void resumeScreenLock() {
    KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);

    assert keyguardManager != null;

    if (!keyguardManager.isKeyguardSecure()) {
        Log.w(TAG, "Keyguard not secure...");
        handleAuthenticated();/*from   w w w.  j  a  v a2s .co m*/
        return;
    }

    if (fingerprintManager.isHardwareDetected() && fingerprintManager.hasEnrolledFingerprints()) {
        Log.i(TAG, "Listening for fingerprints...");
        fingerprintCancellationSignal = new CancellationSignal();
        fingerprintManager.authenticate(null, 0, fingerprintCancellationSignal, fingerprintListener, null);
    } else if (Build.VERSION.SDK_INT >= 21) {
        Log.i(TAG, "firing intent...");
        Intent intent = keyguardManager.createConfirmDeviceCredentialIntent("Unlock Signal", "");
        startActivityForResult(intent, 1);
    } else {
        Log.w(TAG, "Not compatible...");
        handleAuthenticated();
    }
}

From source file:de.schildbach.wallet.util.FingerprintHelper.java

@TargetApi(Build.VERSION_CODES.M)
public boolean init() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        log.info("This Android version does not support fingerprint authentication");
        return false;
    }/*from  ww  w  .ja v  a2  s .c  om*/

    KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(KEYGUARD_SERVICE);
    fingerprintManager = FingerprintManagerCompat.from(context);

    if (!keyguardManager.isKeyguardSecure()) {
        log.info("User hasn't enabled Lock Screen");
        return false;
    }

    if (!hasPermission()) {
        log.info("User hasn't granted permission to use Fingerprint");
        return false;
    }

    if (!fingerprintManager.hasEnrolledFingerprints()) {
        log.info("User hasn't registered any fingerprints");
        return false;
    }

    if (!initKeyStore()) {
        return false;
    }
    return true;
}

From source file:com.rnd.snapsplit.view.OwedFragment.java

@Nullable
@Override/*from  w w  w. j  a v  a  2 s  . c om*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //super.onCreate(savedInstanceState);
    view = inflater.inflate(R.layout.activity_owed, container, false);
    activity = getActivity();
    profile = new Profile(getContext());
    ((Toolbar) getActivity().findViewById(R.id.tool_bar_hamburger)).setVisibility(View.VISIBLE);

    mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);
    mMessageRecyclerView = (RecyclerView) view.findViewById(R.id.messageRecyclerView);
    mLinearLayoutManager = new LinearLayoutManager(getContext());
    //mLinearLayoutManager.setStackFromEnd(true);
    mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference().child("requests");
    mFirebaseAdapter = new FirebaseRecyclerAdapter<PaymentRequest, MessageViewHolder>(PaymentRequest.class,
            R.layout.list_owed, MessageViewHolder.class,
            mFirebaseDatabaseReference.orderByChild("requestEpochDate")) {

        @Override
        protected PaymentRequest parseSnapshot(DataSnapshot snapshot) {
            PaymentRequest pr = super.parseSnapshot(snapshot);
            if (pr != null) {
                pr.setId(snapshot.getKey());
                return pr;
            }
            return null;
        }

        @Override
        protected void populateViewHolder(final MessageViewHolder viewHolder, PaymentRequest pr, int position) {
            mProgressBar.setVisibility(ProgressBar.INVISIBLE);
            if (pr != null && pr.getReceipientPhoneNo().equals(profile.getPhoneNumber())) {

                if (pr.getStrReceiptPic() != null && !pr.getStrReceiptPic().equals("")) {
                    String encodedReceipt = pr.getStrReceiptPic();
                    byte[] encodeByte = Base64.decode(encodedReceipt, Base64.DEFAULT);
                    Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
                    viewHolder.receiptIcon.setImageBitmap(bitmap);
                }
                viewHolder.pr = pr;
                viewHolder.id = pr.getId();
                viewHolder.description.setText(pr.getDescription());
                viewHolder.from.setText(
                        "Request sent by: " + pr.getRequestorName() + " - " + pr.getRequestorPhoneNumber());
                viewHolder.share.setText("Your Share: HKD" + String.format("%.2f", pr.getShareAmount()));
                viewHolder.splitAmount
                        .setText("Total Amount: HKD" + String.format("%.2f", pr.getTotalAmount()));
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy' 'HH:mm:ss");
                String date = null;
                Date temp = new Date(Long.parseLong(pr.getRequestEpochDate()) * (-1));
                date = simpleDateFormat.format(temp);
                viewHolder.date.setText(date);
            } else {
                ViewGroup.LayoutParams params = viewHolder.item.getLayoutParams();
                params.height = 0;
                viewHolder.item.setLayoutParams(params);
            }

            // log a view action on it
            //FirebaseUserActions.getInstance().end(getMessageViewAction(fd));
        }

        @Override
        public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            MessageViewHolder viewHolder = super.onCreateViewHolder(parent, viewType);
            viewHolder.setOnLongClickListener(new MessageViewHolder.LongClickListener() {
                @Override
                public void onLongClick(View view, int position, String id, PaymentRequest pr) {
                    AlertDialog.Builder ImageDialog = new AlertDialog.Builder(getActivity());
                    ImageDialog.setTitle("Receipt Preview - " + pr.getDescription());
                    ImageView showImage = new ImageView(getActivity());
                    Bitmap bitmap = null;
                    if (pr.getStrReceiptPic() != null && !pr.getStrReceiptPic().equals("")) {
                        String encodedReceipt = pr.getStrReceiptPic();
                        byte[] encodeByte = Base64.decode(encodedReceipt, Base64.DEFAULT);
                        bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
                    }
                    if (bitmap != null) {
                        showImage.setImageBitmap(bitmap);
                    }
                    ImageDialog.setView(showImage);

                    ImageDialog.setNegativeButton("Close Preview", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface arg0, int arg1) {
                        }
                    });
                    ImageDialog.show();
                }
            });
            viewHolder.setOnClickListener(new MessageViewHolder.ClickListener() {
                @Override
                public void onItemClick(View view, int position, String id, PaymentRequest pr) {
                    //Toast.makeText(getActivity(), "Item clicked at " + position, Toast.LENGTH_SHORT).show();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("pr", pr);

                    if (initCipher(mCipher, DEFAULT_KEY_NAME)) {
                        // Show the fingerprint dialog. The user has the option to use the fingerprint with
                        // crypto, or you can fall back to using a server-side verified password.
                        DialogFragmentFingerprintAuthentication fragment = new DialogFragmentFingerprintAuthentication();
                        fragment.setCryptoObject(new FingerprintManager.CryptoObject(mCipher));
                        boolean useFingerprintPreference = mSharedPreferences
                                .getBoolean(getString(R.string.use_fingerprint_to_authenticate_key), true);
                        if (useFingerprintPreference) {
                            fragment.setStage(DialogFragmentFingerprintAuthentication.Stage.FINGERPRINT);
                        } else {
                            fragment.setStage(DialogFragmentFingerprintAuthentication.Stage.PASSWORD);
                        }
                        fragment.setArguments(bundle);
                        fragment.setTargetFragment(mFragment, 0);
                        fragment.show(getFragmentManager(), DIALOG_FRAGMENT_TAG);
                    } else {
                        // This happens if the lock screen has been disabled or or a fingerprint got
                        // enrolled. Thus show the dialog to authenticate with their password first
                        // and ask the user if they want to authenticate with fingerprints in the
                        // future
                        DialogFragmentFingerprintAuthentication fragment = new DialogFragmentFingerprintAuthentication();
                        fragment.setCryptoObject(new FingerprintManager.CryptoObject(mCipher));
                        fragment.setStage(
                                DialogFragmentFingerprintAuthentication.Stage.NEW_FINGERPRINT_ENROLLED);
                        fragment.setArguments(bundle);
                        fragment.setTargetFragment(mFragment, 0);
                        fragment.show(getFragmentManager(), DIALOG_FRAGMENT_TAG);
                    }
                }

            });
            return viewHolder;
        }

    };

    mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            super.onItemRangeInserted(positionStart, itemCount);
            int friendlyMessageCount = mFirebaseAdapter.getItemCount();
            int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
            // If the recycler view is initially being loaded or the user is at the bottom of the list, scroll
            // to the bottom of the list to show the newly added message.
            if (lastVisiblePosition == -1 || (positionStart >= (friendlyMessageCount - 1)
                    && lastVisiblePosition == (positionStart - 1))) {
                mMessageRecyclerView.scrollToPosition(positionStart);
            }
        }
    });

    mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
    mMessageRecyclerView.setAdapter(mFirebaseAdapter);

    try {
        mKeyStore = KeyStore.getInstance("AndroidKeyStore");
    } catch (KeyStoreException e) {
        throw new RuntimeException("Failed to get an instance of KeyStore", e);
    }
    try {
        mKeyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        throw new RuntimeException("Failed to get an instance of KeyGenerator", e);
    }
    //Cipher defaultCipher;
    Cipher cipherNotInvalidated;
    try {
        mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/"
                + KeyProperties.ENCRYPTION_PADDING_PKCS7);
        cipherNotInvalidated = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
                + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        throw new RuntimeException("Failed to get an instance of Cipher", e);
    }
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());

    KeyguardManager keyguardManager = getActivity().getSystemService(KeyguardManager.class);
    FingerprintManager fingerprintManager = getActivity().getSystemService(FingerprintManager.class);

    if (!keyguardManager.isKeyguardSecure()) {
        // Show a message that the user hasn't set up a fingerprint or lock screen.
        Toast.makeText(getActivity(),
                "Secure lock screen hasn't set up.\n"
                        + "Go to 'Settings -> Security -> Fingerprint' to set up a fingerprint",
                Toast.LENGTH_LONG).show();
        //return;
    }

    // Now the protection level of USE_FINGERPRINT permission is normal instead of dangerous.
    // See http://developer.android.com/reference/android/Manifest.permission.html#USE_FINGERPRINT
    // The line below prevents the false positive inspection from Android Studio
    // noinspection ResourceType
    if (!fingerprintManager.hasEnrolledFingerprints()) {
        // This happens when no fingerprints are registered.
        Toast.makeText(getActivity(),
                "Go to 'Settings -> Security -> Fingerprint' and register at least one fingerprint",
                Toast.LENGTH_LONG).show();
        //return;
    }

    createKey(DEFAULT_KEY_NAME, true);
    createKey(KEY_NAME_NOT_INVALIDATED, false);

    return view;

}

From source file:org.nypl.simplified.app.MainSettingsAccountActivity.java

@TargetApi(21)
private void handle_pin_reveal(final TextView in_pin_text, final CheckBox in_pin_reveal) {
    /*/*from   www.j  a v  a 2s  .  co m*/
     * Add a listener that reveals/hides the password field.
     */
    in_pin_reveal.setOnCheckedChangeListener((view, checked) -> {
        if (checked) {
            final KeyguardManager keyguard_manager = (KeyguardManager) getSystemService(
                    Context.KEYGUARD_SERVICE);
            if (!keyguard_manager.isKeyguardSecure()) {
                // Show a message that the user hasn't set up a lock screen.
                Toast.makeText(this, R.string.settings_screen_Lock_not_setup, Toast.LENGTH_LONG).show();
                in_pin_reveal.setChecked(false);
            } else {
                final Intent intent = keyguard_manager.createConfirmDeviceCredentialIntent(null, null);
                if (intent != null) {
                    startActivityForResult(intent, 1);
                }
            }
        } else {
            in_pin_text.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
    });
}

From source file:com.breadwallet.BreadWalletApp.java

public void promptForAuthentication(Activity context, int mode, PaymentRequestEntity requestEntity,
        String message, String title, PaymentRequestWrapper paymentRequest, boolean forcePasscode) {
    Log.e(TAG, "promptForAuthentication: " + mode);
    if (context == null)
        return;/*from   w  ww . jav  a 2s.  com*/
    KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Activity.KEYGUARD_SERVICE);

    boolean useFingerPrint = ActivityCompat.checkSelfPermission(this,
            Manifest.permission.USE_FINGERPRINT) == PackageManager.PERMISSION_GRANTED
            && mFingerprintManager.isHardwareDetected() && mFingerprintManager.hasEnrolledFingerprints();
    if (mode == BRConstants.AUTH_FOR_PAY) {
        long limit = KeyStoreManager.getSpendLimit(context);
        long totalSent = BRWalletManager.getInstance(context).getTotalSent();

        if (requestEntity != null)
            if (limit <= totalSent + requestEntity.amount) {
                useFingerPrint = false;
            }
    }

    if (mode == BRConstants.AUTH_FOR_LIMIT || mode == BRConstants.AUTH_FOR_PHRASE) {
        useFingerPrint = false;
    }

    if (KeyStoreManager.getFailCount(context) != 0) {
        useFingerPrint = false;
    }
    long passTime = KeyStoreManager.getLastPasscodeUsedTime(context);
    if (passTime + TimeUnit.MILLISECONDS.convert(2, TimeUnit.DAYS) <= System.currentTimeMillis()) {
        useFingerPrint = false;
    }
    if (forcePasscode)
        useFingerPrint = false;

    if (keyguardManager.isKeyguardSecure()) {
        if (useFingerPrint) {
            // This happens when no fingerprints are registered.
            FingerprintDialogFragment fingerprintDialogFragment = new FingerprintDialogFragment();
            fingerprintDialogFragment.setMode(mode);
            fingerprintDialogFragment.setPaymentRequestEntity(requestEntity, paymentRequest);
            fingerprintDialogFragment.setMessage(message);
            fingerprintDialogFragment.setTitle(message != null ? "" : title);
            if (!context.isDestroyed())
                fingerprintDialogFragment.show(context.getFragmentManager(),
                        FingerprintDialogFragment.class.getName());
        } else {
            PasswordDialogFragment passwordDialogFragment = new PasswordDialogFragment();
            passwordDialogFragment.setMode(mode);
            passwordDialogFragment.setPaymentRequestEntity(requestEntity, paymentRequest);
            passwordDialogFragment.setVerifyOnlyTrue();
            passwordDialogFragment.setMessage(message);
            if (!context.isDestroyed())
                passwordDialogFragment.show(context.getFragmentManager(),
                        PasswordDialogFragment.class.getName());
        }
    } else {
        showDeviceNotSecuredWarning(context);
    }

}

From source file:com.jins_meme.bridge.MainActivity.java

void showAuthScreen() {
    KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);

    if (!keyguardManager.isKeyguardSecure()) {
        basicConfigFragment.unlockAppIDandSecret();
        return;/*from w  w  w. j a v  a  2  s. c  om*/
    }

    Intent intent = keyguardManager.createConfirmDeviceCredentialIntent(getString(R.string.unlock_auth_title),
            getString(R.string.unlock_auth_explain));

    if (intent != null) {
        startActivityForResult(intent, 1);
    }
}