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:com.achep.acdisplay.ui.activities.MainActivity.java

/**
 * Turns screen off and sends a test notification.
 *
 * @param cheat {@code true} if it simply starts {@link AcDisplayActivity},
 *              {@code false} if it turns device off and then uses notification
 *              to wake it up.// ww w. j a  v  a 2  s. c  o m
 */
private void startAcDisplayTest(boolean cheat) {
    if (cheat) {
        startActivity(new Intent(this, AcDisplayActivity.class));
        sendTestNotification(this);
        return;
    }

    int delay = getResources().getInteger(R.integer.config_test_notification_delay);

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Test notification.");
    wakeLock.acquire(delay);

    try {
        // Go sleep
        DevicePolicyManager dpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        dpm.lockNow();

        new Handler().postDelayed(new Runnable() {

            private final Context context = getApplicationContext();

            @Override
            public void run() {
                sendTestNotification(context);
            }
        }, delay);
    } catch (SecurityException e) {
        Log.wtf(TAG, "Failed to turn screen off!");
        wakeLock.release();
    }
}

From source file:com.bullmobi.message.ui.activities.MainActivity.java

/**
 * Turns screen off and sends a test notification.
 *
 * @param cheat {@code true} if it simply starts {@link EasyNotificationActivity},
 *              {@code false} if it turns device off and then uses notification
 *              to wake it up./*from   w w  w.ja v a 2s.  c  o  m*/
 */
private void startEasyNotificationTest(boolean cheat) {
    if (cheat) {
        startActivity(new Intent(this, EasyNotificationActivity.class));
        sendTestNotification(this);
        return;
    }

    int delay = getResources().getInteger(R.integer.config_test_notification_delay);

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Test notification.");
    wakeLock.acquire(delay);

    try {
        // Go sleep
        DevicePolicyManager dpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        dpm.lockNow();

        new Handler().postDelayed(new Runnable() {

            private final Context context = getApplicationContext();

            @Override
            public void run() {
                sendTestNotification(context);
            }
        }, delay);
    } catch (SecurityException e) {
        Log.wtf(TAG, "Failed to turn screen off!");
        wakeLock.release();
    }
}

From source file:com.simicart.core.notification.GCMIntentService.java

private void onRecieveMessage(Context context) {
    // Sang man hinh khi co notification
    PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
    WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK
            | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
    wakeLock.acquire(5000);/*from   w w w.j ava2s  .c  om*/

    // // Am thanh mac dinh
    // try {
    // Uri notification = RingtoneManager
    // .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    // Ringtone r = RingtoneManager.getRingtone(getApplicationContext(),
    // notification);
    // r.play();
    // } catch (Exception e) {
    // e.printStackTrace();
    // }

    // check app open or close
    if (MainActivity.context != null && MainActivity.state != MainActivity.PAUSE
            && notificationData.getShowPopup().equals("1")) {
        createNotification(context);
    } else {
        generateNotification(context, notificationData);
    }
}

From source file:my.home.lehome.service.SendMsgIntentService.java

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

    if (mWakeLock == null) {
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        mWakeLock.acquire();/*from   w w  w .ja  va 2  s  . c  o m*/
        Log.d(TAG, "acquire wakelock");
    }

    mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}

From source file:com.thebigbang.ftpclient.FTPOperation.java

/**
 * will force keep the device turned on for all the operation duration.
 * @param params//from www  .  j a v  a  2s  .  com
 * @return 
 */
@SuppressLint("Wakelock")
@SuppressWarnings("deprecation")
@Override
protected Boolean doInBackground(FTPBundle... params) {
    Thread.currentThread().setName("FTPOperationWorker");
    for (final FTPBundle bundle : params) {

        FTPClient ftp = new FTPClient();
        PowerManager pw = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
        WakeLock w = pw.newWakeLock(PowerManager.FULL_WAKE_LOCK, "FTP Client");
        try {
            // setup ftp connection:
            InetAddress addr = InetAddress.getByName(bundle.FTPServerHost);
            //set here the timeout.
            TimeoutThread timeout = new TimeoutThread(_timeOut, new FTPTimeout() {
                @Override
                public void Occurred(TimeoutException e) {
                    bundle.Exception = e;
                    bundle.OperationStatus = FTPOperationStatus.Failed;
                    publishProgress(bundle);
                }
            });
            timeout.start();
            ftp.connect(addr, bundle.FTPServerPort);
            int reply = ftp.getReplyCode();
            timeout.Stop();
            if (!FTPReply.isPositiveCompletion(reply)) {
                throw new IOException("connection refuse");
            }
            ftp.login(bundle.FTPCredentialUsername, bundle.FTPCredentialPassword);
            if (bundle.OperationType == FTPOperationType.Connect) {
                bundle.OperationStatus = FTPOperationStatus.Succed;
                publishProgress(bundle);
                continue;
            }
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.enterLocalPassiveMode();

            w.acquire();
            // then switch between enum of operation types.
            if (bundle.OperationType == FTPOperationType.RetrieveFilesFoldersList) {
                ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory);
                bundle.FilesOnCurrentPath = ftp.listFiles();
                bundle.FoldersOnCurrentPath = ftp.listDirectories();
                bundle.OperationStatus = FTPOperationStatus.Succed;
            } else if (bundle.OperationType == FTPOperationType.RetrieveFolderList) {
                ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory);
                bundle.FoldersOnCurrentPath = ftp.listDirectories();
                bundle.OperationStatus = FTPOperationStatus.Succed;
            } else if (bundle.OperationType == FTPOperationType.RetrieveFileList) {
                ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory);
                bundle.FilesOnCurrentPath = ftp.listFiles();
                bundle.OperationStatus = FTPOperationStatus.Succed;
            } else if (bundle.OperationType == FTPOperationType.GetData) {
                String finalFPFi = bundle.LocalFilePathName;
                // The remote filename to be downloaded.
                if (bundle.LocalWorkingDirectory != null && bundle.LocalWorkingDirectory != "") {
                    File f = new File(bundle.LocalWorkingDirectory);
                    f.mkdirs();

                    finalFPFi = bundle.LocalWorkingDirectory + finalFPFi;
                }
                FileOutputStream fos = new FileOutputStream(finalFPFi);

                // Download file from FTP server
                String finalFileN = bundle.RemoteFilePathName;
                if (bundle.RemoteWorkingDirectory != null && bundle.RemoteWorkingDirectory != "") {
                    finalFileN = bundle.RemoteWorkingDirectory + finalFileN;
                }
                boolean b = ftp.retrieveFile(finalFileN, fos);
                if (b)
                    bundle.OperationStatus = FTPOperationStatus.Succed;
                else
                    bundle.OperationStatus = FTPOperationStatus.Failed;
                fos.close();

            } else if (bundle.OperationType == FTPOperationType.SendData) {
                InputStream istr = new FileInputStream(bundle.LocalFilePathName);
                ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory);
                Boolean b = ftp.storeFile(bundle.RemoteFilePathName, istr);
                istr.close();
                if (b)
                    bundle.OperationStatus = FTPOperationStatus.Succed;
                else
                    bundle.OperationStatus = FTPOperationStatus.Failed;
            } else if (bundle.OperationType == FTPOperationType.DeleteData) {
                throw new IOException("DeleteData is Not yet implemented");
            }

            ftp.disconnect();
            // then finish/return.
            //publishProgress(bundle);
        } catch (IOException e) {
            e.printStackTrace();
            bundle.Exception = e;
            bundle.OperationStatus = FTPOperationStatus.Failed;
        }
        try {
            w.release();
        } catch (RuntimeException ex) {
            ex.printStackTrace();
        }
        publishProgress(bundle);
    }
    return true;
}

From source file:com.linroid.pushapp.service.DownloadService.java

/**
 * ?/*ww  w.  j a v  a 2  s  .  c o  m*/
 * @param pack 
 */
private void onDownloadComplete(Pack pack) {
    Timber.d("%s ?,?:%s", pack.getAppName(), pack.getPath());
    int toastResId = R.string.toast_download_complete;
    if (autoInstall.getValue()) {
        startActivity(IntentUtil.installApk(pack.getPath()));
        if (AndroidUtil.isAccessibilitySettingsOn(this, ApkAutoInstallService.class.getCanonicalName())) {
            PowerManager powermanager = ((PowerManager) getSystemService(Context.POWER_SERVICE));
            PowerManager.WakeLock wakeLock = powermanager.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                    | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP),
                    "Install Worker, FULL WAKE LOCK");
            wakeLock.acquire();
            wakeLock.release();
            KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
            //                if(keyguardManager.isDeviceLocked()) {
            final KeyguardManager.KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("unLock");
            keyguardLock.disableKeyguard();
            //                }
            ApkAutoInstallService.addInstallPackage(pack);
            toastResId = R.string.toast_start_install;
        } else {
            toastResId = R.string.toast_download_complete;
        }
    }
    Toast.makeText(this, getString(toastResId, pack.getAppName()), Toast.LENGTH_SHORT).show();

}

From source file:step.StepService.java

private void acquireWakeLock() {
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    int wakeFlags;
    wakeFlags = PowerManager.PARTIAL_WAKE_LOCK;
    wakeLock = pm.newWakeLock(wakeFlags, TAG);
    wakeLock.acquire();//ww  w.  jav a 2  s. c om
}

From source file:de.badaix.snapcast.SnapclientService.java

private void start(String host, int port) {
    try {/*from ww w .j  a va  2s  .  c  om*/
        //https://code.google.com/p/android/issues/detail?id=22763
        if (running)
            return;
        File binary = new File(getFilesDir(), "snapclient");
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);

        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PARTIAL_WAKE_LOCK, "SnapcastWakeLock");
        wakeLock.acquire();

        WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
        wifiWakeLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "SnapcastWifiWakeLock");
        wifiWakeLock.acquire();

        process = new ProcessBuilder()
                .command(binary.getAbsolutePath(), "-h", host, "-p", Integer.toString(port))
                .redirectErrorStream(true).start();

        Thread reader = new Thread(new Runnable() {
            @Override
            public void run() {
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(process.getInputStream()));
                String line;
                try {
                    while ((line = bufferedReader.readLine()) != null) {
                        log(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        logReceived = false;
        reader.start();

        //TODO: wait for started message on stdout
        /*            long now = System.currentTimeMillis();
                    while (!logReceived) {
        if (System.currentTimeMillis() > now + 1000)
            throw new Exception("start timeout");
        Thread.sleep(100, 0);
                    }
        */
    } catch (Exception e) {
        e.printStackTrace();
        if (listener != null)
            listener.onError(this, e.getMessage(), e);
        stop();
    }
}

From source file:net.kayateia.lifestream.StreamService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.v(LOG_TAG, "Kicked");

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    final PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");

    // See CaptureService for comments on this wake lock arrangement.
    boolean needsRelease = true;
    try {/*from   w w  w.ja  v a  2  s  .  co m*/
        // If we don't release it within the timeout somehow, release it anyway.
        // This may interrupt a long backlog download or something, but this
        // is really about as long as we can reasonably expect to take.
        Log.v(LOG_TAG, "Acquire wakelock");
        if (wl != null)
            wl.acquire(WAKELOCK_TIMEOUT);

        if (!Network.IsActive(this)) {
            Log.i(LOG_TAG, "No network active, giving up");
            return START_NOT_STICKY;
        }

        // Do the check in a thread.
        new AsyncTask<StreamService, Void, Void>() {
            @Override
            protected Void doInBackground(StreamService... svc) {
                svc[0].checkNewImages();
                return null;
            }

            @Override
            protected void onPostExecute(Void foo) {
                Log.v(LOG_TAG, "Release wakelock by worker");
                if (wl != null && wl.isHeld())
                    wl.release();
            }
        }.execute(this);
        needsRelease = false;
    } finally {
        if (needsRelease) {
            Log.v(LOG_TAG, "Release wakelock by default");
            if (wl != null && wl.isHeld())
                wl.release();
        }
    }

    // There's no need to worry about this.. we'll get re-kicked by the alarm.
    return START_NOT_STICKY;
}

From source file:com.konsula.app.gcm.MyGcmListenerService.java

/**
 * Called when message is received.//from w  w  w .j av a 2  s . co m
 *
 * @param from SenderID of the sender.
 * @param data Data bundle containing message data as key/value pairs.
 *             For Set of keys use data.keySet().
 */
// [START receive_message]
@Override
public void onMessageReceived(String from, Bundle data) {
    String message = data.getString("message");
    togo = data.getString("type");
    bundle = data;
    //        Settings.System.putString(this.getContentResolver(), Settings.System.NEXT_ALARM_FORMATTED, message);

    Log.d(TAG, String.valueOf(data));
    Log.d(TAG, "Message: " + message);

    if (from.startsWith("/topics/")) {
        // message received from some topic.
    } else {
        // normal downstream message.
    }

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
    wl.acquire(3000);
    wl.release();

    //kalo misalnya app kebuka, message diterima disini.

    // [START_EXCLUDE]
    /**
     * Production applications would usually process the message here.
     * Eg: - Syncing with server.
     *     - Store message in local database.
     *     - Update UI.
     */

    /**
     * In some cases it may be useful to show a notification indicating to the user
     * that a message was received.
     */
    handleGCM(bundle);
    sendNotification(message);
    // [END_EXCLUDE]
}