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.example.android.supportv4.media.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.  j av  a2s  .c om
 */
private void createMediaPlayerIfNeeded() {
    Log.d(TAG, "createMediaPlayerIfNeeded. needed? " + (mMediaPlayer == null));
    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(mService.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);
    } else {
        mMediaPlayer.reset();
    }
}

From source file:com.detroitteatime.autocarfinder.Main.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);

    myMenu = menu;//from w w  w. ja v a2s  .  c o m

    int setting = data1.getInt(WAKE_LOCK_SETTING, PowerManager.PARTIAL_WAKE_LOCK);

    if (setting == PowerManager.PARTIAL_WAKE_LOCK) {

        myMenu.findItem(R.id.set_wakelock).setTitle("Change to FULL_WAKE_LOCK");

    } else {

        myMenu.findItem(R.id.set_wakelock).setTitle("Change to PARTIAL_WAKE_LOCK");

    }

    return true;
}

From source file:com.example.android.mediabrowserservice.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.//  ww  w  .j  ava  2  s .  com
 */
private void createMediaPlayerIfNeeded() {
    LogHelper.d(TAG, "createMediaPlayerIfNeeded. needed? ", (mMediaPlayer == null));
    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(mService.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);
    } else {
        mMediaPlayer.reset();
    }
}

From source file:com.nogago.android.tracks.services.TrackRecordingService.java

/**
 * Tries to acquire a partial wake lock if not already acquired. Logs errors
 * and gives up trying in case the wake lock cannot be acquired.
 *///from  w  w w  . j av  a 2s. co  m
private void acquireWakeLock() {
    try {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (pm == null) {
            Log.e(TAG, "TrackRecordingService: Power manager not found!");
            return;
        }
        if (wakeLock == null) {
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
            if (wakeLock == null) {
                Log.e(TAG, "TrackRecordingService: Could not create wake lock (null).");
                return;
            }
        }
        if (!wakeLock.isHeld()) {
            wakeLock.acquire();
            if (!wakeLock.isHeld()) {
                Log.e(TAG, "TrackRecordingService: Could not acquire wake lock.");
            }
        }
    } catch (RuntimeException e) {
        Log.e(TAG, "TrackRecordingService: Caught unexpected exception: " + e.getMessage(), e);
    }
}

From source file:br.com.viniciuscr.notification2android.mediaPlayer.MediaPlaybackService.java

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

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

    Intent i = new Intent(Intent.ACTION_MEDIA_BUTTON);
    i.setComponent(rec);//from  w  ww  .  j  ava  2s.c  o m
    PendingIntent pi = PendingIntent.getBroadcast(this /*context*/, 0 /*requestCode, ignored*/, i /*intent*/,
            0 /*flags*/);
    mRemoteControlClient = new RemoteControlClient(pi);
    mAudioManager.registerRemoteControlClient(mRemoteControlClient);

    int flags = RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_NEXT
            | RemoteControlClient.FLAG_KEY_MEDIA_PLAY | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE
            | RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_STOP;
    mRemoteControlClient.setTransportControlFlags(flags);

    mPreferences = getSharedPreferences("Music", MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE);
    mCardId = MusicUtils.getCardId(this);

    registerExternalStorageListener();

    // Needs to be done in this thread, since otherwise ApplicationContext.getPowerManager() crashes.
    mPlayer = new MultiPlayer();
    mPlayer.setHandler(mMediaplayerHandler);

    reloadQueue();
    notifyChange(QUEUE_CHANGED);
    notifyChange(META_CHANGED);

    IntentFilter commandFilter = new IntentFilter();
    commandFilter.addAction(SERVICECMD);
    commandFilter.addAction(TOGGLEPAUSE_ACTION);
    commandFilter.addAction(PAUSE_ACTION);
    commandFilter.addAction(NEXT_ACTION);
    commandFilter.addAction(PREVIOUS_ACTION);
    registerReceiver(mIntentReceiver, commandFilter);

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

    // If the service was idle, but got killed before it stopped itself, the
    // system will relaunch it. Make sure it gets stopped again in that case.
    Message msg = mDelayedStopHandler.obtainMessage();
    mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}

From source file:org.restcomm.app.qoslib.Services.Intents.IntentHandler.java

/**
 * constructor//from ww w  .j  a  va 2  s  .  c o  m
 */
public IntentHandler(MainService owner, DataMonitorStats dataMonitorStats) {
    this.owner = owner;
    this.dataMonitorStats = dataMonitorStats;
    PowerManager powerManager = (PowerManager) owner.getSystemService(owner.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
    gson = new Gson();
    reportManager = owner.getReportManager();
}

From source file:com.example.android.AudioArchive.playback.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  .j  a  va 2 s  .c o m
 */
private void createMediaPlayerIfNeeded() {
    LogHelper.d(TAG, "createMediaPlayerIfNeeded. needed? ", (mMediaPlayer == null));
    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);
    } else {
        mMediaPlayer.reset();
    }
}

From source file:com.detroitteatime.autocarfinder.Main.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int itemId = item.getItemId();
    if (itemId == R.id.sleep) {
        Intent intent = new Intent(Main.this, SleepTimeDialog.class);
        startActivity(intent);// w ww .j  av a  2  s  .c  o m
        return true;
    } else if (itemId == R.id.no_sleep) {
        editor1.putInt(Main.SLEEP_MODE_KEY, Main.SLEEP_MODE_FALSE);
        editor1.commit();
    } else if (itemId == R.id.set_wakelock) {
        int setting = data1.getInt(WAKE_LOCK_SETTING, PowerManager.PARTIAL_WAKE_LOCK);
        if (setting == PowerManager.PARTIAL_WAKE_LOCK) {

            editor1.putInt(WAKE_LOCK_SETTING, PowerManager.FULL_WAKE_LOCK);
            editor1.commit();

            myMenu.findItem(R.id.set_wakelock).setTitle("Change to PARTIAL_WAKE_LOCK");

        } else {

            editor1.putInt(WAKE_LOCK_SETTING, PowerManager.PARTIAL_WAKE_LOCK);
            editor1.commit();

            myMenu.findItem(R.id.set_wakelock).setTitle("Change to FULL_WAKE_LOCK");

        }
    } else if (itemId == R.id.legal) {
        String LicenseInfo = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(getApplicationContext());
        Builder LicenseDialog = new Builder(Main.this);
        LicenseDialog.setTitle("Legal Notices");
        LicenseDialog.setMessage(LicenseInfo);
        LicenseDialog.show();
        return true;
    } else if (itemId == R.id.info) {
        String info = getString(R.string.how_to);
        Builder InfoDialog = new Builder(Main.this);
        InfoDialog.setTitle("Legal Notices");
        InfoDialog.setMessage(info);
        InfoDialog.show();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

From source file:jackpal.androidterm.Term.java

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

    Log.v(TermDebug.LOG_TAG, "onCreate");

    mPrivateAlias = new ComponentName(this, RemoteInterface.PRIVACT_ACTIVITY_ALIAS);

    if (icicle == null)
        onNewIntent(getIntent());/*from   w ww  .  ja  va  2s  .c o m*/

    final SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    mSettings = new TermSettings(getResources(), mPrefs);
    mPrefs.registerOnSharedPreferenceChangeListener(this);

    boolean vimflavor = this.getPackageName().matches(".*vim.androidterm.*");

    if (!vimflavor && mSettings.doPathExtensions()) {
        mPathReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                String path = makePathFromBundle(getResultExtras(false));
                if (intent.getAction().equals(ACTION_PATH_PREPEND_BROADCAST)) {
                    mSettings.setPrependPath(path);
                } else {
                    mSettings.setAppendPath(path);
                }
                mPendingPathBroadcasts--;

                if (mPendingPathBroadcasts <= 0 && mTermService != null) {
                    populateViewFlipper();
                    populateWindowList();
                }
            }
        };

        Intent broadcast = new Intent(ACTION_PATH_BROADCAST);
        if (AndroidCompat.SDK >= 12) {
            broadcast.addFlags(FLAG_INCLUDE_STOPPED_PACKAGES);
        }
        mPendingPathBroadcasts++;
        sendOrderedBroadcast(broadcast, PERMISSION_PATH_BROADCAST, mPathReceiver, null, RESULT_OK, null, null);

        if (mSettings.allowPathPrepend()) {
            broadcast = new Intent(broadcast);
            broadcast.setAction(ACTION_PATH_PREPEND_BROADCAST);
            mPendingPathBroadcasts++;
            sendOrderedBroadcast(broadcast, PERMISSION_PATH_PREPEND_BROADCAST, mPathReceiver, null, RESULT_OK,
                    null, null);
        }
    }

    TSIntent = new Intent(this, TermService.class);
    startService(TSIntent);

    if (AndroidCompat.SDK >= 11) {
        int theme = mSettings.getColorTheme();
        int actionBarMode = mSettings.actionBarMode();
        mActionBarMode = actionBarMode;
        switch (actionBarMode) {
        case TermSettings.ACTION_BAR_MODE_ALWAYS_VISIBLE:
            if (theme == 0) {
                setTheme(R.style.Theme_Holo);
            } else {
                setTheme(R.style.Theme_Holo_Light);
            }
            break;
        case TermSettings.ACTION_BAR_MODE_HIDES + 1:
        case TermSettings.ACTION_BAR_MODE_HIDES:
            if (theme == 0) {
                setTheme(R.style.Theme_Holo_ActionBarOverlay);
            } else {
                setTheme(R.style.Theme_Holo_Light_ActionBarOverlay);
            }
            break;
        }
    } else {
        mActionBarMode = TermSettings.ACTION_BAR_MODE_ALWAYS_VISIBLE;
    }

    setContentView(R.layout.term_activity);
    mViewFlipper = (TermViewFlipper) findViewById(VIEW_FLIPPER);
    setFunctionKeyListener();

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TermDebug.LOG_TAG);
    WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    int wifiLockMode = WifiManager.WIFI_MODE_FULL;
    if (AndroidCompat.SDK >= 12) {
        wifiLockMode = WIFI_MODE_FULL_HIGH_PERF;
    }
    mWifiLock = wm.createWifiLock(wifiLockMode, TermDebug.LOG_TAG);

    ActionBarCompat actionBar = ActivityCompat.getActionBar(this);
    if (actionBar != null) {
        mActionBar = actionBar;
        actionBar.setNavigationMode(ActionBarCompat.NAVIGATION_MODE_LIST);
        actionBar.setDisplayOptions(0, ActionBarCompat.DISPLAY_SHOW_TITLE);
        if (mActionBarMode >= TermSettings.ACTION_BAR_MODE_HIDES) {
            actionBar.hide();
        }
    }

    mHaveFullHwKeyboard = checkHaveFullHwKeyboard(getResources().getConfiguration());
    setSoftInputMode(mHaveFullHwKeyboard);

    if (mFunctionBar == -1)
        mFunctionBar = mSettings.showFunctionBar() ? 1 : 0;
    if (mFunctionBar == 1)
        setFunctionBar(mFunctionBar);

    updatePrefs();
    permissionCheckExternalStorage();
    mAlreadyStarted = true;
}

From source file:com.newsrob.EntryManager.java

private void switchStorageProvider() {

    Log.d(TAG, "Switch Storage Provider");

    if (isModelCurrentlyUpdated())
        return;/*from   w  ww.j  a  va  2 s .  c o m*/

    final String newPrefValue = getSharedPreferences().getString(SETTINGS_STORAGE_PROVIDER_KEY, null);
    final String oldStorageProviderClass = fileContextAdapter.getClass().getName();

    final String newStorageProviderClass = STORAGE_PROVIDER_SD_CARD.equals(newPrefValue)
            ? SdCardStorageAdapter.class.getName()
            : PhoneMemoryStorageAdapter.class.getName();
    if (!oldStorageProviderClass.equals(newStorageProviderClass)) {

        runningThread = new Thread(new Runnable() {

            public void run() {
                final PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
                final PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
                Log.i(TAG, "Wake lock acquired at " + new Date().toString() + ".");
                wl.acquire();
                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                final Timing t = new Timing("Storage Provider Switch", ctx);
                ModelUpdateResult result = null;
                if (isModelCurrentlyUpdated())
                    return;
                try {
                    lockModel("EM.switchStorageProvider.run");
                } catch (final IllegalStateException ise) {
                    return;
                }
                try {

                    Log.i(TAG, "Switching storage providers started at " + new Date().toString() + ".");

                    fireModelUpdateStarted("Switching storage providers", false, true);
                    Log.d(TAG, "Change of storage provider detected.");

                    final List<Job> jobList = new LinkedList<Job>();

                    final Job clearOldStorageProvider = new Job("Clearing Old Storage Provider",
                            EntryManager.this) {

                        @Override
                        public void run() {
                            Log.d(TAG, "Clearing the old storage provider.");
                            doClearCache();
                            if (fileContextAdapter.canWrite())
                                WebPageDownloadDirector.removeAllAssets(fileContextAdapter);
                        }

                    };
                    jobList.add(clearOldStorageProvider);
                    final Job switchStorageProviders = new Job("Switching Storage Providers",
                            EntryManager.this) {

                        @Override
                        public void run() throws Exception {
                            Log.d(TAG, "Establishing new storage provider: " + newStorageProviderClass);
                            fileContextAdapter = newStorageProviderClass.equals(
                                    SdCardStorageAdapter.class.getName()) ? new SdCardStorageAdapter(ctx)
                                            : new PhoneMemoryStorageAdapter(ctx);

                            Log.d(TAG, "New storage provider established.");
                        }

                    };
                    jobList.add(switchStorageProviders);

                    final Job clearNewStorageProvider = new Job("Clearing New Storage Provider",
                            EntryManager.this) {

                        @Override
                        public void run() {
                            Log.d(TAG, "Clearing the new storage provider.");
                            doClearCache();
                            if (fileContextAdapter.canWrite())
                                WebPageDownloadDirector.removeAllAssets(fileContextAdapter);
                        }

                    };
                    jobList.add(clearNewStorageProvider);

                    runJobs(jobList);

                    result = new SwitchStorageProviderResult();

                } catch (final Throwable throwable) {
                    result = new SwitchStorageProviderFailed(throwable);
                    Log.d(TAG, "Problem during switching storage providers.", throwable);
                    t.stop();
                } finally {
                    unlockModel("EM.switchStorageProvider.run");
                    clearCancelState();
                    fireModelUpdateFinished(result);
                    fireStatusUpdated();
                    Log.i(TAG, "Switching storage providers finished at " + new Date().toString() + ".");

                    wl.release();
                    t.stop();
                }
            }

        }, "Storage Provider Switch Worker");
        runningThread.start();
    }
}