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.droid.app.fotobot.FotoBot.java

/**
 *      ? ,   ?,    ?// w w  w. j ava 2 s  . c o  m
 *
 * @param h
 * @param delay
 */
public void fbpause(final Handler h, final int delay) {

    if (delay > 3) {
        SendMessage(".", MSG_INFO);
    }

    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");

    wakeLock.acquire();

    Thread thread = new Thread() {
        public void run() {

            PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
            PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                    "MyWakelockTag");

            wakeLock.acquire();

            int n = 5;

            if (delay >= wake_up_interval) {
                n = (int) (delay - ((delay / wake_up_interval) * long_pause * 2));
            }

            for (int i = 1; i <= n; i++) {

                if (i % 3 == 0) {
                    if (isCharging_before != isCharging) {

                        if (isCharging) {
                            SendMessage(getResources().getString(R.string.voltage_restored));
                            if (isCharging_sms)
                                sendSMS(sms_voltage_alert_number,
                                        getResources().getString(R.string.voltage_restored));
                        } else {
                            SendMessage(getResources().getString(R.string.no_voltage));
                            if (isCharging_sms)
                                sendSMS(sms_voltage_alert_number,
                                        getResources().getString(R.string.no_voltage));
                        }

                        isCharging_before = isCharging;

                    }
                }

                Message msg = Message.obtain(); // Creates an new Message instance

                // we make 1 sec for each n
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if (getstatus() == 3) {
                    return;
                }

                if (i % 5 == 0 && sms_check_file) {
                    // checking for sms file each 5 seconds during big pause between photos
                    File sms_file = null;

                    //                        sms_file = new File((getApplicationContext().getFilesDir().toString() + "/sms.txt"));
                    sms_file = new File(work_dir + "/sms.txt");

                    if (sms_file.isFile()) {

                        sms = file2array(sms_file.toString());

                        sms_getdata();

                        try {
                            TimeUnit.SECONDS.sleep(3);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        for (int ind = 0; ind < sms.size(); ind++) {
                            SendMessage(sms.get(ind).toString(), MSG_INFO);
                        }

                        SendMessage("SMS:", MSG_INFO);

                        sms_file.delete();

                        sms.clear();

                        sms_update_db = true;

                        if (sms_status && sms_incoming_passwd.equals(sms_passwd)) {
                            sendSMS(sms_sender_num, "Bat: " + battery_level + "%\n" + "Upd: " + Photo_Frequency
                                    + "sec\n" + "Flash: " + Use_Flash + "\n" + "Net: " + network);
                            sms_status = false;
                        }

                        if (sms_net_status && sms_incoming_passwd.equals(sms_passwd)) {
                            sendSMS(sms_sender_num,
                                    "Net: " + network + "\n" + "Ch: " + Network_Channel + "\n" + "Method: "
                                            + Network_Connection_Method + "\n" + "Mail: " + EMail_Recepient
                                            + "\n");
                            sms_net_status = false;
                        }

                        if (sms_email_status && sms_incoming_passwd.equals(sms_passwd)) {
                            sendSMS(sms_sender_num,
                                    "Mail: " + EMail_Recepient + "\n" + "FMail: " + EMail_Sender + "\n"
                                            + "FMailP: " + EMail_Sender_Password + "\n" + "SMTPHost: "
                                            + SMTP_Host + "\n" + "SMTPPort: " + SMTP_Port + "\n");
                            sms_email_status = false;
                        }

                        if (sms_media_status && sms_incoming_passwd.equals(sms_passwd)) {
                            sendSMS(sms_sender_num, "Flash: " + Use_Flash + "\n" + "JPEG: " + JPEG_Compression
                                    + "\n" + "Fc: " + make_photo_fc + "\n" + "Bc: " + make_photo_bc + "\n");
                            sms_media_status = false;
                        }

                        if (sms_incoming_passwd.equals(sms_passwd) && sms_help) {
                            sendSMS(sms_sender_num, sms_commands_list());
                            sms_help = false;
                        }

                        // drop password before next usage
                        sms_incoming_passwd = "";

                        return;

                    } else {

                    }

                }

                if (i % wake_up_interval == 0 && frame_delay) {

                    String cmd = null;

                    try {

                        if (Build.VERSION.SDK_INT <= 12) {
                            cmd = "logcat -v long -d -f " + work_dir + "/logfile.txt" + " Logs:* FotoBot:* *:S";
                        } else {
                            cmd = "logcat -v long -d -f " + work_dir + "/logfile.txt";
                        }
                        Runtime.getRuntime().exec(cmd);

                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.d("LOG_TAG", "logcat2file doesn't work");
                    }

                    try {
                        TimeUnit.SECONDS.sleep(short_pause);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    // ?    log_size,  ? 
                    File logcat_file;
                    logcat_file = new File(work_dir + "/logfile.txt");

                    boolean fileExists = logcat_file.isFile();

                    if (fileExists) {

                        if (logcat_file.length() / 1000 > log_size) {
                            clearLog();
                        }

                    } else {
                        SendMessage("logfile.txt doesn't exist.");
                    }

                    SendMessage(".", MSG_INFO);

                    if (camera == null) {
                        Log.d(LOG_TAG, "camera == null");
                        SendMessage("..", MSG_INFO);
                        try {
                            camera = Camera.open();
                            SendMessage(".", MSG_INFO);
                            Log.d(LOG_TAG, "Camera has been successfully opened");
                        } catch (Exception e) {
                            SendMessage("...", MSG_INFO);
                            Log.d(LOG_TAG, "Problem with camera opening");
                            e.printStackTrace();
                        }
                    }

                    try {
                        camera.setPreviewDisplay(holder);
                        camera.startPreview();
                        SendMessage(".", MSG_INFO);
                        Log.d(LOG_TAG, "Preview started");
                    } catch (Exception e) {
                        e.printStackTrace();
                        SendMessage("...", MSG_INFO);
                        Log.d(LOG_TAG, "Problem with starting of preview");
                    }

                    try {
                        TimeUnit.SECONDS.sleep(long_pause);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if (camera != null) {
                        Log.d(LOG_TAG, "Camera is busy");
                        try {
                            camera.stopPreview();
                            camera.release();
                            camera = null;
                            Log.d(LOG_TAG, "Camera unlocked");
                        } catch (Exception e) {
                            SendMessage("...", MSG_INFO);
                        }

                    }

                    try {
                        TimeUnit.SECONDS.sleep(long_pause);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }

            }
        }

    };
    thread.start();

    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    wakeLock.release();

}

From source file:com.csipsimple.service.SipService.java

/**
 * Ask to take the control of the wifi and the partial wake lock if
 * configured//from   w  ww .  j  a v a  2  s. co  m
 */
private synchronized void acquireResources() {
    if (holdResources) {
        return;
    }

    // Add a wake lock for CPU if necessary
    if (prefsWrapper.getPreferenceBooleanValue(SipConfigManager.USE_PARTIAL_WAKE_LOCK)) {
        PowerManager pman = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (wakeLock == null) {
            wakeLock = pman.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "com.csipsimple.SipService");
            wakeLock.setReferenceCounted(false);
        }
        // Extra check if set reference counted is false ???
        if (!wakeLock.isHeld()) {
            wakeLock.acquire();
        }
    }

    // Add a lock for WIFI if necessary
    WifiManager wman = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    if (wifiLock == null) {
        int mode = WifiManager.WIFI_MODE_FULL;
        if (Compatibility.isCompatible(9)
                && prefsWrapper.getPreferenceBooleanValue(SipConfigManager.LOCK_WIFI_PERFS)) {
            mode = 0x3; // WIFI_MODE_FULL_HIGH_PERF 
        }
        wifiLock = wman.createWifiLock(mode, "com.csipsimple.SipService");
        wifiLock.setReferenceCounted(false);
    }
    if (prefsWrapper.getPreferenceBooleanValue(SipConfigManager.LOCK_WIFI) && !wifiLock.isHeld()) {
        WifiInfo winfo = wman.getConnectionInfo();
        if (winfo != null) {
            DetailedState dstate = WifiInfo.getDetailedStateOf(winfo.getSupplicantState());
            // We assume that if obtaining ip addr, we are almost connected
            // so can keep wifi lock
            if (dstate == DetailedState.OBTAINING_IPADDR || dstate == DetailedState.CONNECTED) {
                if (!wifiLock.isHeld()) {
                    wifiLock.acquire();
                }
            }
        }
    }
    holdResources = true;
}

From source file:com.chen.emailsync.SyncManager.java

private void acquireWakeLock(long id) {
    synchronized (mWakeLocks) {
        Long lock = mWakeLocks.get(id);
        if (lock == null) {
            if (mWakeLock == null) {
                PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
                mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MAIL_SERVICE");
                mWakeLock.acquire();/*from w  w  w  .j a v  a2 s.  c o  m*/
                // STOPSHIP Remove
                log("+WAKE LOCK ACQUIRED");
            }
            mWakeLocks.put(id, System.currentTimeMillis());
        }
    }
}

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);//w w w .ja v  a  2 s.com
    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:mp.teardrop.PlaybackService.java

@Override
public void onCreate() {
    HandlerThread thread = new HandlerThread("PlaybackService", Process.THREAD_PRIORITY_DEFAULT);
    thread.start();//from w  ww  .  j  a  va  2  s  . c  om

    mTimeline = new SongTimeline(this);
    mTimeline.setCallback(this);
    int state = loadState();

    mPlayCounts = new PlayCountsHelper(this);

    mMediaPlayer = getNewMediaPlayer();
    mBastpUtil = new BastpUtil();
    mReadahead = new ReadaheadThread();
    mReadahead.start();

    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

    SharedPreferences settings = getSettings(this);
    settings.registerOnSharedPreferenceChangeListener(this);
    mNotificationMode = Integer.parseInt(settings.getString(PrefKeys.NOTIFICATION_MODE, "1"));
    mScrobble = settings.getBoolean(PrefKeys.SCROBBLE, false);
    mIdleTimeout = settings.getBoolean(PrefKeys.USE_IDLE_TIMEOUT, false)
            ? settings.getInt(PrefKeys.IDLE_TIMEOUT, 3600)
            : 0;

    Song.mCoverLoadMode = settings.getBoolean(PrefKeys.COVERLOADER_ANDROID, true)
            ? Song.mCoverLoadMode | Song.COVER_MODE_ANDROID
            : Song.mCoverLoadMode & ~(Song.COVER_MODE_ANDROID);
    Song.mCoverLoadMode = settings.getBoolean(PrefKeys.COVERLOADER_VANILLA, true)
            ? Song.mCoverLoadMode | Song.COVER_MODE_VANILLA
            : Song.mCoverLoadMode & ~(Song.COVER_MODE_VANILLA);
    Song.mCoverLoadMode = settings.getBoolean(PrefKeys.COVERLOADER_SHADOW, true)
            ? Song.mCoverLoadMode | Song.COVER_MODE_SHADOW
            : Song.mCoverLoadMode & ~(Song.COVER_MODE_SHADOW);

    mHeadsetOnly = settings.getBoolean(PrefKeys.HEADSET_ONLY, false);
    mStockBroadcast = settings.getBoolean(PrefKeys.STOCK_BROADCAST, false);
    mInvertNotification = settings.getBoolean(PrefKeys.NOTIFICATION_INVERTED_COLOR, false);
    mNotificationAction = createNotificationAction(settings);
    mHeadsetPause = getSettings(this).getBoolean(PrefKeys.HEADSET_PAUSE, true);
    mShakeAction = settings.getBoolean(PrefKeys.ENABLE_SHAKE, false)
            ? Action.getAction(settings, PrefKeys.SHAKE_ACTION, Action.NextSong)
            : Action.Nothing;
    mShakeThreshold = settings.getInt(PrefKeys.SHAKE_THRESHOLD, 80) / 10.0f;

    mReplayGainTrackEnabled = settings.getBoolean(PrefKeys.ENABLE_TRACK_REPLAYGAIN, false);
    mReplayGainAlbumEnabled = settings.getBoolean(PrefKeys.ENABLE_ALBUM_REPLAYGAIN, false);
    mReplayGainBump = settings.getInt(PrefKeys.REPLAYGAIN_BUMP, 75); /* seek bar is 150 -> 75 == middle == 0 */
    mReplayGainUntaggedDeBump = settings.getInt(PrefKeys.REPLAYGAIN_UNTAGGED_DEBUMP,
            150); /* seek bar is 150 -> == 0 */

    mReadaheadEnabled = settings.getBoolean(PrefKeys.ENABLE_READAHEAD, false);

    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TeardropMusicLock");

    mReceiver = new Receiver();
    IntentFilter filter = new IntentFilter();
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    filter.addAction(Intent.ACTION_SCREEN_ON);
    registerReceiver(mReceiver, filter);

    getContentResolver().registerContentObserver(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, true, mObserver);

    CompatIcs.registerRemote(this, mAudioManager);

    mLooper = thread.getLooper();
    mHandler = new Handler(mLooper, this);

    initWidgets();

    updateState(state);
    setCurrentSong(0, false);

    sInstance = this;
    synchronized (sWait) {
        sWait.notifyAll();
    }

    mAccelFiltered = 0.0f;
    mAccelLast = SensorManager.GRAVITY_EARTH;
    setupSensor();
}

From source file:me.spadival.podmode.PodModeService.java

@Override
public void onCreate() {

    IntentFilter usbFilter = new IntentFilter();
    usbFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    usbFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
    registerReceiver(mUsbReceiver, usbFilter);
    // mProvider = RemoteMetadataProvider.getInstance(this);

    // mProvider.setOnMetadataChangeListener(mMetadataListner);
    // mProvider.acquireRemoteControls();
    LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(this);
    IntentFilter notifyFilter = new IntentFilter();
    notifyFilter.addAction(NOTIFYACTION);
    bManager.registerReceiver(mNotifyReceiver, notifyFilter);

    mSerialHost = new FTDriver((UsbManager) getSystemService(Context.USB_SERVICE));

    mSerialDevice = new FT311UARTInterface(this, null);

    // Get the local Bluetooth adapter
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    // Get a set of currently paired devices
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

    mBluetoothDevice = null;//from   w  w w.j a  v a  2s.  c om

    /*   // If there are paired devices, add each one to the ArrayAdapter
       if (pairedDevices.size() > 0) {
          for (BluetoothDevice device : pairedDevices) {
    if (device.getName().equals("PodModeBT"))
       mBluetoothDevice = device;
          }
       }
            
       if (mBluetoothDevice != null) {
          mBTDevice = new BluetoothSerialService(this, mHandler);
          mBTDevice.connect(mBluetoothDevice);
       } */

    // Create the Wifi lock (this does not acquire the lock, this just
    // creates it)
    mWifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
            .createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");

    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

    // Create the retriever and start an asynchronous task that will prepare
    // it.

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    mRetriever = new MusicRetriever(getContentResolver(), getApplicationContext(), true, prefs);

    // mRetriever.switchToMainPlaylist();

    prefs.registerOnSharedPreferenceChangeListener((OnSharedPreferenceChangeListener) this);

    mNowPlaying = prefs.getInt("nowplaying", 0);

    String mBaudrate = prefs.getString("baud_rate", "57600");

    if (mBaudrate.equals("57600"))
        mSerialBaudRate = FTDriver.BAUD57600;
    else if (mBaudrate.equals("38400"))
        mSerialBaudRate = FTDriver.BAUD38400;
    else if (mBaudrate.equals("19200"))
        mSerialBaudRate = FTDriver.BAUD19200;

    (new PrepareMusicRetrieverTask(mRetriever, this)).execute();

    // create the Audio Focus Helper, if the Audio Focus feature is
    // available (SDK 8 or above)
    if (android.os.Build.VERSION.SDK_INT >= 8)
        mAudioFocusHelper = new AudioFocusHelper(getApplicationContext(), this);
    else
        mAudioFocus = AudioFocus.Focused; // no focus feature, so we always
    // "have" audio focus

    boolean wakeLockPreferred = prefs.getBoolean("wakelock", false);

    if (podWakeLock == null && wakeLockPreferred) {
        PowerManager powerMgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
        podWakeLock = powerMgr.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, WAKETAG);
        podWakeLock.acquire();
    }

    PackageManager pxm = getPackageManager();
    Intent mediaIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);

    List<ResolveInfo> mAppsInfo = pxm.queryBroadcastReceivers(mediaIntent, 0);

    mSimpleRemoteApp = prefs.getString("selectapp", null);
    mAdvancedRemoteApp = prefs.getString("selectadvancedapp", PACKAGENAME);

    // Make sure App preferences are still valid and Apps haven't been
    // uninstalled.

    if (mAppsInfo.size() > 0) {

        CharSequence[] entryValues = new CharSequence[mAppsInfo.size()];
        CharSequence[] advEntryValues = new CharSequence[mAppsInfo.size() + 1];

        advEntryValues[0] = PACKAGENAME;

        int i = 0;
        for (ResolveInfo info : mAppsInfo) {
            entryValues[i] = (String) info.activityInfo.packageName;
            advEntryValues[i + 1] = (String) info.activityInfo.packageName;

            i++;
        }

        boolean entryFound = false;

        if (mSimpleRemoteApp != null) {
            for (i = 0; i < entryValues.length; i++) {
                if (mSimpleRemoteApp.equals(entryValues[i])) {
                    entryFound = true;
                }
            }
        }

        if (!entryFound) {
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("selectapp", (String) entryValues[0]);
            editor.commit();
            mSimpleRemoteApp = (String) entryValues[0];
        }

        entryFound = false;

        if (mAdvancedRemoteApp != null) {
            for (i = 0; i < advEntryValues.length; i++) {
                if (mAdvancedRemoteApp.equals(advEntryValues[i])) {
                    entryFound = true;
                }
            }
        }

        if (!entryFound) {
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("selectadvancedapp", (String) advEntryValues[0]);
            editor.commit();
            mAdvancedRemoteApp = (String) advEntryValues[0];

        }
    } else {
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("selectadvancedapp", PACKAGENAME);
        editor.commit();
        mAdvancedRemoteApp = PACKAGENAME;
    }

    mAccessoryName = prefs.getString("accessoryName", null);
    mAccessoryMnf = prefs.getString("accessoryMnf", null);
    mAccessoryModel = prefs.getString("accessoryModel", null);

}

From source file:com.newsrob.EntryManager.java

private void switchStorageProvider() {

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

    if (isModelCurrentlyUpdated())
        return;/*from   w  ww  .  j  a v a  2s. co 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();
    }
}

From source file:com.ferdi2005.secondgram.NotificationsController.java

public NotificationsController() {
    notificationManager = NotificationManagerCompat.from(ApplicationLoader.applicationContext);
    SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications",
            Context.MODE_PRIVATE);
    inChatSoundEnabled = preferences.getBoolean("EnableInChatSound", true);

    try {/*from  www  . j a va2  s  . c  o  m*/
        audioManager = (AudioManager) ApplicationLoader.applicationContext
                .getSystemService(Context.AUDIO_SERVICE);
    } catch (Exception e) {
        FileLog.e(e);
    }
    try {
        alarmManager = (AlarmManager) ApplicationLoader.applicationContext
                .getSystemService(Context.ALARM_SERVICE);
    } catch (Exception e) {
        FileLog.e(e);
    }

    try {
        PowerManager pm = (PowerManager) ApplicationLoader.applicationContext
                .getSystemService(Context.POWER_SERVICE);
        notificationDelayWakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "lock");
        notificationDelayWakelock.setReferenceCounted(false);
    } catch (Exception e) {
        FileLog.e(e);
    }

    notificationDelayRunnable = new Runnable() {
        @Override
        public void run() {
            FileLog.e("delay reached");
            if (!delayedPushMessages.isEmpty()) {
                showOrUpdateNotification(true);
                delayedPushMessages.clear();
            }
            try {
                if (notificationDelayWakelock.isHeld()) {
                    notificationDelayWakelock.release();
                }
            } catch (Exception e) {
                FileLog.e(e);
            }
        }
    };
}

From source file:com.android.exchange.ExchangeService.java

private void acquireWakeLock(long id) {
    synchronized (mWakeLocks) {
        Boolean lock = mWakeLocks.get(id);
        if (lock == null) {
            if (mWakeLock == null) {
                PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
                mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MAIL_SERVICE");
                mWakeLock.acquire();/*from  www.  j  ava  2 s  . c o m*/
                //log("+WAKE LOCK ACQUIRED");
            }
            mWakeLocks.put(id, true);
        }
    }
}

From source file:com.andrew.apolloMod.service.ApolloService.java

@SuppressLint({ "WorldWriteableFiles", "WorldReadableFiles" })
@Override/*from w w w.  j ava2s .  com*/
public void onCreate() {
    super.onCreate();

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    ComponentName rec = new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName());
    mAudioManager.registerMediaButtonEventReceiver(rec);
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setComponent(rec);
    PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, mediaButtonIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    if (Constants.isApi14Supported()) {
        mRemoteControlClient = new RemoteControlClient(mediaPendingIntent);
        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(APOLLO_PREFERENCES, 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);
    commandFilter.addAction(CYCLEREPEAT_ACTION);
    commandFilter.addAction(TOGGLESHUFFLE_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);
}