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:net.czlee.debatekeeper.AlertManager.java

/**
 * Creates the appropriate wake lock based on the "keep screen on" setting.
 * If <code>mWakeLock</code> exists, this releases and overwrites it.
 *//*www.  j av  a  2 s .  c om*/
private void createWakeLock() {

    // If there exists a wake lock, release it.
    if (mWakeLock != null) {
        mWakeLock.release();
        mWakeLock = null;
    }

    mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Debatekeeper");

    // Either we have the lock or we don't, we don't need to count how many times we locked
    // it.  Turning this off makes it okay to acquire or release multiple times.
    mWakeLock.setReferenceCounted(false);
}

From source file:com.ferdi2005.secondgram.voip.VoIPService.java

@Override
public void onCreate() {
    super.onCreate();
    FileLog.d("=============== VoIPService STARTING ===============");
    AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1
            && am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER) != null) {
        int outFramesPerBuffer = Integer
                .parseInt(am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER));
        VoIPController.setNativeBufferSize(outFramesPerBuffer);
    } else {//from   w  w w.  j  av a2  s  .c  o m
        VoIPController.setNativeBufferSize(
                AudioTrack.getMinBufferSize(48000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT)
                        / 2);
    }
    final SharedPreferences preferences = getSharedPreferences("mainconfig", MODE_PRIVATE);
    VoIPServerConfig.setConfig(preferences.getString("voip_server_config", "{}"));
    if (System.currentTimeMillis() - preferences.getLong("voip_server_config_updated", 0) > 24 * 3600000) {
        ConnectionsManager.getInstance().sendRequest(new TLRPC.TL_phone_getCallConfig(), new RequestDelegate() {
            @Override
            public void run(TLObject response, TLRPC.TL_error error) {
                if (error == null) {
                    String data = ((TLRPC.TL_dataJSON) response).data;
                    VoIPServerConfig.setConfig(data);
                    preferences.edit().putString("voip_server_config", data)
                            .putLong("voip_server_config_updated",
                                    BuildConfig.DEBUG ? 0 : System.currentTimeMillis())
                            .apply();
                }
            }
        });
    }
    try {
        controller = new VoIPController();
        controller.setConnectionStateListener(this);
        controller.setConfig(MessagesController.getInstance().callPacketTimeout / 1000.0,
                MessagesController.getInstance().callConnectTimeout / 1000.0,
                preferences.getInt("VoipDataSaving", VoIPController.DATA_SAVING_NEVER));

        cpuWakelock = ((PowerManager) getSystemService(POWER_SERVICE))
                .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "telegram-voip");
        cpuWakelock.acquire();

        btAdapter = am.isBluetoothScoAvailableOffCall() ? BluetoothAdapter.getDefaultAdapter() : null;

        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(ACTION_HEADSET_PLUG);
        if (btAdapter != null) {
            filter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
            filter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
        }
        filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
        filter.addAction(getPackageName() + ".END_CALL");
        filter.addAction(getPackageName() + ".DECLINE_CALL");
        filter.addAction(getPackageName() + ".ANSWER_CALL");
        registerReceiver(receiver, filter);

        ConnectionsManager.getInstance().setAppPaused(false, false);

        soundPool = new SoundPool(1, AudioManager.STREAM_VOICE_CALL, 0);
        spConnectingId = soundPool.load(this, R.raw.voip_connecting, 1);
        spRingbackID = soundPool.load(this, R.raw.voip_ringback, 1);
        spFailedID = soundPool.load(this, R.raw.voip_failed, 1);
        spEndId = soundPool.load(this, R.raw.voip_end, 1);
        spBusyId = soundPool.load(this, R.raw.voip_busy, 1);

        am.registerMediaButtonEventReceiver(new ComponentName(this, VoIPMediaButtonReceiver.class));

        if (btAdapter != null && btAdapter.isEnabled()) {
            int headsetState = btAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
            updateBluetoothHeadsetState(headsetState == BluetoothProfile.STATE_CONNECTED);
            if (headsetState == BluetoothProfile.STATE_CONNECTED)
                am.setBluetoothScoOn(true);
            for (StateListener l : stateListeners)
                l.onAudioSettingsChanged();
        }

        NotificationCenter.getInstance().addObserver(this, NotificationCenter.appDidLogout);
    } catch (Exception x) {
        FileLog.e("error initializing voip controller", x);
        callFailed();
    }
}

From source file:com.allthatseries.RNAudioPlayer.Playback.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.//  w  w w .  ja  v a  2 s.  c o  m
 */
private void createMediaPlayerIfNeeded() {
    if (mMediaPlayer == null) {
        mMediaPlayer = new MediaPlayer();

        // Make sure the media 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.
        mMediaPlayer.setWakeMode(mContext.getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

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

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (mMediaPlayer != null) {
                    try {
                        Thread.sleep(500);
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                                    Intent intent = new Intent("update-position-event");
                                    intent.putExtra("currentPosition", mMediaPlayer.getCurrentPosition());
                                    LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
                                }
                            }
                        });

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    } else {
        mMediaPlayer.reset();
    }
}

From source file:com.naman14.timber.musicplayer.MusicService.java

@Override
public void onCreate() {
    if (D)/*from  w w  w  .j a  v a  2 s.  c o m*/
        Log.d(TAG, "Creating service");
    super.onCreate();

    mNotificationManager = NotificationManagerCompat.from(this);

    // gets a pointer to the playback state store
    mPlaybackStateStore = MusicPlaybackState.getInstance(this);
    mSongPlayCount = SongPlayCount.getInstance(this);
    mRecentStore = RecentStore.getInstance(this);

    mHandlerThread = new HandlerThread("MusicPlayerHandler", android.os.Process.THREAD_PRIORITY_BACKGROUND);
    mHandlerThread.start();

    mPlayerHandler = new MusicPlayerHandler(this, mHandlerThread.getLooper());

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mMediaButtonReceiverComponent = new ComponentName(getPackageName(),
            MediaButtonIntentReceiver.class.getName());
    mAudioManager.registerMediaButtonEventReceiver(mMediaButtonReceiverComponent);

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

    mPreferences = getSharedPreferences("Service", 0);
    //        mCardId = getCardId();

    //        registerExternalStorageListener();

    mPlayer = new MultiPlayer2(this);
    mPlayer.setHandler(mPlayerHandler);

    // Initialize the intent filter and each action
    final IntentFilter filter = new IntentFilter();
    filter.addAction(SERVICECMD);
    filter.addAction(TOGGLEPAUSE_ACTION);
    filter.addAction(PAUSE_ACTION);
    filter.addAction(STOP_ACTION);
    filter.addAction(NEXT_ACTION);
    filter.addAction(PREVIOUS_ACTION);
    filter.addAction(PREVIOUS_FORCE_ACTION);
    filter.addAction(REPEAT_ACTION);
    filter.addAction(SHUFFLE_ACTION);

    // Attach the broadcast listener
    registerReceiver(mIntentReceiver, filter);

    //        mMediaStoreObserver = new MediaStoreObserver(mPlayerHandler);
    //        getContentResolver().registerContentObserver(
    //                MediaStore.Audio.Media.INTERNAL_CONTENT_URI, true, mMediaStoreObserver);
    //        getContentResolver().registerContentObserver(
    //                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, true, mMediaStoreObserver);

    // Initialize the wake lock
    final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
    mWakeLock.setReferenceCounted(false);

    final Intent shutdownIntent = new Intent(this, MusicService.class);
    shutdownIntent.setAction(SHUTDOWN);

    mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    mShutdownIntent = PendingIntent.getService(this, 0, shutdownIntent, 0);

    scheduleDelayedShutdown();

    //        reloadQueueAfterPermissionCheck();
    notifyChange(QUEUE_CHANGED);
    notifyChange(META_CHANGED);
}

From source file:com.example.socketio.lib.IOConnection.java

/**
 * Sends a plain message to the {@link IOTransport}.
 * //from  w w  w. j a  v  a 2  s  .  c  om
 * @param text
 *            the Text to be send.
 */
private synchronized void sendPlain(String text) {
    if (wakelock == null) {
        // Log.e(TAG, "wakelock==null");
        PowerManager pm = (PowerManager) mContext.getSystemService(Service.POWER_SERVICE);
        wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, wakeLockTag);
    }
    wakelock.acquire();
    if (getState() == STATE_READY)
        try {
            logger.info("> " + text);
            transport.send(text);
        } catch (Exception e) {
            logger.info("IOEx: saving");
            outputBuffer.add(text);
        }
    else {
        outputBuffer.add(text);
    }
    if (wakelock != null && wakelock.isHeld()) {
        wakelock.release();
    }
}

From source file:com.github.wakhub.monodict.activity.FlashcardActivity.java

@Background
void startAutoPlay() {
    PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    wakeLock.acquire();/*from   ww  w  .jav  a2  s.  c o m*/

    autoPlayProgress = AutoPlayProgress.START;

    while (autoPlayLoop()) {
        activityHelper.sleep(500);
    }
    wakeLock.release();
}

From source file:name.setup.dance.StepService.java

private void acquireWakeLock() {
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    int wakeFlags;
    if (mDanceStepAppSettings.wakeAggressively()) {
        wakeFlags = PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP;
    } else if (mDanceStepAppSettings.keepScreenOn()) {
        wakeFlags = PowerManager.SCREEN_DIM_WAKE_LOCK;
    } else {/* w w  w  . j av a  2s  .  co  m*/
        wakeFlags = PowerManager.PARTIAL_WAKE_LOCK;
    }
    wakeLock = pm.newWakeLock(wakeFlags, TAG);
    wakeLock.acquire();
}

From source file:com.appdevper.mediaplayer.app.LocalPlayback.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.//from w w w. jav  a  2s  .co m
 */
private void createMediaPlayerIfNeeded() {
    LogHelper.d(TAG, "createMediaPlayerIfNeeded. needed? ", (mMediaPlayer == null));
    if (mMediaPlayer == null) {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setWakeMode(mService.getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnErrorListener(this);
        mMediaPlayer.setOnSeekCompleteListener(this);
    } else {
        mMediaPlayer.reset();
    }
}

From source file:com.devalladolid.musictoday.MusicService.java

@Override
public void onCreate() {
    if (D)//from  ww  w  .j a  v  a2s.c  o  m
        Log.d(TAG, "Creating service");
    super.onCreate();

    mNotificationManager = NotificationManagerCompat.from(this);

    // gets a pointer to the playback state store
    mPlaybackStateStore = MusicPlaybackState.getInstance(this);
    mSongPlayCount = SongPlayCount.getInstance(this);
    mRecentStore = RecentStore.getInstance(this);

    mHandlerThread = new HandlerThread("MusicPlayerHandler", android.os.Process.THREAD_PRIORITY_BACKGROUND);
    mHandlerThread.start();

    mPlayerHandler = new MusicPlayerHandler(this, mHandlerThread.getLooper());

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mMediaButtonReceiverComponent = new ComponentName(getPackageName(),
            MediaButtonIntentReceiver.class.getName());
    mAudioManager.registerMediaButtonEventReceiver(mMediaButtonReceiverComponent);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        setUpMediaSession();

    mPreferences = getSharedPreferences("Service", 0);
    mCardId = getCardId();

    registerExternalStorageListener();

    mPlayer = new MultiPlayer(this);
    mPlayer.setHandler(mPlayerHandler);

    // Initialize the intent filter and each action
    final IntentFilter filter = new IntentFilter();
    filter.addAction(SERVICECMD);
    filter.addAction(TOGGLEPAUSE_ACTION);
    filter.addAction(PAUSE_ACTION);
    filter.addAction(STOP_ACTION);
    filter.addAction(NEXT_ACTION);
    filter.addAction(PREVIOUS_ACTION);
    filter.addAction(PREVIOUS_FORCE_ACTION);
    filter.addAction(REPEAT_ACTION);
    filter.addAction(SHUFFLE_ACTION);
    // Attach the broadcast listener
    registerReceiver(mIntentReceiver, filter);

    mMediaStoreObserver = new MediaStoreObserver(mPlayerHandler);
    getContentResolver().registerContentObserver(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, true,
            mMediaStoreObserver);
    getContentResolver().registerContentObserver(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, true,
            mMediaStoreObserver);

    // Initialize the wake lock
    final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
    mWakeLock.setReferenceCounted(false);

    final Intent shutdownIntent = new Intent(this, MusicService.class);
    shutdownIntent.setAction(SHUTDOWN);

    mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    mShutdownIntent = PendingIntent.getService(this, 0, shutdownIntent, 0);

    scheduleDelayedShutdown();

    reloadQueueAfterPermissionCheck();
    notifyChange(QUEUE_CHANGED);
    notifyChange(META_CHANGED);
}

From source file:org.runnerup.gpstracker.GpsTracker.java

private void wakelock(boolean get) {
    if (mWakeLock != null) {
        if (mWakeLock.isHeld()) {
            mWakeLock.release();/*  w w w.  j  a  v a 2  s  .c  o m*/
        }
        mWakeLock = null;
    }
    if (get) {
        PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "RunnerUp");
        if (mWakeLock != null) {
            mWakeLock.acquire();
        }
    }
}