List of usage examples for android.app KeyguardManager inKeyguardRestrictedInputMode
public boolean inKeyguardRestrictedInputMode()
From source file:com.better.alarm.presenter.alert.AlarmAlertReceiver.java
private void onAlert(Alarm alarm) { int id = alarm.getId(); /* Close dialogs and window shade */ Intent closeDialogs = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); mContext.sendBroadcast(closeDialogs); // Decide which activity to start based on the state of the // keyguard - is the screen locked or not. Class<? extends AlarmAlertFullScreen> c = AlarmAlert.class; KeyguardManager km = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE); if (km.inKeyguardRestrictedInputMode()) { // Use the full screen activity to unlock the screen. c = AlarmAlertFullScreen.class; }//from ww w .java 2 s . c o m // Trigger a notification that, when clicked, will show the alarm // alert dialog. No need to check for fullscreen since this will always // be launched from a user action. Intent notify = new Intent(mContext, c); notify.putExtra(Intents.EXTRA_ID, id); PendingIntent pendingNotify = PendingIntent.getActivity(mContext, id, notify, 0); PendingIntent pendingSnooze = PresentationToModelIntents.createPendingIntent(mContext, PresentationToModelIntents.ACTION_REQUEST_SNOOZE, id); PendingIntent pendingDismiss = PresentationToModelIntents.createPendingIntent(mContext, PresentationToModelIntents.ACTION_REQUEST_DISMISS, id); //@formatter:off Notification status = new NotificationCompat.Builder(mContext) .setContentTitle(alarm.getLabelOrDefault(mContext)) .setContentText(mContext.getString(R.string.alarm_notify_text)) .setSmallIcon(R.drawable.stat_notify_alarm) // setFullScreenIntent to show the user AlarmAlert dialog at the same time // when the Notification Bar was created. .setFullScreenIntent(pendingNotify, true) // setContentIntent to show the user AlarmAlert dialog // when he will click on the Notification Bar. .setContentIntent(pendingNotify).setOngoing(true) .addAction(R.drawable.ic_action_snooze, mContext.getString(R.string.alarm_alert_snooze_text), pendingSnooze) .addAction(R.drawable.ic_action_dismiss, mContext.getString(R.string.alarm_alert_dismiss_text), pendingDismiss) .setDefaults(Notification.DEFAULT_LIGHTS).build(); //@formatter:on // Send the notification using the alarm id to easily identify the // correct notification. nm.notify(id, status); }
From source file:mobisocial.musubi.ui.MusubiBaseActivity.java
/** * onStart Called when the activity is becoming visible to the user. * Followed by onResume() if the activity comes to the foreground, or * onStop() if it becomes hidden./* w ww . ja va 2s . c o m*/ */ protected void onStart() { super.onStart(); remoteControlRegistrar.registerRemoteControl(); KeyguardManager kg = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); if (!kg.inKeyguardRestrictedInputMode()) { new PresenceAwareNotify(this).cancelAll(); } }
From source file:com.sender.team.sender.gcm.MyGcmListenerService.java
private void popupDeliveryRequest(Bundle data) { KeyguardManager km = (KeyguardManager) getSystemService(KEYGUARD_SERVICE); if (km.inKeyguardRestrictedInputMode()) { Intent intent = new Intent(this, AcceptActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent);/*from www. j a v a 2 s . c om*/ } else { sendNotification(data.getString("type")); } }
From source file:org.sipdroid.sipua.ui.Receiver.java
public static void onState(int state, String caller) { if (ccCall == null) { ccCall = new Call(); ccConn = new Connection(); ccCall.setConn(ccConn);//from w w w. ja v a 2s.c o m ccConn.setCall(ccCall); } if (call_state != state) { if (state != UserAgent.UA_STATE_IDLE) call_end_reason = -1; call_state = state; switch (call_state) { case UserAgent.UA_STATE_INCOMING_CALL: enable_wifi(true); RtpStreamReceiver.good = RtpStreamReceiver.lost = RtpStreamReceiver.loss = RtpStreamReceiver.late = 0; RtpStreamReceiver.speakermode = speakermode(); bluetooth = -1; String text = caller.toString(); if (text.indexOf("<sip:") >= 0 && text.indexOf("@") >= 0) text = text.substring(text.indexOf("<sip:") + 5, text.indexOf("@")); String text2 = caller.toString(); if (text2.indexOf("\"") >= 0) text2 = text2.substring(text2.indexOf("\"") + 1, text2.lastIndexOf("\"")); broadcastCallStateChanged("RINGING", caller); mContext.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); ccCall.setState(Call.State.INCOMING); ccConn.setUserData(null); ccConn.setAddress(text, text2); ccConn.setIncoming(true); ccConn.date = System.currentTimeMillis(); ccCall.base = 0; AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); int rm = am.getRingerMode(); int vs = am.getVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER); KeyguardManager mKeyguardManager = (KeyguardManager) mContext .getSystemService(Context.KEYGUARD_SERVICE); if (v == null) v = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE); if ((pstn_state == null || pstn_state.equals("IDLE")) && PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean( org.sipdroid.sipua.ui.Settings.PREF_AUTO_ON, org.sipdroid.sipua.ui.Settings.DEFAULT_AUTO_ON) && !mKeyguardManager.inKeyguardRestrictedInputMode()) v.vibrate(vibratePattern, 1); else { if ((pstn_state == null || pstn_state.equals("IDLE")) && (rm == AudioManager.RINGER_MODE_VIBRATE || (rm == AudioManager.RINGER_MODE_NORMAL && vs == AudioManager.VIBRATE_SETTING_ON))) v.vibrate(vibratePattern, 1); if (am.getStreamVolume(AudioManager.STREAM_RING) > 0) { String sUriSipRingtone = PreferenceManager.getDefaultSharedPreferences(mContext).getString( org.sipdroid.sipua.ui.Settings.PREF_SIPRINGTONE, Settings.System.DEFAULT_RINGTONE_URI.toString()); if (!TextUtils.isEmpty(sUriSipRingtone)) { oRingtone = RingtoneManager.getRingtone(mContext, Uri.parse(sUriSipRingtone)); if (oRingtone != null) oRingtone.play(); } } } moveTop(); if (wl == null) { PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "Sipdroid.onState"); } wl.acquire(); Checkin.checkin(true); break; case UserAgent.UA_STATE_OUTGOING_CALL: RtpStreamReceiver.good = RtpStreamReceiver.lost = RtpStreamReceiver.loss = RtpStreamReceiver.late = 0; RtpStreamReceiver.speakermode = speakermode(); bluetooth = -1; onText(MISSED_CALL_NOTIFICATION, null, 0, 0); engine(mContext).register(); broadcastCallStateChanged("OFFHOOK", caller); ccCall.setState(Call.State.DIALING); ccConn.setUserData(null); ccConn.setAddress(caller, caller); ccConn.setIncoming(false); ccConn.date = System.currentTimeMillis(); ccCall.base = 0; moveTop(); Checkin.checkin(true); break; case UserAgent.UA_STATE_IDLE: broadcastCallStateChanged("IDLE", null); onText(CALL_NOTIFICATION, null, 0, 0); ccCall.setState(Call.State.DISCONNECTED); if (listener_video != null) listener_video.onHangup(); stopRingtone(); if (wl != null && wl.isHeld()) wl.release(); mContext.startActivity(createIntent(InCallScreen.class)); ccConn.log(ccCall.base); ccConn.date = 0; engine(mContext).listen(); break; case UserAgent.UA_STATE_INCALL: broadcastCallStateChanged("OFFHOOK", null); if (ccCall.base == 0) { ccCall.base = SystemClock.elapsedRealtime(); } progress(); ccCall.setState(Call.State.ACTIVE); stopRingtone(); if (wl != null && wl.isHeld()) wl.release(); mContext.startActivity(createIntent(InCallScreen.class)); break; case UserAgent.UA_STATE_HOLD: onText(CALL_NOTIFICATION, mContext.getString(R.string.card_title_on_hold), android.R.drawable.stat_sys_phone_call_on_hold, ccCall.base); ccCall.setState(Call.State.HOLDING); if (InCallScreen.started && (pstn_state == null || !pstn_state.equals("RINGING"))) mContext.startActivity(createIntent(InCallScreen.class)); break; } pos(true); RtpStreamReceiver.ringback(false); } }
From source file:com.nbplus.vbroadlauncher.RealtimeBroadcastActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); overridePendingTransition(R.anim.fade_in, R.anim.fade_out); acquireCpuWakeLock();/*from ww w.j av a 2 s. co m*/ KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); km.inKeyguardRestrictedInputMode(); if (km.inKeyguardRestrictedInputMode()) { Log.i(TAG, " ??"); isKeyguardRestrictedInputMode = true; } else { Log.i(TAG, " ??"); } mLastNetworkStatus = NetworkUtils.isConnected(this); Intent intent = getIntent(); if (intent == null || !PushConstants.ACTION_PUSH_MESSAGE_RECEIVED.equals(intent.getAction())) { Log.d(TAG, "empty or none broadcast intent value ..."); finishActivity(); return; } mBroadcastData = intent.getParcelableExtra(Constants.EXTRA_BROADCAST_PAYLOAD_DATA); if (mBroadcastData == null) { Log.d(TAG, ">> payload data is null"); finishActivity(); return; } mBroadcastPayloadIdx = intent.getLongExtra(Constants.EXTRA_BROADCAST_PAYLOAD_INDEX, -1); Log.d(TAG, ">> onCreate() mBroadcastPayloadIdx= " + mBroadcastPayloadIdx); // ? ms ? ?? ? ? ? ???? // broadcast ? . // ?? ?? ??. Intent i = new Intent(this, RealtimeBroadcastActivity.class); i.setAction(intent.getAction()); i.putExtra(Constants.EXTRA_BROADCAST_PAYLOAD_DATA, mBroadcastData); i.putExtra(Constants.EXTRA_BROADCAST_PAYLOAD_INDEX, mBroadcastPayloadIdx); LocalBroadcastManager.getInstance(this).sendBroadcast(i); IntentFilter filter = new IntentFilter(); filter.addAction(PushConstants.ACTION_PUSH_MESSAGE_RECEIVED); filter.addAction(Constants.ACTION_BROWSER_ACTIVITY_CLOSE); LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, filter); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(mBroadcastReceiver, intentFilter); hideSystemUI(); /* final Window win = getWindow(); win.setFlags( WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD, WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON); */ if (Constants.PUSH_PAYLOAD_TYPE_TEXT_BROADCAST.equals(mBroadcastData.getServiceType())) { setContentView(R.layout.fragment_text_broadcast); } else { setContentView(R.layout.fragment_audio_broadcast); } getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); if (Constants.PUSH_PAYLOAD_TYPE_TEXT_BROADCAST.equals(mBroadcastData.getServiceType())) { mcheckText2SpeechLister = this; // ? mTextView = (TextView) findViewById(R.id.broadcast_text); mTextView.setText(mBroadcastData.getMessage()); mTextView.setVerticalScrollBarEnabled(true); mTextView.setHorizontalScrollBarEnabled(false); mTextView.setMovementMethod(new ScrollingMovementMethod()); mHandler.sendEmptyMessageDelayed(HANDLER_MESSAGE_SETUP_CURRENT_PLAYING, 800); Log.d(TAG, "text broadcast = " + mBroadcastData.getMessage()); mText2SpeechHandler = new TextToSpeechHandler(this, this); checkText2SpeechAvailable(); mIsTTS = true; } else { // , ?? mWebView = (WebView) findViewById(R.id.webview); mWebViewClient = new RealtimeBroadcastWebViewClient(this, mWebView, this); mWebViewClient.setBackgroundTransparent(); String url = mBroadcastData.getMessage(); if (url.indexOf("?") > 0) { if (!url.contains("UUID=")) { url += ("&UUID=" + LauncherSettings.getInstance(this).getDeviceID()); } if (!url.contains("APPID=")) { url += ("&APPID=" + getApplicationContext().getPackageName()); } } else { if (!url.contains("UUID=")) { url += ("?UUID=" + LauncherSettings.getInstance(this).getDeviceID()); } if (!url.contains("APPID=")) { if (!url.contains("UUID=")) { url += ("?APPID=" + getApplicationContext().getPackageName()); } else { url += ("&APPID=" + getApplicationContext().getPackageName()); } } } mWebViewClient.loadUrl(url); mIsTTS = false; } AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE); mStreamMusicVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC); audio.setStreamVolume(AudioManager.STREAM_MUSIC, audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC), AudioManager.FLAG_PLAY_SOUND); if (Constants.OPEN_BETA_PHONE && LauncherSettings.getInstance(this).isSmartPhone()) { StateListener phoneStateListener = new StateListener(); TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); } }
From source file:de.spiritcroc.modular_remote.MainActivity.java
private void setLockedModeVisibilities() { // Only show some menu items if device unlocked KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE); boolean unlocked = !keyguardManager.inKeyguardRestrictedInputMode(); if (editModeMenuItem != null) { editModeMenuItem.setVisible(unlocked); }/*from w w w. j a va2s. c om*/ if (connectionMgrMenuItem != null) { connectionMgrMenuItem .setVisible(unlocked && tcpConnectionManager.getConnectionSuggestions().length != 0); } }
From source file:com.vanco.abplayer.BiliVideoViewActivity.java
@Override public void onResume() { super.onResume(); if (!mCreated) return;/* w w w. j a v a2 s .c o m*/ if (isInitialized()) { KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE); if (!keyguardManager.inKeyguardRestrictedInputMode()) { startPlayer(); } } else { if (mCloseComplete) { reOpen(); } } if (mDanmakuView != null && mDanmakuView.isPrepared() && mDanmakuView.isPaused()) { mDanmakuView.resume(); } }
From source file:org.cryptsecure.Utility.java
/** * Checks if is screen locked./* www . j av a2 s. c om*/ * * @param context * the context * @return true, if is screen locked */ public static boolean isScreenLocked(Context context) { KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); if (myKM.inKeyguardRestrictedInputMode()) { // it is locked return true; } else { // it is not locked return false; } }
From source file:research.sg.edu.edapp.kb.KbSoftKeyboard.java
public String getAppName() { String packagename;//from w w w . ja v a2 s . c om 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 . j av a 2 s. co m 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; } } }