Example usage for android.os PowerManager PARTIAL_WAKE_LOCK

List of usage examples for android.os PowerManager PARTIAL_WAKE_LOCK

Introduction

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

Prototype

int PARTIAL_WAKE_LOCK

To view the source code for android.os PowerManager PARTIAL_WAKE_LOCK.

Click Source Link

Document

Wake lock level: Ensures that the CPU is running; the screen and keyboard backlight will be allowed to go off.

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./*  w  ww  .  ja  v  a  2 s  .  co 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:org.LK8000.LK8000.java

public void initSDL() {
    if (!Loader.loaded)
        return;/*  w w  w  . j  av a2  s.  c  o m*/

    /* check if external storage is available; LK8000 doesn't work as
       long as external storage is being forwarded to a PC */
    String state = Environment.getExternalStorageState();
    Log.d(TAG, "getExternalStorageState() = " + state);
    if (!Environment.MEDIA_MOUNTED.equals(state)) {
        TextView tv = new TextView(this);
        tv.setText("External storage is not available (state='" + state + "').  Please turn off USB storage.");
        setContentView(tv);
        return;
    }

    nativeView = new NativeView(this, quitHandler, errorHandler);
    setContentView(nativeView);
    // Receive keyboard events
    nativeView.setFocusableInTouchMode(true);
    nativeView.setFocusable(true);
    nativeView.requestFocus();

    // Obtain an instance of the Android PowerManager class
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);

    // Create a WakeLock instance to keep the screen from timing out
    final String LKTAG = "LK8000:" + BuildConfig.BUILD_TYPE;
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, LKTAG);

    // Activate the WakeLock
    wakeLock.acquire();
}

From source file:com.baruckis.nanodegree.spotifystreamer.PlayerService.java

private void initMediaPlayer() {
    // Set mMediaPlayer properties
    mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    // Set listeners
    mMediaPlayer.setOnPreparedListener(this);
    mMediaPlayer.setOnCompletionListener(this);
    mMediaPlayer.setOnErrorListener(this);
}

From source file:org.videolan.vlc2.audio.AudioService.java

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

    // Get libVLC instance
    try {//  w  w w  .  j  a  v  a2  s. c  o m
        mLibVLC = VLCInstance.getLibVlcInstance();
    } catch (LibVlcException e) {
        e.printStackTrace();
    }

    mCallback = new HashMap<IAudioServiceCallback, Integer>();
    mCurrentIndex = -1;
    mPrevIndex = -1;
    mNextIndex = -1;
    mPrevious = new Stack<Integer>();
    mEventHandler = EventHandler.getInstance();
    mRemoteControlClientReceiverComponent = new ComponentName(getPackageName(),
            RemoteControlClientReceiver.class.getName());

    // Make sure the audio player will acquire a wake-lock while playing. If we don't do
    // that, the CPU might go to sleep while the song is playing, causing playback to stop.
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

    IntentFilter filter = new IntentFilter();
    filter.setPriority(Integer.MAX_VALUE);
    filter.addAction(ACTION_REMOTE_BACKWARD);
    filter.addAction(ACTION_REMOTE_PLAYPAUSE);
    filter.addAction(ACTION_REMOTE_PLAY);
    filter.addAction(ACTION_REMOTE_PAUSE);
    filter.addAction(ACTION_REMOTE_STOP);
    filter.addAction(ACTION_REMOTE_FORWARD);
    filter.addAction(ACTION_REMOTE_LAST_PLAYLIST);
    filter.addAction(ACTION_WIDGET_INIT);
    filter.addAction(Intent.ACTION_HEADSET_PLUG);
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    filter.addAction(VLCApplication.SLEEP_INTENT);
    filter.addAction(VLCApplication.INCOMING_CALL_INTENT);
    filter.addAction(VLCApplication.CALL_ENDED_INTENT);
    registerReceiver(serviceReceiver, filter);

    final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    boolean stealRemoteControl = pref.getBoolean("enable_steal_remote_control", false);

    if (!LibVlcUtil.isFroyoOrLater() || stealRemoteControl) {
        /* Backward compatibility for API 7 */
        filter = new IntentFilter();
        if (stealRemoteControl)
            filter.setPriority(Integer.MAX_VALUE);
        filter.addAction(Intent.ACTION_MEDIA_BUTTON);
        mRemoteControlClientReceiver = new RemoteControlClientReceiver();
        registerReceiver(mRemoteControlClientReceiver, filter);
    }
}

From source file:com.andryr.musicplayer.PlaybackService.java

@Override
public void onCreate() {
    super.onCreate();
    mStatePrefs = getSharedPreferences(STATE_PREFS_NAME, MODE_PRIVATE);

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setOnCompletionListener(this);
    mMediaPlayer.setOnErrorListener(this);
    mMediaPlayer.setOnPreparedListener(this);
    mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    Intent i = new Intent(this, AudioEffectsReceiver.class);
    i.setAction(AudioEffectsReceiver.ACTION_OPEN_AUDIO_EFFECT_SESSION);
    i.putExtra(AudioEffectsReceiver.EXTRA_AUDIO_SESSION_ID, mMediaPlayer.getAudioSessionId());
    sendBroadcast(i);/*from w  w w  .j av  a 2 s  .co  m*/

    IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
    registerReceiver(mHeadsetStateReceiver, receiverFilter);

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    mAutoPause = prefs.getBoolean(PREF_AUTO_PAUSE, false);

    initTelephony();

    restoreState();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        setupMediaSession();
    }

}

From source file:com.geryon.ocraa.MusicService.java

/**
 * Makes sure the media player exists and has been reset. This will create the media player
 * if needed, or reset the existing media player if one already exists.
 *//* www .  j  a  v  a2  s. c  o m*/
void createMediaPlayerIfNeeded() {
    if (mPlayer == null) {
        mPlayer = new MediaPlayer();

        // Make sure the media player w ill acquire a wake-lock while playing. If we don't do
        // that, the CPU might go to sleep while the song is playing, causing playback to stop.
        //
        // Remember that to use this, we have to declare the android.permission.WAKE_LOCK
        // permission in AndroidManifest.xml.
        mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

        // we want the media player to notify us when it's ready preparing, and when it's done
        // playing:
        mPlayer.setOnPreparedListener(this);
        mPlayer.setOnCompletionListener(this);
        mPlayer.setOnErrorListener(this);
    } else
        mPlayer.reset();
}

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 . j av a  2s  . com
 */
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:pct.droid.base.torrent.TorrentService.java

public void streamTorrent(@NonNull final String torrentUrl) {
    Timber.d("streamTorrent");

    //attempt to initialize service
    initialize();//  www.j  a v  a2 s  . c  o m

    if (mHandler == null || mIsStreaming)
        return;

    mIsCanceled = false;
    mReady = false;

    Timber.d("Starting streaming");

    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, THREAD_NAME);
    mWakeLock.acquire();

    SessionSettings sessionSettings = mTorrentSession.getSettings();
    sessionSettings.setActiveDHTLimit(PrefUtils.get(this, Prefs.LIBTORRENT_DHT_LIMIT, 200));
    sessionSettings.setConnectionsLimit(PrefUtils.get(this, Prefs.LIBTORRENT_CONNECTION_LIMIT, 200));
    sessionSettings.setDownloadRateLimit(PrefUtils.get(this, Prefs.LIBTORRENT_DOWNLOAD_LIMIT, 0));
    sessionSettings.setUploadRateLimit(PrefUtils.get(this, Prefs.LIBTORRENT_UPLOAD_LIMIT, 0));
    mTorrentSession.setSettings(sessionSettings);

    mHandler.post(new Runnable() {
        @Override
        public void run() {
            Timber.d("streaming runnable");
            mIsStreaming = true;
            mCurrentTorrentUrl = torrentUrl;

            File saveDirectory = new File(PopcornApplication.getStreamDir());
            saveDirectory.mkdirs();

            File torrentFileDir = new File(saveDirectory, "files");
            torrentFileDir.mkdirs();

            File torrentFile = new File(torrentFileDir, System.currentTimeMillis() + ".torrent");

            if (!torrentFile.exists()) {
                int fileCreationTries = 0;
                while (fileCreationTries < 4) {
                    try {
                        fileCreationTries++;
                        if (torrentFileDir.mkdirs() || torrentFileDir.isDirectory()) {
                            Timber.d("Creating torrent file");
                            torrentFile.createNewFile();
                        }
                    } catch (IOException e) {
                        Timber.e(e, "Error on file create");
                    }
                }

                if (!getTorrentFile(torrentUrl, torrentFile)) {
                    for (final Listener listener : mListener) {
                        ThreadUtils.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                listener.onStreamError(new IOException("Write error"));
                            }
                        });
                    }
                    return;
                } else if (!torrentFile.exists()) {
                    for (final Listener listener : mListener) {
                        ThreadUtils.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                listener.onStreamError(new IOException("Write error"));
                            }
                        });
                    }
                    return;
                }
            }

            if (!mCurrentTorrentUrl.equals(torrentUrl) || mIsCanceled) {
                return;
            }

            mCurrentTorrent = mTorrentSession.addTorrent(torrentFile, saveDirectory);
            mCurrentListener = new TorrentAlertAdapter(mCurrentTorrent);
            mTorrentSession.addListener(mCurrentListener);

            TorrentInfo torrentInfo = mCurrentTorrent.getTorrentInfo();
            FileStorage fileStorage = torrentInfo.getFiles();
            long highestFileSize = 0;
            int selectedFile = -1;
            for (int i = 0; i < fileStorage.geNumFiles(); i++) {
                long fileSize = fileStorage.getFileSize(i);
                if (highestFileSize < fileSize) {
                    highestFileSize = fileSize;
                    selectedFile = i;
                }
            }

            mCurrentVideoLocation = new File(saveDirectory, torrentInfo.getFileAt(selectedFile).getPath());

            Timber.d("Video location: %s", mCurrentVideoLocation);

            //post a new runnable which will potentially take along time.
            //this is the runnable which actually starts the streaming.
            //posting this as a runnable will allow other runnables that have been posted
            //execute before this potentially blocking runnable
            mHandler.post(new Runnable() {
                @Override
                public void run() {

                    //blocking call.
                    mDHT.waitNodes(30);
                    mCurrentTorrent.setSequentialDownload(true);
                    mCurrentTorrent.resume();
                    for (final Listener listener : mListener) {
                        ThreadUtils.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                listener.onStreamStarted();
                            }
                        });
                    }
                }
            });
        }
    });
}

From source file:ch.ethz.twimight.net.opportunistic.ScanningService.java

/**
 * Acquire the Wake Lock/*from  w  w  w .  j a  v  a 2 s .c  o  m*/
 * 
 * @param context
 */
void getWakeLock(Context context) {

    releaseWakeLock();

    PowerManager mgr = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKE_LOCK);
    wakeLock.acquire();
}

From source file:org.moire.ultrasonic.service.DownloadServiceImpl.java

@SuppressLint("NewApi")
@Override/*from w  w  w  . j  a  va 2s  . c o  m*/
public void onCreate() {
    super.onCreate();

    new Thread(new Runnable() {
        @Override
        public void run() {
            Thread.currentThread().setName("DownloadServiceImpl");

            Looper.prepare();

            if (mediaPlayer != null) {
                mediaPlayer.release();
            }

            mediaPlayer = new MediaPlayer();
            mediaPlayer.setWakeMode(DownloadServiceImpl.this, PowerManager.PARTIAL_WAKE_LOCK);

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
                    handleError(new Exception(String.format("MediaPlayer error: %d (%d)", what, more)));
                    return false;
                }
            });

            try {
                Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
                i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, mediaPlayer.getAudioSessionId());
                i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
                sendBroadcast(i);
            } catch (Throwable e) {
                // Froyo or lower
            }

            mediaPlayerLooper = Looper.myLooper();
            mediaPlayerHandler = new Handler(mediaPlayerLooper);
            Looper.loop();
        }
    }).start();

    audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
    setUpRemoteControlClient();

    if (equalizerAvailable) {
        equalizerController = new EqualizerController(this, mediaPlayer);
        if (!equalizerController.isAvailable()) {
            equalizerController = null;
        } else {
            equalizerController.loadSettings();
        }
    }
    if (visualizerAvailable) {
        visualizerController = new VisualizerController(mediaPlayer);
        if (!visualizerController.isAvailable()) {
            visualizerController = null;
        }
    }

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    wakeLock.setReferenceCounted(false);

    instance = this;
    lifecycleSupport.onCreate();
}