Example usage for android.os PowerManager newWakeLock

List of usage examples for android.os PowerManager newWakeLock

Introduction

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

Prototype

public WakeLock newWakeLock(int levelAndFlags, String tag) 

Source Link

Document

Creates a new wake lock with the specified level and flags.

Usage

From source file:im.vector.notifications.NotificationUtils.java

/**
 * Add the notification sound.//from  w  ww.  j  av  a  2s . c  o  m
 *
 * @param context      the context
 * @param builder      the notification builder
 * @param isBackground true if the notification is a background one
 * @param isBing       true if the notification should play sound
 */
@SuppressLint("NewApi")
private static void manageNotificationSound(Context context, NotificationCompat.Builder builder,
        boolean isBackground, boolean isBing) {
    @ColorInt
    int highlightColor = ContextCompat.getColor(context, R.color.vector_fuchsia_color);
    int defaultColor = Color.TRANSPARENT;

    if (isBackground) {
        builder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
        builder.setColor(defaultColor);
    } else if (isBing) {
        builder.setPriority(NotificationCompat.PRIORITY_HIGH);
        builder.setColor(highlightColor);
    } else {
        builder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
        builder.setColor(Color.TRANSPARENT);
    }

    if (!isBackground) {
        builder.setDefaults(Notification.DEFAULT_LIGHTS);

        if (isBing && (null != PreferencesManager.getNotificationRingTone(context))) {
            builder.setSound(PreferencesManager.getNotificationRingTone(context));

            if (Build.VERSION.SDK_INT >= 26) {
                builder.setChannelId(NOISY_NOTIFICATION_CHANNEL_ID);
            }
        }

        // turn the screen on for 3 seconds
        if (Matrix.getInstance(VectorApp.getInstance()).getSharedGCMRegistrationManager().isScreenTurnedOn()) {
            PowerManager pm = (PowerManager) VectorApp.getInstance().getSystemService(Context.POWER_SERVICE);
            PowerManager.WakeLock wl = pm.newWakeLock(
                    PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
                    "manageNotificationSound");
            wl.acquire(3000);
            wl.release();
        }
    }
}

From source file:de.ub0r.android.smsdroid.SmsReceiver.java

static void handleOnReceive(final BroadcastReceiver receiver, final Context context, final Intent intent) {
    final String action = intent.getAction();
    Log.d(TAG, "onReceive(context, ", action, ")");
    final PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    final PowerManager.WakeLock wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    wakelock.acquire();/*from  w w  w.j av a  2 s.c  om*/
    Log.i(TAG, "got wakelock");
    Log.d(TAG, "got intent: ", action);
    try {
        Log.d(TAG, "sleep(", SLEEP, ")");
        Thread.sleep(SLEEP);
    } catch (InterruptedException e) {
        Log.d(TAG, "interrupted in spinlock", e);
        e.printStackTrace();
    }
    String text;
    if (SenderActivity.MESSAGE_SENT_ACTION.equals(action)) {
        handleSent(context, intent, receiver.getResultCode());
    } else {
        boolean silent = false;

        if (shouldHandleSmsAction(context, action)) {
            Bundle b = intent.getExtras();
            assert b != null;
            Object[] messages = (Object[]) b.get("pdus");
            SmsMessage[] smsMessage = new SmsMessage[messages.length];
            int l = messages.length;
            for (int i = 0; i < l; i++) {
                smsMessage[i] = SmsMessage.createFromPdu((byte[]) messages[i]);
            }
            text = null;
            if (l > 0) {
                // concatenate multipart SMS body
                StringBuilder sbt = new StringBuilder();
                for (int i = 0; i < l; i++) {
                    sbt.append(smsMessage[i].getMessageBody());
                }
                text = sbt.toString();

                // ! Check in blacklist db - filter spam
                String s = smsMessage[0].getDisplayOriginatingAddress();

                // this code is used to strip a forwarding agent and display the orginated number as sender
                final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
                if (prefs.getBoolean(PreferencesActivity.PREFS_FORWARD_SMS_CLEAN, false)
                        && text.contains(":")) {
                    Pattern smsPattern = Pattern.compile("([0-9a-zA-Z+]+):");
                    Matcher m = smsPattern.matcher(text);
                    if (m.find()) {
                        s = m.group(1);
                        Log.d(TAG, "found forwarding sms number: (", s, ")");
                        // now strip the sender from the message
                        Pattern textPattern = Pattern.compile("^[0-9a-zA-Z+]+: (.*)");
                        Matcher m2 = textPattern.matcher(text);
                        if (text.contains(":") && m2.find()) {
                            text = m2.group(1);
                            Log.d(TAG, "stripped the message");
                        }
                    }
                }

                final SpamDB db = new SpamDB(context);
                db.open();
                if (db.isInDB(smsMessage[0].getOriginatingAddress())) {
                    Log.d(TAG, "Message from ", s, " filtered.");
                    silent = true;
                } else {
                    Log.d(TAG, "Message from ", s, " NOT filtered.");
                }
                db.close();

                if (action.equals(ACTION_SMS_NEW)) {
                    // API19+: save message to the database
                    ContentValues values = new ContentValues();
                    values.put("address", s);
                    values.put("body", text);
                    context.getContentResolver().insert(Uri.parse("content://sms/inbox"), values);
                    Log.d(TAG, "Insert SMS into database: ", s, ", ", text);
                }
            }
            updateNotificationsWithNewText(context, text, silent);
        } else if (ACTION_MMS_OLD.equals(action) || ACTION_MMS_MEW.equals(action)) {
            text = MMS_BODY;
            // TODO API19+ MMS code
            updateNotificationsWithNewText(context, text, silent);
        }
    }
    wakelock.release();
    Log.i(TAG, "wakelock released");
}

From source file:org.metawatch.manager.Monitors.java

public static void updateWeatherData(final Context context) {
    Thread thread = new Thread("WeatherUpdater") {
        @Override/*from   ww  w.j ava2s .co m*/
        public void run() {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Weather");
            wl.acquire();

            switch (Preferences.weatherProvider) {
            case WeatherProvider.GOOGLE:
                updateWeatherDataGoogle(context);
                break;

            case WeatherProvider.WUNDERGROUND:
                updateWeatherDataWunderground(context);
                break;
            }

            wl.release();
        }
    };
    thread.start();
}

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);/*  ww w . j a v a 2 s. c om*/
        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.google.android.apps.muzei.TaskQueueService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent.getAction() == null) {
        return;/*from  w w  w . j ava  2 s  . c om*/
    }

    String action = intent.getAction();
    if (ACTION_DOWNLOAD_CURRENT_ARTWORK.equals(action)) {
        // This is normally not started by a WakefulBroadcastReceiver so request a
        // new wakelock.
        PowerManager pwm = (PowerManager) getSystemService(POWER_SERVICE);
        PowerManager.WakeLock lock = pwm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        lock.acquire(DOWNLOAD_ARTWORK_WAKELOCK_TIMEOUT_MILLIS);

        try {
            // Handle internal download artwork request
            ArtworkCache.getInstance(this).maybeDownloadCurrentArtworkSync();
        } finally {
            if (lock.isHeld()) {
                lock.release();
            }
        }

        WakefulBroadcastReceiver.completeWakefulIntent(intent);
    }
}

From source file:com.commonsware.android.antidoze.ScheduledService.java

@Override
public void onCreate() {
    super.onCreate();

    PowerManager mgr = (PowerManager) getSystemService(POWER_SERVICE);

    wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getSimpleName());
    wakeLock.acquire();// w ww.ja v  a  2s.  c  om

    if (BuildConfig.IS_FOREGROUND) {
        foregroundify();
    }

    log = new File(getExternalFilesDir(null), "antidoze-log.txt");
    log.getParentFile().mkdirs();
    sched.scheduleAtFixedRate(this, 0, 15, TimeUnit.SECONDS);
}

From source file:com.android.mms.quickmessage.QuickMessageWear.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mContext = this;
    Intent i = getIntent();//from  ww  w. j av a2 s  . c o m
    parseIntent(i);
    //Get partial Wakelock so that we can send the message even if phone is locked
    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    mWakeLock.acquire();
}

From source file:com.connectsdk.smarthomesampler.SceneService.java

@Override
public void onCreate() {
    super.onCreate();
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Wake Lock");
    wakeLock.acquire();/* www.  ja va 2s .c  om*/

    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(getString(R.string.app_name))
            .setContentText(getString(R.string.smarthome_service_is_working)).setContentIntent(pendingIntent)
            .build();

    startForeground(NOTIFICATION_ID, notification);
}

From source file:it.baywaylabs.jumpersumo.robot.Daemon.java

/**
 * Method auto invoked pre execute the task.
 *//*w  ww .j  a  v  a 2  s.  c o m*/
@Override
protected void onPreExecute() {
    super.onPreExecute();
    // take CPU lock to prevent CPU from going off if the user
    // presses the power button during download
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
    mWakeLock.acquire();
    folder = new File(Constants.DIR_ROBOT_DAEMON);
    if (!folder.exists()) {
        folder.mkdir();
    }
}

From source file:com.androidzeitgeist.dashwatch.DashWatchService.java

/**
 * Asks extensions to provide data updates.
 *///from   w w  w.j ava2s  .  c o m
private void updateExtensions() {
    PowerManager pwm = (PowerManager) getSystemService(POWER_SERVICE);
    PowerManager.WakeLock lock = pwm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    lock.acquire(UPDATE_WAKELOCK_TIMEOUT_MILLIS);

    int reason = DashClockExtension.UPDATE_REASON_INITIAL;

    try {
        for (ComponentName cn : mExtensionManager.getActiveExtensionNames()) {
            mExtensionHost.execute(cn, ExtensionHost.UPDATE_OPERATIONS.get(reason),
                    ExtensionHost.UPDATE_COLLAPSE_TIME_MILLIS, reason);
        }
    } finally {
        lock.release();
    }
}