Example usage for android.content Context KEYGUARD_SERVICE

List of usage examples for android.content Context KEYGUARD_SERVICE

Introduction

In this page you can find the example usage for android.content Context KEYGUARD_SERVICE.

Prototype

String KEYGUARD_SERVICE

To view the source code for android.content Context KEYGUARD_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.app.KeyguardManager for controlling keyguard.

Usage

From source file:ro.ciubex.keepscreenlock.MainApplication.java

/**
 * Called when the application is starting, before any activity, service,
 * or receiver objects (excluding content providers) have been created.
 *//*from   w  w w  .  jav  a 2 s  .c o m*/
@Override
public void onCreate() {
    super.onCreate();
    MainApplication.isEmulator = String.valueOf(Build.PRODUCT).startsWith("sdk");
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mDeviceManger = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
    mComponentName = new ComponentName(this, AdminPermissionReceiver.class);
    mSdkInt = android.os.Build.VERSION.SDK_INT;
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    initLocale();
    checkKeepScreenLockReceiver();
}

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.  ja v  a 2  s  .c o  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:com.tozny.e3db.android.DefaultKeyAuthenticator.java

@RequiresApi(api = Build.VERSION_CODES.M)
@Override/*from w w  w.j  a  v a 2  s. c  om*/
public void authenticateWithLockScreen(AuthenticateHandler cont) {
    DeviceCredentialsFragment f = new DeviceCredentialsFragment(cont, title,
            (KeyguardManager) activity.getSystemService(Context.KEYGUARD_SERVICE));
    FragmentManager fragmentManager = activity.getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(f, "device_credentials_fragment");
    fragmentTransaction.commit();
}

From source file:com.android.cts.verifier.managedprovisioning.ByodHelperActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        Log.w(TAG, "Restored state");
        mOriginalSettings = savedInstanceState.getBundle(ORIGINAL_SETTINGS_NAME);
    } else {//from  www.j  a  va  2s . c  o m
        mOriginalSettings = new Bundle();
    }

    mAdminReceiverComponent = new ComponentName(this, DeviceAdminTestReceiver.class.getName());
    mDevicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Intent intent = getIntent();
    String action = intent.getAction();
    Log.d(TAG, "ByodHelperActivity.onCreate: " + action);

    // we are explicitly started by {@link DeviceAdminTestReceiver} after a successful provisioning.
    if (action.equals(ACTION_PROFILE_PROVISIONED)) {
        // Jump back to CTS verifier with result.
        Intent response = new Intent(ACTION_PROFILE_OWNER_STATUS);
        response.putExtra(EXTRA_PROVISIONED, isProfileOwner());
        startActivityInPrimary(response);
        // Queried by CtsVerifier in the primary side using startActivityForResult.
    } else if (action.equals(ACTION_QUERY_PROFILE_OWNER)) {
        Intent response = new Intent();
        response.putExtra(EXTRA_PROVISIONED, isProfileOwner());
        setResult(RESULT_OK, response);
        // Request to delete work profile.
    } else if (action.equals(ACTION_REMOVE_MANAGED_PROFILE)) {
        if (isProfileOwner()) {
            Log.d(TAG, "Clearing cross profile intents");
            mDevicePolicyManager.clearCrossProfileIntentFilters(mAdminReceiverComponent);
            mDevicePolicyManager.wipeData(0);
            showToast(R.string.provisioning_byod_profile_deleted);
        }
    } else if (action.equals(ACTION_INSTALL_APK)) {
        boolean allowNonMarket = intent.getBooleanExtra(EXTRA_ALLOW_NON_MARKET_APPS, false);
        boolean wasAllowed = getAllowNonMarket();

        // Update permission to install non-market apps
        setAllowNonMarket(allowNonMarket);
        mOriginalSettings.putBoolean(INSTALL_NON_MARKET_APPS, wasAllowed);

        // Request to install a non-market application- easiest way is to reinstall ourself
        final Intent installIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE)
                .setData(Uri.parse("package:" + getPackageName()))
                .putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true).putExtra(Intent.EXTRA_RETURN_RESULT, true);
        startActivityForResult(installIntent, REQUEST_INSTALL_PACKAGE);

        // Not yet ready to finish- wait until the result comes back
        return;
        // Queried by CtsVerifier in the primary side using startActivityForResult.
    } else if (action.equals(ACTION_CHECK_INTENT_FILTERS)) {
        final boolean intentFiltersSetForManagedIntents = new IntentFiltersTestHelper(this)
                .checkCrossProfileIntentFilters(IntentFiltersTestHelper.FLAG_INTENTS_FROM_MANAGED);
        setResult(intentFiltersSetForManagedIntents ? RESULT_OK : RESULT_FAILED, null);
    } else if (action.equals(ACTION_CAPTURE_AND_CHECK_IMAGE)) {
        // We need the camera permission to send the image capture intent.
        grantCameraPermissionToSelf();
        Intent captureImageIntent = getCaptureImageIntent();
        Pair<File, Uri> pair = getTempUri("image.jpg");
        mImageFile = pair.first;
        mImageUri = pair.second;
        captureImageIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
        if (captureImageIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(captureImageIntent, REQUEST_IMAGE_CAPTURE);
        } else {
            Log.e(TAG, "Capture image intent could not be resolved in managed profile.");
            showToast(R.string.provisioning_byod_capture_media_error);
            finish();
        }
        return;
    } else if (action.equals(ACTION_CAPTURE_AND_CHECK_VIDEO_WITH_EXTRA_OUTPUT)
            || action.equals(ACTION_CAPTURE_AND_CHECK_VIDEO_WITHOUT_EXTRA_OUTPUT)) {
        // We need the camera permission to send the video capture intent.
        grantCameraPermissionToSelf();
        Intent captureVideoIntent = getCaptureVideoIntent();
        int videoCaptureRequestId;
        if (action.equals(ACTION_CAPTURE_AND_CHECK_VIDEO_WITH_EXTRA_OUTPUT)) {
            mVideoUri = getTempUri("video.mp4").second;
            captureVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mVideoUri);
            videoCaptureRequestId = REQUEST_VIDEO_CAPTURE_WITH_EXTRA_OUTPUT;
        } else {
            videoCaptureRequestId = REQUEST_VIDEO_CAPTURE_WITHOUT_EXTRA_OUTPUT;
        }
        if (captureVideoIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(captureVideoIntent, videoCaptureRequestId);
        } else {
            Log.e(TAG, "Capture video intent could not be resolved in managed profile.");
            showToast(R.string.provisioning_byod_capture_media_error);
            finish();
        }
        return;
    } else if (action.equals(ACTION_CAPTURE_AND_CHECK_AUDIO)) {
        Intent captureAudioIntent = getCaptureAudioIntent();
        if (captureAudioIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(captureAudioIntent, REQUEST_AUDIO_CAPTURE);
        } else {
            Log.e(TAG, "Capture audio intent could not be resolved in managed profile.");
            showToast(R.string.provisioning_byod_capture_media_error);
            finish();
        }
        return;
    } else if (ACTION_KEYGUARD_DISABLED_FEATURES.equals(action)) {
        final int value = intent.getIntExtra(EXTRA_PARAMETER_1,
                DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE);
        mDevicePolicyManager.setKeyguardDisabledFeatures(mAdminReceiverComponent, value);
    } else if (ACTION_LOCKNOW.equals(action)) {
        mDevicePolicyManager.lockNow();
        setResult(RESULT_OK);
    } else if (action.equals(ACTION_TEST_NFC_BEAM)) {
        Intent testNfcBeamIntent = new Intent(this, NfcTestActivity.class);
        testNfcBeamIntent.putExtras(intent);
        startActivity(testNfcBeamIntent);
        finish();
        return;
    } else if (action.equals(ACTION_TEST_CROSS_PROFILE_INTENTS_DIALOG)) {
        sendIntentInsideChooser(new Intent(CrossProfileTestActivity.ACTION_CROSS_PROFILE_TO_PERSONAL));
    } else if (action.equals(ACTION_TEST_APP_LINKING_DIALOG)) {
        mDevicePolicyManager.addUserRestriction(DeviceAdminTestReceiver.getReceiverComponentName(),
                UserManager.ALLOW_PARENT_PROFILE_APP_LINKING);
        Intent toSend = new Intent(Intent.ACTION_VIEW);
        toSend.setData(Uri.parse("http://com.android.cts.verifier"));
        sendIntentInsideChooser(toSend);
    } else if (action.equals(ACTION_SET_USER_RESTRICTION)) {
        final String restriction = intent.getStringExtra(EXTRA_PARAMETER_1);
        if (restriction != null) {
            mDevicePolicyManager.addUserRestriction(DeviceAdminTestReceiver.getReceiverComponentName(),
                    restriction);
        }
    } else if (action.equals(ACTION_CLEAR_USER_RESTRICTION)) {
        final String restriction = intent.getStringExtra(EXTRA_PARAMETER_1);
        if (restriction != null) {
            mDevicePolicyManager.clearUserRestriction(DeviceAdminTestReceiver.getReceiverComponentName(),
                    restriction);
        }
    } else if (action.equals(ACTION_BYOD_SET_LOCATION_AND_CHECK_UPDATES)) {
        handleLocationAction();
        return;
    } else if (action.equals(ACTION_NOTIFICATION)) {
        showNotification(Notification.VISIBILITY_PUBLIC);
    } else if (ACTION_NOTIFICATION_ON_LOCKSCREEN.equals(action)) {
        mDevicePolicyManager.lockNow();
        showNotification(Notification.VISIBILITY_PRIVATE);
    } else if (ACTION_CLEAR_NOTIFICATION.equals(action)) {
        mNotificationManager.cancel(NOTIFICATION_ID);
    } else if (ACTION_TEST_SELECT_WORK_CHALLENGE.equals(action)) {
        mDevicePolicyManager.setOrganizationColor(mAdminReceiverComponent, Color.BLUE);
        mDevicePolicyManager.setOrganizationName(mAdminReceiverComponent,
                getResources().getString(R.string.provisioning_byod_confirm_work_credentials_header));
        startActivity(new Intent(DevicePolicyManager.ACTION_SET_NEW_PASSWORD));
    } else if (ACTION_LAUNCH_CONFIRM_WORK_CREDENTIALS.equals(action)) {
        KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        Intent launchIntent = keyguardManager.createConfirmDeviceCredentialIntent(null, null);
        startActivity(launchIntent);
    } else if (ACTION_SET_ORGANIZATION_INFO.equals(action)) {
        if (intent.hasExtra(OrganizationInfoTestActivity.EXTRA_ORGANIZATION_NAME)) {
            final String organizationName = intent
                    .getStringExtra(OrganizationInfoTestActivity.EXTRA_ORGANIZATION_NAME);
            mDevicePolicyManager.setOrganizationName(mAdminReceiverComponent, organizationName);
        }
        final int organizationColor = intent.getIntExtra(OrganizationInfoTestActivity.EXTRA_ORGANIZATION_COLOR,
                mDevicePolicyManager.getOrganizationColor(mAdminReceiverComponent));
        mDevicePolicyManager.setOrganizationColor(mAdminReceiverComponent, organizationColor);
    } else if (ACTION_TEST_PARENT_PROFILE_PASSWORD.equals(action)) {
        startActivity(new Intent(DevicePolicyManager.ACTION_SET_NEW_PARENT_PROFILE_PASSWORD));
    }
    // This activity has no UI and is only used to respond to CtsVerifier in the primary side.
    finish();
}

From source file:com.android.app.MediaPlaybackActivity.java

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    if (mService == null)
        return false;
    MenuItem item = menu.findItem(PARTY_SHUFFLE);
    if (item != null) {
        int shuffle = MusicUtils.getCurrentShuffleMode();
        if (shuffle == MediaPlaybackService.SHUFFLE_AUTO) {
            item.setIcon(R.drawable.ic_menu_party_shuffle);
            item.setTitle(R.string.party_shuffle_off);
        } else {//from  www . ja v  a2  s. com
            item.setIcon(R.drawable.ic_menu_party_shuffle);
            item.setTitle(R.string.party_shuffle);
        }
    }

    item = menu.findItem(ADD_TO_PLAYLIST);
    if (item != null) {
        SubMenu sub = item.getSubMenu();
        MusicUtils.makePlaylistMenu(this, sub);
    }

    KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
    menu.setGroupVisible(1, !km.inKeyguardRestrictedInputMode());

    return true;
}

From source file:com.ucmap.dingdinghelper.services.DingDingHelperAccessibilityService.java

private void wakeAndUnlock() {
    //???//from  www  . j  av a  2 s  .  c  o  m
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);

    //?PowerManager.WakeLock???|??Tag
    PowerManager.WakeLock wl = pm
            .newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");

    //?
    wl.acquire(1000);

    //??
    KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
    kl = km.newKeyguardLock("unLock");

    //?
    kl.disableKeyguard();

}

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) {
    /*/* www .j a  v a  2  s  . c o  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:research.sg.edu.edapp.kb.KbSoftKeyboard.java

public String getAppName() {
    String packagename;/*from w  w  w.j a  v a2 s. c o  m*/

    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {

        KeyguardManager myKM = (KeyguardManager) getApplicationContext()
                .getSystemService(Context.KEYGUARD_SERVICE);
        if (myKM.inKeyguardRestrictedInputMode()) {
            //it is locked

            System.out.println("[AppLogger]Screen is locked");
            packagename = "LockScreen";
        } else {
            //it is not locked

            ActivityManager am = (ActivityManager) getApplicationContext().getSystemService(ACTIVITY_SERVICE);

            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;

            packagename = componentInfo.getPackageName();

            System.out.println(
                    "[AppLogger]Build Version:" + Build.VERSION.SDK_INT + ",Package Name:" + packagename);
        }
    }

    else {

        KeyguardManager myKM = (KeyguardManager) getApplicationContext()
                .getSystemService(Context.KEYGUARD_SERVICE);
        if (myKM.inKeyguardRestrictedInputMode()) {
            //it is locked

            System.out.println("[AppLogger]Screen is locked");
            packagename = "LockScreen";
        }

        else {

            //ActivityManager am =(ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
            //packagename = am.getRunningAppProcesses().get(0).processName;

            packagename = getTopPackage();
        }

        System.out.println(
                "[AlarmReceiver]Build Version:" + Build.VERSION.SDK_INT + "Package Name:" + packagename);
    }
    return packagename;
}

From source file:com.paywith.ibeacon.service.IBeaconService.java

private void processRangeData() {
    // Don Kelley August 2014 (based loosely on original method from Radius)
    // This is the method that does most of the custom paywith magical logic.

    // always check if user logged in before continuing
    if (!getUserLoggedIn()) {
        Log.e("processRangeData() ", "user logged out");
        disableScanning();// w  w  w.ja  v a  2  s  .c om
        return;
    }
    Iterator<Region> regionIterator = rangedRegionState.keySet().iterator();
    while (regionIterator.hasNext()) {
        Region region = regionIterator.next();
        RangeState rangeState = rangedRegionState.get(region);
        if (IBeaconManager.debug)
            Log.d(TAG, "Calling ranging callback");
        //rangeState.getCallback().call(IBeaconService.this, "rangingData", new RangingData(rangeState.finalizeIBeacons(), region));

        //Log.e("iterator",trackedBeacons);
        IBeacon nearest_beacon = findNearest(trackedBeacons);
        Boolean beacon_changed = false;

        if (nearest_beacon == null) {
            //Log.e("nearest_beacon() result","no beacon found");
            // if no paywith beacon nearby, remove any of our notifications.
            // Need this to only happen after several iterations of no beacon found.... 
            noPaywithBeaconCount = noPaywithBeaconCount + 1; // inc the counter and remove notification if higher than 10 cycles

            if (noPaywithBeaconCount > 3) {
                // clear all paywith notifications and launch url... nothing has been found for 10 cycles
                setNextLaunchUrl(null);
                NotificationManager notificationManager = (NotificationManager) getSystemService(
                        Context.NOTIFICATION_SERVICE);
                notificationManager.cancelAll();
                old_locid = 0;
                old_locid2 = 0;
                lastBeaconFound = null;
                lastBeaconFound2 = null;
                lastaction = "cancelAll";
            }
            return;
        }
        noPaywithBeaconCount = 0; // always reset the sequential nobeaconsfound counter once a nearby paywith beacon is found

        Integer m1 = nearest_beacon.getMinor();
        Integer M1 = nearest_beacon.getMajor();
        Integer m2 = 0; // just some safe default settings
        Integer M2 = 0;
        Integer m3 = 0;
        Integer M3 = 0;
        if (lastBeaconFound != null) {
            m2 = lastBeaconFound.getMinor();
            M2 = lastBeaconFound.getMajor();
        }

        if (lastBeaconFound2 != null) {
            m3 = lastBeaconFound2.getMinor();
            M3 = lastBeaconFound2.getMajor();
        }

        //Log.e("service",m1.toString() + " = " + m2.toString() + " = " + m3.toString() + ", " + M1.toString() + " = " + M2.toString() + " = " + M3.toString());
        lastBeaconFound2 = lastBeaconFound;
        lastBeaconFound = nearest_beacon;

        //Log.e("matching?",m1.toString() + " = " + m2.toString() + ", " + M1.toString() + " = " + M2.toString());
        if (!m1.equals(m2) || !M1.equals(M2) || !m2.equals(m3) || !M2.equals(M3)) {
            // simple debouncer queue:
            // We only get past this point if beacon found is same as last beacon found and also the one before that.
            //return;
            // skip this... now that we're reducing the frequency of beacon checks, this will take way too long to happen.
        }

        Integer thisminor = nearest_beacon.getMinor();
        String muuid = nearest_beacon.getProximityUuid();
        Integer mmajor = nearest_beacon.getMajor();
        Integer mminor = nearest_beacon.getMinor();
        Double distance = nearest_beacon.getAccuracy();

        String last_updated_at = null; // need to do the date formatting below.
        String current_datetime = null;
        String beaconurl;
        String beaconname;
        Integer location_id;
        // also need to store results of this api beacon call in sharedprefs and check
        // if data for a found beacon exists there and use that data before making a
        // possibly unneccessary api callback about it.

        // note: I need to do something like this still (from iOS app):

        String format = "yyyy-MM-dd HH:mm:ss Z";
        SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
        //System.out.format("%30s %s\n", format, sdf.format(new Date(0)));
        //sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        current_datetime = sdf.format(new Date(0)); // this will be used for beacon database getUpdatedAt/setUpdatedAt string dates        

        // Set a Beacon Shell object into UserHelper with last updated at of right now
        // so that we do not query for this Beacon again until +24hours since we do not want to overwhelm device
        /*NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:DATE_FORMAT];
        NSString *last_updated_at = [dateFormatter stringFromDate:[NSDate date]];*/
        // the call should include last_updated_at, @"last_updated_at

        // experimenting with storing in my new sqlite db and looking for existing records there before hitting api

        DatabaseHandler db = new DatabaseHandler(this);

        /**
         * CRUD Operations
         * */

        //Log.e("Select:", "Looking for beacon in db..");
        BeaconStore foundBeacon = db.getBeacon(muuid, mmajor, mminor);

        // Read all beacons (just a database demo example - not sure we'll ever need it in our app)
        /*Log.e("Reading: ", "Reading all beacons.."); 
        List<BeaconStore> beacons = db.getAllBeacons();       
                 
        for (BeaconStore cn : beacons) {
        String log = "Id: "+cn.getID()+" ,uuid: " + cn.getUuid() + " ,major: " + cn.getMajor() + " ,minor: " + cn.getMinor();
            // Writing Contacts to log
        Log.e("Beacon: ", log);
        }*/

        // beacon isn't in our phone database so poll api about it
        if (foundBeacon == null) {
            Log.e("Service", "Making API Call");
            //if (distance < 1) {
            // distance handling is done in nearest_beacon() now...
            //Log.e("IBeaconService","*** mminor=" + mminor.toString() + ", distance =" + distance.toString());
            Map<String, String> beaconApiData = runAppAPI("beaconInfoRequest", muuid, mmajor.toString(),
                    mminor.toString());

            //Log.e("Insert: ", "Inserting beacon from api results.."); 
            //String mername = beaconApiData.get("name");
            //Integer locid = Integer.parseInt(beaconApiData.get("location_id"));
            //String url = beaconApiData.get("url");  

            beaconurl = beaconApiData.get("url");
            beaconname = beaconApiData.get("name");
            location_id = Integer.parseInt(beaconApiData.get("location_id"));

            // Insert Beacon
            db.addBeacon(new BeaconStore(muuid, mmajor, mminor, current_datetime, beaconname, location_id,
                    beaconurl));

        } else {

            //Log.e("Service","!*!*! NOT Making API Call - beacon already in our sql db!");

            beaconurl = foundBeacon.getUrl();
            beaconname = foundBeacon.getMerchantName();
            location_id = foundBeacon.getLocationId();
        }

        // Check if database current_datetime for this beacon is older than 1 hour and older than 24 hours.
        // different logic may result based on those values.
        // for example, if greater than 24 hours old, we should still poll the api for updated info about this beacon.
        // 

        //Log.e("ibeaconservice","about to send data to app");
        //Log.e("beaconurl"," " + beaconurl);
        if (beaconurl != null && beaconurl != "signinfailure") {
            // force open app at payment page:
            //Log.e("service","beaconurl = " + beaconurl);
            String previousNotificationUrl = apiInstance.getCurrentLaunchUrl();
            // only generate notification if it's different from the last one
            String notetext = "Pay with your phone";
            notetext = notetext + " at " + beaconname;

            //Log.e("service","lastaction=" + lastaction + ", lastlocationid=" + lastlocationid.toString() + ", location_id=" + location_id.toString());
            //Log.e("locid before N/1/2",location_id+"/"+old_locid+"/"+old_locid2);

            // if location_id has changed from last two sent by a notification in this background service:
            beacon_changed = (location_id.equals(old_locid) && old_locid.equals(old_locid2));
            //Log.e("beacon_changed",beacon_changed.toString());
            //old_locid = location_id;
            PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
            KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
            boolean isScreenOn = powerManager.isScreenOn();
            boolean keyboardLocked = km.inKeyguardRestrictedInputMode();

            if (isForeground("com.paywith.paywith") && isScreenOn && !keyboardLocked) {
                // only if the app is running main on your phone AND phone is currently unlocked

                // only do this if:
                // the last thing this service did was NOT send a location id
                // OR the last thing this service did was NOT send this same location change

                // also add the 3 level debouncer when in foreground to locations list 
                //Log.e("matching?",m1.toString() + " = " + m2.toString() + ", " + M1.toString() + " = " + M2.toString());
                if (!m1.equals(m2) || !M1.equals(M2) || !m2.equals(m3) || !M2.equals(M3)) {
                    // simple debouncer queue:
                    // We only get past this point if beacon found is same as last beacon found and also the one before that.
                    return;
                    // skip this... now that we're reducing the frequency of beacon checks, this will take way too long to happen.
                }
                //if (!lastaction.equals("moveLocationToTop") || 
                //      lastaction.equals("moveLocationToTop") && !lastlocationid.equals(location_id)) {

                //Log.e("service","sending new location to locationlist:" + location_id.toString());
                // tell app to move this location to top of location list if possible
                moveLocationToTop(location_id.toString());
                //}
                //generateNotification("TEST",notetext, beaconurl, location_id.toString());// this generates system notification

                lastaction = "moveLocationToTop";
                scanPeriod = IBeaconManager.DEFAULT_FOREGROUND_SCAN_PERIOD;
                betweenScanPeriod = IBeaconManager.DEFAULT_FOREGROUND_BETWEEN_SCAN_PERIOD;
                //setScanPeriods(scanPeriod,betweenScanPeriod);
                //Log.e("sending intent","locations list order");
            } else if (!lastaction.equals("generateNotification")
                    || lastaction.equals("generateNotification") && !lastlocationid.equals(location_id)) { // add hour timer here also                       
                // && beacon_changed
                // only if app is running in background or not running at all.

                // only do this if:
                // the last thing this service did was NOT send a location id
                // OR the last thing this service did was NOT send this same location change
                // ALSO only notify if this location hasn't been notified within last hour.  (still necessary?  not sure...)
                // (trying without the hour thing for now).

                // simple debouncer targetted at notifications:
                if (!m1.equals(m2) || !M1.equals(M2) || !m2.equals(m3) || !M2.equals(M3)) {
                    //if (m1.equals(m2) && M1.equals(M2) || m1.equals(m3) && M1.equals(M3)) {
                    // logic:  if this beacon was notified within the past 3 cycles, don't notify again.
                    return;
                }

                // generate notification.
                generateNotification("Pay Here", notetext, beaconurl, location_id.toString());// this generates system notification
                setNextLaunchUrl(beaconurl);
                setNextLaunchName(beaconname);
                lastaction = "generateNotification";
                //Log.e("sending intent","*** notification of new location");
                scanPeriod = IBeaconManager.DEFAULT_BACKGROUND_SCAN_PERIOD;
                betweenScanPeriod = IBeaconManager.DEFAULT_BACKGROUND_BETWEEN_SCAN_PERIOD;
                //setScanPeriods(scanPeriod,betweenScanPeriod);
            }
            lastlocationid = location_id;
            //}
            // update location_id queue history
            old_locid2 = old_locid;
            old_locid = location_id;
        }
    }

}

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  ww w . ja va2s  . c o m
    }

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

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