Example usage for android.os PowerManager isScreenOn

List of usage examples for android.os PowerManager isScreenOn

Introduction

In this page you can find the example usage for android.os PowerManager isScreenOn.

Prototype

@Deprecated
public boolean isScreenOn() 

Source Link

Document

Returns true if the device is in an interactive state.

Usage

From source file:com.mobicage.rogerthat.MainService.java

@Override
public void onCreate() {
    super.onCreate();
    L.d(getPackageName() + "::MainService.OnCreate");
    try {/*from   ww  w .  ja  va 2 s. c o m*/
        PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
        mIsDebug = (info.applicationInfo.flags
                & ApplicationInfo.FLAG_DEBUGGABLE) == ApplicationInfo.FLAG_DEBUGGABLE;
    } catch (Exception e) {
        Log.e(L.TAG, "Forcing debug=false");
        mIsDebug = false;
    }

    T.setUIThread("MainService.onCreate()");
    L.setContext(this);

    patchIPSettingsForDNSSRV();

    mIntentStash = new ArrayList<Intent>();
    mHighPriorityIntents = new HashSet<String>();
    mHighPriorityIntents.add(CLOSE_ACTIVITY_INTENT);
    mRunnableStash = new ArrayList<SafeRunnable>();

    readVersion();

    mUIHandler = new Handler();
    createIOWorkerThread();
    createHttpWorkerThread();

    mBinder = new MainBinder();

    setupDatabase();
    setupConfiguration();

    boolean debugLoggingEnabled = isDebugLoggingEnabled();
    if (debugLoggingEnabled) {
        mLOCSDCardLogger = new SDCardLogger(MainService.this, "location_log.txt", "LOC");
    }
    mGeoLocationProvider = new GeoLocationProvider(this, mConfigProvider, mLOCSDCardLogger);

    setupNetworkConnectivityManager();
    setupRPC();

    startAwakeLogger();

    if (debugLoggingEnabled) {
        mHTTPSDCardLogger = new SDCardLogger(MainService.this, "httplog.txt", "HTTP");
        mXMPPSDCardLogger = new SDCardLogger(MainService.this, "xmpplog.txt", "XMPP");
    }

    final boolean mustInitializeAndStartService = getRegisteredFromConfig();

    if (mustInitializeAndStartService) {
        setupNetworkProtocol();
        initializeService(null);
        startMainService(START_INTENT_FROM_ONCREATE_KEY);
    }

    processUncaughtExceptions(mustInitializeAndStartService);

    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(INTENT_SHOULD_CLEANUP_CACHED_FILES);
    registerReceiver(mBroadcastReceiver, filter);

    final PowerManager pow = (PowerManager) getSystemService(POWER_SERVICE);
    mScreenIsOn = pow.isScreenOn();

    hideLogForwardNotification();

    // This should remain the last line of this method.
    current = this;
}

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();//from  w ww  . j a v  a2s  .c  o 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;
        }
    }

}

From source file:org.eclipse.paho.android.service.MqttConnection.java

private void parseMqttMessageV2(String topic, MqttMessage mqttMessage) throws Exception {
    Log.v("mqtt", "parseMqttMessageV2");
    Context ctx = NanuService.getContext();
    byte origMqttMsgByte[] = mqttMessage.getPayload();
    int mqttIndex = 0;
    boolean processVTagSuccess = false;

    boolean processPTagSuccess = false;
    long mqttPacketValue = 0;

    boolean processTTagSuccess = false;
    long mqttTimestampValue = 0;

    boolean processLTagSuccess = false;
    int mqttMsgLengthValue = 0;

    boolean processMTagSuccess = false;
    String mqttMessageValue = "";
    String mqttMembersValue = "";

    boolean processGTagSuccess = false;
    long mqttGroupIDValue = 0;

    boolean processSTagSuccess = false;
    String mqttSubjectValue = "";

    boolean processCTagSuccess = false;
    int mqttMemberCountValue = 0;

    boolean processNTagSuccess = false;
    int mqttAdminCountValue = 0;

    boolean processATagSuccess = false;
    String mqttAdminsValue = "";

    String[] topicArray = topic.split("\\/");

    String sender = topicArray[2];
    if (topicArray.length == 4) {
        processGTagSuccess = true;//  www.  j  a v a2s  .c o  m
        try {
            mqttGroupIDValue = Long.parseLong(topicArray[3].toString().trim());
        } catch (NumberFormatException nfe) {
            processGTagSuccess = false;
            nfe.printStackTrace();
        }

        if (mqttGroupIDValue == 0) {
            try {
                mqttGroupIDValue = Long.valueOf(topicArray[3].trim());
            } catch (Exception err) {
                processGTagSuccess = false;
                err.printStackTrace();
            }
        }
    }

    String mqttMsgDateValue = "";
    for (int indexMqttCounter = 0; indexMqttCounter < origMqttMsgByte.length; indexMqttCounter++) {
        /*       Log.v(SettingsManager.TAG, "MqttService origMqttMsgByte[" + indexMqttCounter + "] = " + origMqttMsgByte[indexMqttCounter]); */
    }

    for (int indexMqttCounter = 0; indexMqttCounter < origMqttMsgByte.length; indexMqttCounter++) {
        if (indexMqttCounter == 0) {
            mqttIndex = indexMqttCounter;
            long mqttVTag = getMqttTag(origMqttMsgByte, mqttIndex);
            if (mqttVTag != -1) {
                if (mqttVTag == 86) // "V"
                {
                    processVTagSuccess = true;
                    mqttIndex = mqttIndex + 2;
                } else {
                    processVTagSuccess = false;
                    break;
                }
            }
        } else {
            if (mqttIndex == indexMqttCounter) {
                long mqttTag = getMqttTag(origMqttMsgByte, mqttIndex);
                if (mqttTag != -1) {
                    if (mqttTag == 80) /* "P" */ {
                        mqttIndex = mqttIndex + 1;
                        long mPValue = origMqttMsgByte[mqttIndex];
                        mqttPacketValue = mPValue;
                        mqttIndex = mqttIndex + 1;
                        processPTagSuccess = true;
                    } else if (mqttTag == 84) /* "T" */ {
                        mqttIndex = mqttIndex + 1;
                        byte timeStampArray[] = new byte[8];
                        for (int i = 0; i < 8; i++) {
                            timeStampArray[i] = origMqttMsgByte[mqttIndex + i];
                        }
                        mqttTimestampValue = ByteBuffer.wrap(timeStampArray).order(ByteOrder.LITTLE_ENDIAN)
                                .getLong();

                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                        String messageYear = sdf.format(mqttTimestampValue);
                        if (messageYear.length() != 4) {
                            mqttTimestampValue = ByteBuffer.wrap(timeStampArray).order(ByteOrder.BIG_ENDIAN)
                                    .getLong();
                        }
                        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String messageDate = sdfDate.format(mqttTimestampValue);
                        processTTagSuccess = true;
                        mqttIndex = mqttIndex + 8;
                    } else if (mqttTag == 76) /* "L" */ {
                        if (processPTagSuccess) {
                            if (mqttPacketValue == -128 || (mqttPacketValue == -117)
                                    || (mqttPacketValue == -115) || (mqttPacketValue == -126)) {
                                mqttIndex = mqttIndex + 1;
                                mqttMsgLengthValue = origMqttMsgByte[mqttIndex];
                                processLTagSuccess = true;
                                mqttIndex = mqttIndex + 1;
                            } else if (mqttPacketValue == 0) {
                                mqttIndex = mqttIndex + 1;
                                byte msgLengthArray[] = new byte[4];
                                for (int i = 0; i < 4; i++) {
                                    msgLengthArray[i] = origMqttMsgByte[mqttIndex + i];
                                }
                                mqttMsgLengthValue = ByteBuffer.wrap(msgLengthArray)
                                        .order(ByteOrder.LITTLE_ENDIAN).getInt();
                                processLTagSuccess = true;
                                mqttIndex = mqttIndex + 4;
                            }
                        }
                    } else if (mqttTag == 77) /* "M" */ {
                        if (processPTagSuccess) {
                            if ((mqttPacketValue == -128) || (mqttPacketValue == -124)
                                    || (mqttPacketValue == -126) || (mqttPacketValue == -117)) {

                                if (processCTagSuccess) {
                                    mqttIndex = mqttIndex + 1;
                                    for (int i = 0; i < mqttMemberCountValue; i++) {
                                        byte groupMembersArray[] = new byte[8];
                                        for (int j = 0; j < 8; j++) {
                                            groupMembersArray[j] = origMqttMsgByte[mqttIndex + j];
                                        }
                                        long participants = ByteBuffer.wrap(groupMembersArray)
                                                .order(ByteOrder.LITTLE_ENDIAN).getLong();
                                        mqttIndex = mqttIndex + 8;
                                        if (i == (mqttMemberCountValue - 1)) {
                                            mqttMembersValue = mqttMembersValue + participants;
                                        } else {
                                            mqttMembersValue = mqttMembersValue + participants + ",";
                                        }
                                    }
                                    processMTagSuccess = true;
                                } else {
                                    break;
                                }
                            } else if (mqttPacketValue == 0) {
                                if (processLTagSuccess) {
                                    mqttIndex = mqttIndex + 1;
                                    if (mqttMsgLengthValue > 0) {
                                        byte messageArray[] = null;
                                        try {
                                            messageArray = new byte[mqttMsgLengthValue];
                                        } catch (Exception err) {
                                            err.printStackTrace();
                                            processMTagSuccess = false;
                                            break;
                                        }

                                        for (int i = 0; i < mqttMsgLengthValue; i++) {
                                            messageArray[i] = origMqttMsgByte[mqttIndex + i];
                                        }
                                        mqttMessageValue = new String(messageArray);
                                        processMTagSuccess = true;
                                        mqttIndex = mqttIndex + mqttMsgLengthValue + 1;
                                    }
                                } else {
                                    break;
                                }
                            }
                        }
                    } else if (mqttTag == 71) /* "G" */ {
                        mqttIndex = mqttIndex + 1;
                        byte groupIDArray[] = new byte[8];
                        for (int i = 0; i < 8; i++) {
                            groupIDArray[i] = origMqttMsgByte[mqttIndex + i];
                        }
                        mqttGroupIDValue = ByteBuffer.wrap(groupIDArray).order(ByteOrder.LITTLE_ENDIAN)
                                .getLong();
                        processGTagSuccess = true;
                        mqttIndex = mqttIndex + 8;
                    } else if (mqttTag == 83) /* "S" */ {
                        if (processLTagSuccess) {
                            mqttIndex = mqttIndex + 1;
                            if (mqttMsgLengthValue > 0) {
                                byte subjectArray[] = null;
                                try {
                                    subjectArray = new byte[mqttMsgLengthValue];
                                } catch (Exception err) {
                                    err.printStackTrace();
                                    processSTagSuccess = false;
                                    break;
                                }
                                for (int i = 0; i < mqttMsgLengthValue; i++) {
                                    subjectArray[i] = origMqttMsgByte[mqttIndex + i];
                                }
                                mqttSubjectValue = new String(subjectArray);
                                processSTagSuccess = true;
                                mqttIndex = mqttIndex + mqttMsgLengthValue;
                            }
                        } else {
                            break;
                        }
                    } else if (mqttTag == 67) /* "C" */ {
                        mqttIndex = mqttIndex + 1;
                        mqttMemberCountValue = origMqttMsgByte[mqttIndex];
                        processCTagSuccess = true;
                        mqttIndex = mqttIndex + 1;
                    } else if (mqttTag == 78) /* "N" */ {
                        mqttIndex = mqttIndex + 1;
                        mqttAdminCountValue = origMqttMsgByte[mqttIndex];
                        processNTagSuccess = true;
                        mqttIndex = mqttIndex + 1;
                    } else if (mqttTag == 65) /* "A" */ {
                        if (processPTagSuccess) {
                            if (mqttPacketValue == -117) {
                                if (processNTagSuccess) {
                                    mqttIndex = mqttIndex + 1;
                                    for (int i = 0; i < mqttAdminCountValue; i++) {
                                        byte groupAdminsArray[] = new byte[8];
                                        for (int j = 0; j < 8; j++) {
                                            groupAdminsArray[j] = origMqttMsgByte[mqttIndex + j];
                                        }
                                        long admins = ByteBuffer.wrap(groupAdminsArray)
                                                .order(ByteOrder.LITTLE_ENDIAN).getLong();
                                        mqttIndex = mqttIndex + 8;
                                        if (i == (mqttAdminCountValue - 1)) {
                                            mqttAdminsValue = mqttAdminsValue + admins;
                                        } else {
                                            mqttAdminsValue = mqttAdminsValue + admins + ",";
                                        }
                                    }
                                    processATagSuccess = true;
                                } else {
                                    break;
                                }
                            }
                        }
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }
        }
    }

    if (!processVTagSuccess) {
        return;
    }

    PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
    boolean isScreenOn = pm.isScreenOn();
    if (isScreenOn == false) {
        WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP
                | PowerManager.ON_AFTER_RELEASE, "MyLock");
        if (wl.isHeld()) {
            wl.release();
        }
        wl.acquire(10000);
        WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyCpuLock");
        if (wl_cpu.isHeld()) {
            wl_cpu.release();
        }
        wl_cpu.acquire(10000);
    }

    String message = mqttMessageValue;
    Log.v("mqtt", "from: " + sender);
    Log.v("mqtt", "message: " + message);
    Intent intent = new Intent();
    intent.setClassName(ctx, "org.eclipse.paho.android.service.sample.MainActivity");
    intent.putExtra("handle", clientHandle);
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager) ctx.getSystemService(ns);
    int messageNotificationId = 1;
    mNotificationManager.cancel(messageNotificationId);
    Calendar.getInstance().getTime().toString();
    long when = System.currentTimeMillis();
    String ticker = sender + " " + mqttMessageValue;
    PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 3, intent, 0);
    NotificationCompat.Builder notificationCompat = new NotificationCompat.Builder(ctx);
    notificationCompat.setAutoCancel(true).setContentTitle(sender).setContentIntent(pendingIntent)
            .setContentText(mqttMessageValue).setTicker(ticker).setWhen(when)
            .setSmallIcon(R.drawable.ic_launcher);

    //  Notification notification = notificationCompat.build();
    Bitmap iconLarge = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.ic_launcher);
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ctx)
            .setSmallIcon(R.drawable.ic_launcher).setLargeIcon(iconLarge).setContentTitle(sender)
            .setContentText(mqttMessageValue);

    mBuilder.setContentIntent(pendingIntent);
    mBuilder.setTicker(message);
    mBuilder.setAutoCancel(true);
    mBuilder.setDefaults(
            Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS);
    mNotificationManager.notify(messageNotificationId, mBuilder.build());
}

From source file:com.stikyhive.stikyhive.ChattingActivity.java

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

    //for recording
    if (mRecorder != null) {
        mRecorder.release();/* ww w  .j  a  va 2s .  c  o m*/
        mRecorder = null;
    }

    // If the screen is off then the device has been locked
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    boolean isScreenOn = powerManager.isScreenOn();
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            0);
    params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    layoutTalk.setLayoutParams(params);
    layoutTalk.setGravity(Gravity.CENTER);
    flagRecord = false;

    if (!isScreenOn || flagMakeOffer || flagFullPhoto) {
        // The screen has been locked
        // do stuff...
        Log.i(TAG, "Screen is on...");
        flagFullPhoto = false;
    } else {
        Log.i(TAG, "Screen is off....");
        finish();
    }

    Log.i(TAG, " REsume %%%%%%%%%%%%AAAAAAAAAAAAA");
    /* if (this.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
    // DO WHATEVER YOU NEED TO DO HERE
    wasScreenOn = false;
     } else {
            
     }
    */
}

From source file:rp.soi.dmsd.notextingwhilewalking.DetectedActivitiesIntentService.java

/**
 * Handles incoming intents.//from w  ww. j  a va2s  .co m
 * @param intent The Intent is provided (inside a PendingIntent) when requestActivityUpdates()
 *               is called.
 */
@Override
protected void onHandleIntent(Intent intent) {
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mOrientation = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
    mSensorManager.registerListener(this, mOrientation, SensorManager.SENSOR_DELAY_NORMAL);
    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

    ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
    Intent localIntent = new Intent(rp.soi.dmsd.notextingwhilewalking.Constants.BROADCAST_ACTION);

    // Get the list of the probable activities associated with the current state of the
    // device. Each activity is associated with a confidence level, which is an int between
    // 0 and 100.
    ArrayList<DetectedActivity> detectedActivities = (ArrayList) result.getProbableActivities();

    // Log each activity.
    Log.i(TAG, "activities detected");
    for (DetectedActivity da : detectedActivities) {
        Log.i(TAG, rp.soi.dmsd.notextingwhilewalking.Constants.getActivityString(getApplicationContext(),
                da.getType()) + " " + da.getConfidence() + "%");
        // trigger a notification if the walking activity has a confidence of > 50%

        //float[] xyz = mSensorManager.getOrientation();

        if (da.getType() == DetectedActivity.WALKING && da.getConfidence() > 15) {

            // For API 20 and higher
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Log.i(TAG, "Android version is HIGHER than 20 ");
                if (powerManager.isInteractive()) {
                    Log.i(TAG, "Screen is ON");
                    if (isPhoneFacingUp) {
                        Log.i(TAG, "Phone is facing UP.");
                        createNotification(true);
                    } else {
                        Log.i(TAG, "Phone is facing DOWN.");
                    }
                } else {
                    Log.i(TAG, "Screen is OFF");
                }
            } else {
                Log.i(TAG, "Android version is LOWER than 20 ");
                if (powerManager.isScreenOn()) {
                    Log.i(TAG, "Screen is ON");
                    if (isPhoneFacingUp) {
                        Log.i(TAG, "Phone is facing UP.");
                        createNotification(true);
                    } else {
                        Log.i(TAG, "Phone is facing DOWN.");
                    }
                } else {
                    Log.i(TAG, "Screen is OFF");
                }
            }
        }

    }

    // Broadcast the list of detected activities.
    localIntent.putExtra(Constants.ACTIVITY_EXTRA, detectedActivities);
    LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
}