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:jp.morihirosoft.twwb.TwwbService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (DEBUG)/* w  ww.  j a v a2s  .  c o m*/
        Log.d(TAG, "onStartCommand: intent=" + intent);
    registerReceivers();
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    if (pm.isScreenOn()) {
        startRecognition();
    }
    return super.onStartCommand(intent, flags, startId);
}

From source file:fr.inria.ucn.collectors.SysStateCollector.java

/**
 * // w w w.  j  a  v a2  s  .  c o m
 * @param c
 * @param ts
 * @param change
 */
@SuppressLint("NewApi")
public void run(Context c, long ts, boolean change) {
    try {
        JSONObject data = new JSONObject();
        data.put("on_screen_state_change", change); // this collection run was triggered by screen state change

        data.put("hostname", Helpers.getSystemProperty("net.hostname", "unknown hostname"));
        data.put("current_timezone", Time.getCurrentTimezone());

        // general memory state
        ActivityManager am = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE);
        MemoryInfo mi = new MemoryInfo();
        am.getMemoryInfo(mi);

        JSONObject mem = new JSONObject();
        mem.put("available", mi.availMem);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            mem.put("total", mi.totalMem);
        }
        mem.put("is_low", mi.lowMemory);
        data.put("memory", mem);

        // screen state
        PowerManager pm = (PowerManager) c.getSystemService(Context.POWER_SERVICE);
        data.put("screen_on", pm.isScreenOn());

        // battery state
        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent battery = c.registerReceiver(null, ifilter);
        int level = battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = battery.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        float pct = (float) (100.0 * level) / scale;
        int status = battery.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging = (status == BatteryManager.BATTERY_STATUS_CHARGING
                || status == BatteryManager.BATTERY_STATUS_FULL);
        int chargePlug = battery.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

        JSONObject batt = new JSONObject();
        batt.put("level", level);
        batt.put("scale", scale);
        batt.put("pct", pct);
        batt.put("is_charging", isCharging);
        batt.put("usb_charge", usbCharge);
        batt.put("ac_charge", acCharge);
        data.put("battery", batt);

        // some proc stats
        data.put("cpu", getCpuStat());
        data.put("loadavg", getLoadStat());
        data.put("uptime", getUptimeStat());

        // audio state
        data.put("audio", getAudioState(c));

        // done
        Helpers.sendResultObj(c, "system_state", ts, data);

    } catch (JSONException jex) {
        Log.w(Constants.LOGTAG, "failed to create json object", jex);
    }
}

From source file:ti.modules.titanium.android.notificationmanager.NotificationManagerModule.java

@Kroll.method
public void notify(int id, Object notificationValue) {
    NotificationProxy notificationProxy = NotificationProxy.fromObject(notificationValue);
    NotificationManager manager = getManager();
    if (manager != null && notificationProxy != null) {
        // targeting Android O or above? create default channel

        try {/*w w w . j a  v a 2s . c o m*/
            notificationProxy.setCurrentId(id);
            Notification notification = notificationProxy.getNotification();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
                    && notification.getChannelId() == DEFAULT_CHANNEL_ID) {
                useDefaultChannel();
            }
            getManager().notify(id, notification);
            HashMap wakeParams = notificationProxy.getWakeParams();
            if (wakeParams != null) {
                int wakeTime = TiConvert.toInt(wakeParams.get("time"), 3000);
                int wakeFlags = TiConvert.toInt(wakeParams.get("flags"), (PowerManager.FULL_WAKE_LOCK
                        | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE));
                PowerManager pm = (PowerManager) TiApplication.getInstance()
                        .getSystemService(TiApplication.getInstance().getApplicationContext().POWER_SERVICE);
                if (pm != null && !pm.isScreenOn()) {
                    try {
                        WakeLock wl = pm.newWakeLock(wakeFlags, "TiWakeLock");
                        wl.acquire(wakeTime);
                    } catch (IllegalArgumentException e) {
                        Log.e(TAG, e.getMessage());
                    }
                }
            }
        } catch (Exception e) {

        }
    }
}

From source file:org.protocoderrunner.base.BaseActivity.java

public boolean isScreenOn() {
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    return pm.isScreenOn();

}

From source file:com.wifiafterconnect.WifiAuthenticator.java

protected void requestUserParams(ParsedHttpInput parsedPage) {

    debug("Need user input for authentication credentials.");

    if (getContext() == null) {
        error("Context is not set - cannot start WifiAuthenticationActivity");
        return;//w  w w . j a v a2 s  .c o m
    }
    // Need to check that screen is not off:
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    if (!pm.isScreenOn()) {
        /** Screen is Off
         * if Disable Wifi is enabled :  
         *    1) Disable wifi (if configured).
         *    2) Post notification with intent to re-enable wifi.
         * otherwise : 
         *  setup Broadcast receiver waiting for SCREEN_ON event, 
         *  which will restart the service on wake-up if wifi is still connected. 
         *  Don't just want to pop the Activity and let it sit there, 
         *  as Wifi may get disconnected and device moved to another location meanwhile 
         **/
        boolean disableWifiOnLock = prefs.getAutoDisableWifi();

        debug("Screen is off and disableWifiOnLock is " + disableWifiOnLock);

        if (disableWifiOnLock) {
            WifiTools.disableWifi(getContext());
            notifyWifiDisabled();
        } else {
            ScreenOnReceiver.register(getContext());
            // don't want to receive repeat notifications - will re-enable when screen comes on
            WifiBroadcastReceiver.setEnabled(getContext(), false);
        }
    } else {
        debug("Screen is on - Starting new activity.");
        /**
         *  Screen is On - so proceeding displaying activity asking for credentials.
         */
        Intent intent = makeIntent(WifiAuthenticatorActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(OPTION_URL, parsedPage.getURL().toString());
        intent.putExtra(OPTION_PAGE, parsedPage.getHtml());
        toIntent(intent);
        debug("Starting activity for intent:" + intent.toString());
        startActivity(intent);
    }
}

From source file:com.yangtsaosoftware.pebblemessenger.services.NotificationService.java

@Override
public void onNotificationPosted(StatusBarNotification sbn) {
    if (sbn == null)
        return;/*from  w w w . jav  a  2 s  . com*/
    Constants.log(LOG_TAG, "New Access Event:" + sbn.getPackageName() + " tag:" + sbn.getTag());
    /*if(event.getEventType()!= AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED){
            
    return;
    }
    */
    PowerManager powMan = (PowerManager) this.getSystemService(POWER_SERVICE);
    if (!notifScreenOn && powMan.isScreenOn()) {
        Constants.log(LOG_TAG, "because screen out!");
        return;
    }
    //Parcelable parcelable=event.getParcelableData();
    //if(!(parcelable instanceof Notification)) return;
    Notification notif = sbn.getNotification();
    if (sbn.isOngoing()) {
        Constants.log(LOG_TAG, "because is Ongoing!");
        return;
    }

    String eventPackageName;

    if (sbn.getPackageName() != null) {
        eventPackageName = sbn.getPackageName();
    } else {
        Constants.log(LOG_TAG, "Can't get event package name. Returning.");
        return;
    }

    boolean found = false;
    for (String packageName : packages) {
        if (packageName.equalsIgnoreCase(eventPackageName)) {
            found = true;
            break;
        }
    }
    if (!found) {
        Constants.log(LOG_TAG, eventPackageName + " was not found in the include list. Returning.");
        return;
    }
    String title = eventPackageName.substring(eventPackageName.lastIndexOf('.') + 1);
    // get the notification text
    Bundle notiBundle = notif.extras;
    StringBuilder notifySb = new StringBuilder();
    CharSequence notifyChars = notiBundle.getCharSequence(Notification.EXTRA_TITLE);
    if (notifyChars != null) {
        notifySb.append(notifyChars);
    } else {
        Constants.log(LOG_TAG, "empty message title,return!");
        return;
    }

    CharSequence bodyCS = notiBundle.getCharSequence(Notification.EXTRA_TEXT);
    if (bodyCS != null) {
        notifySb.append(":");
        notifySb.append(bodyCS);
    } else {
        Constants.log(LOG_TAG, "empty message body,return!" + notifySb.toString());
        return;
    }
    bodyCS = notiBundle.getCharSequence(Notification.EXTRA_SUB_TEXT);
    if (bodyCS != null) {
        notifySb.append(bodyCS);
    }

    Message msg = Message.obtain();
    msg.what = MessageProcessingService.MSG_NEW_MESSAGE;
    Bundle b = new Bundle();
    b.putString(MessageDbHandler.COL_MESSAGE_APP, title);
    b.putString(MessageDbHandler.COL_MESSAGE_CONTENT, notifySb.toString());
    Constants.log(LOG_TAG, "Send new message title:" + title + " body:" + notifySb.toString());
    msg.setData(b);
    try {
        rMessageProcessHandler.send(msg);
    } catch (RemoteException e) {
        e.printStackTrace();
        Constants.log(LOG_TAG, "Error when sending message to MessageProcessingService.");
    }
}

From source file:org.android.gcm.client.GcmIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    final SharedPreferences prefs = getSharedPreferences("gcmclient", Context.MODE_PRIVATE);
    pushpak = prefs.getString("push_pak", "");
    pushact = prefs.getString("push_act", "");
    final boolean pushon = prefs.getBoolean("push_on", true);
    final boolean pushnotif = prefs.getBoolean("push_notification", true);

    if (pushnotif) {
        final String notifact = prefs.getString("notification_act", "");
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        // The getMessageType() intent parameter must be the intent you received
        // in your BroadcastReceiver.
        String messageType = gcm.getMessageType(intent);

        // Send a notification.
        if (!extras.isEmpty()) { // has effect of unparcelling Bundle
            /*/*from   ww  w.  j  av  a2s . co  m*/
             * Filter messages based on message type. Since it is likely that GCM will be
             * extended in the future with new message types, just ignore any message types you're
             * not interested in, or that you don't recognize.
             */
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
                sendNotification(getString(R.string.send_error) + ": " + extras.toString(), notifact);
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
                sendNotification(getString(R.string.deleted) + ": " + extras.toString(), notifact);
                // If it's a regular GCM message, do some work.
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                // Post notification of received message.
                sendNotification(
                        getString(R.string.received, extras.getString("name"), extras.getString("num")),
                        notifact);
                Log.i(TAG, "Received: " + extras.toString());
            }
        }
    }

    // End if push is not enabled.
    if (!pushon) {
        // Release the wake lock provided by the WakefulBroadcastReceiver.
        GcmBroadcastReceiver.completeWakefulIntent(intent);
        return;
    }

    final boolean fullwake = prefs.getBoolean("full_wake", false);
    final boolean endoff = prefs.getBoolean("end_off", true);

    // Manage the screen.
    PowerManager mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock mWakeLock = mPowerManager
            .newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, TAG);
    boolean misScreenOn = mPowerManager.isScreenOn();
    int mScreenTimeout = 0;
    if (!misScreenOn) {
        if (endoff) {
            // Change the screen timeout setting.
            mScreenTimeout = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT,
                    0);
            if (mScreenTimeout != 0) {
                Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 3000);
            }
        }
        // Full wake lock
        if (fullwake) {
            mWakeLock.acquire();
        }
    }

    // Start the activity.
    try {
        startActivity(getPushactIntent(Intent.FLAG_ACTIVITY_NO_USER_ACTION | Intent.FLAG_ACTIVITY_NO_ANIMATION
                | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS));
        // Wait to register.
        Thread.sleep(REGISTER_DURATION);
    } catch (android.content.ActivityNotFoundException e) {
        RING_DURATION = 0;
        Log.i(TAG, "Activity not started");
    } catch (InterruptedException e) {
    }

    // Release the wake lock.
    if (!misScreenOn && fullwake) {
        mWakeLock.release();
    }
    GcmBroadcastReceiver.completeWakefulIntent(intent);

    // Restore the screen timeout setting.
    if (endoff && mScreenTimeout != 0) {
        try {
            Thread.sleep(RING_DURATION);
        } catch (InterruptedException e) {
        }
        Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, mScreenTimeout);
    }
}

From source file:com.wifiafterconnect.WifiAuthenticator.java

public boolean checkTNCShown(ParsedHttpInput parsed) {
    String ssid = WifiTools.getSSID(getContext());
    WifiAuthDatabase wifiDb = getDb();/*from  w  w w  . j ava2 s.c o  m*/
    if (wifiDb == null || ssid == null || ssid.isEmpty())
        return true;

    if (wifiDb.isKnownSSID(ssid))
        return true;
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    Context context = getContext();
    boolean urlOpened = false;
    if (pm.isScreenOn() && context != null) {
        try {
            debug("TNC not shown previously. Redirecting to page in browser.");
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(parsed.getURL().toURI().toString()));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            urlOpened = true;
        } catch (URISyntaxException e) { // don't care
        }
    } else {
        // what should we do when the screen is locked???
    }
    wifiDb.storeSSID(ssid);
    return !urlOpened;
}

From source file:com.tfg.sawan.bsecure.beacon.UriBeaconDiscoveryService.java

@Override
@SuppressWarnings("deprecation")
public int onStartCommand(Intent intent, int flags, int startId) {
    // Since sometimes the lists have values when onStartCommand gets called
    initializeLists();/*  w ww.  jav a2  s. c o m*/
    // Start scanning only if the screen is on
    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    // NOTE: use powerManager.isInteractive() when minsdk >= 20
    if (powerManager.isScreenOn()) {
        mCanUpdateNotifications = false;
        mHandler.postDelayed(mNotificationUpdateGateTimeout, NOTIFICATION_UPDATE_GATE_DURATION);
        startSearchingForUriBeacons();
        mMdnsUrlDiscoverer.startScanning();
        mSsdpUrlDiscoverer.startScanning();
    }

    //make sure the service keeps running
    return START_STICKY;
}

From source file:org.physical_web.physicalweb.UriBeaconDiscoveryService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // Since sometimes the lists have values when onStartCommand gets called
    initializeLists();/*from  www .  j a  v  a  2  s  . co m*/
    // Start scanning only if the screen is on
    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    if (powerManager.isScreenOn()) {
        mCanUpdateNotifications = false;
        mHandler.postDelayed(mNotificationUpdateGateTimeout, NOTIFICATION_UPDATE_GATE_DURATION);
        startSearchingForUriBeacons();
        mMdnsUrlDiscoverer.startScanning();
    }

    //make sure the service keeps running
    return START_STICKY;
}