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.keithcassidy.finishline.FinishLineService.java

private void acquireWakeLock() {
    try {/*  w  w  w  .j  av  a  2 s.c o m*/
        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (powerManager == null) {
            Log.e(TAG, "powerManager is null.");
            return;
        }

        if (wakeLock == null) {
            wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
            if (wakeLock == null) {
                Log.e(TAG, "wakeLock is null.");
                return;
            }
        }

        if (!wakeLock.isHeld()) {
            wakeLock.acquire();
            if (!wakeLock.isHeld()) {
                Log.e(TAG, "Unable to hold wakeLock.");
            }
        }

    } catch (RuntimeException e) {
        Log.e(TAG, "Caught RuntimeException exception in acquireWakeLock", e);
    }
}

From source file:com.putlocker.upload.DownloadService.java

@Override
protected void onHandleIntent(Intent intent) {
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Download Wakelock");
    wl.acquire();//from  ww w .jav a 2 s . com

    ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    WifiLock wifiLock = null;
    // We only want to aquire the wifi wake lock
    if (mWifi.isConnected()) {
        wifiLock = ((WifiManager) this.getSystemService(Context.WIFI_SERVICE))
                .createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY, "WlanSilencerScanLock");
        wifiLock.acquire();
    }

    if (intent.hasExtra(JOB_EXTRA_DOWNLOAD)) {
        handleDownloadIntent(intent);
    } else {
        handleUploadIntent(intent);
    }

    if (wifiLock != null && wifiLock.isHeld()) {
        wifiLock.release();
    }

    wl.release();
}

From source file:com.snt.bt.recon.activities.MainActivity.java

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(com.snt.bt.recon.R.layout.activity_main);
    ButterKnife.bind(this);
    logDebug("Activity", "######################## On Create ########################");
    //Lock orientation
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    //Leave screen on
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    //leave cpu on
    wl = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
            "wlTag");
    wl.acquire();/* ww  w.  j a  v  a2s.c o  m*/

    //For device id
    telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

    //for connectivity
    cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    try {

        logDebug("DatabaseTest", "Reading all trips..");
        List<Trip> trips = db.getAll(Trip.class);
        for (Trip trip : trips) {
            String log = "session id: " + trip.getSessionId() + " imei: " + trip.getImei() + " transport: "
                    + trip.getTransport() + " TS: " + trip.getTimestampStart() + " TE: "
                    + trip.getTimestampEnd() + " upload status: " + trip.getUploadStatus();
            logDebug("DatabaseTest", log);
        }
        logDebug("DatabaseTest", "Reading all locations..");
        List<GPSLocation> locs = db.getAll(GPSLocation.class);
        for (GPSLocation loc : locs) {
            String log = "loc id: " + loc.getLocationId() + " sess id: " + loc.getSessionId() + " timestamp: "
                    + loc.getTimestamp() + " upload status: " + loc.getUploadStatus();
            logDebug("DatabaseTest", log);
        }
        logDebug("DatabaseTest", "Reading all bc..");
        List<BluetoothClassicEntry> bcs = db.getAll(BluetoothClassicEntry.class);
        for (BluetoothClassicEntry bc : bcs) {
            String log = "sess id: " + bc.getSessionId() + " loc id: " + bc.getLocationId() + " upload status: "
                    + bc.getUploadStatus();
            logDebug("DatabaseTest", log);
        }
        logDebug("DatabaseTest", "Reading all ble..");
        List<BluetoothLowEnergyEntry> bles = db.getAll(BluetoothLowEnergyEntry.class);
        for (BluetoothLowEnergyEntry ble : bles) {
            String log = "sess id: " + ble.getSessionId() + " loc id: " + ble.getLocationId()
                    + " upload status: " + ble.getUploadStatus();
            logDebug("DatabaseTest", log);
        }
    } catch (InstantiationException | IllegalAccessException e) {
        e.printStackTrace();
    }

    //Show select transpot mode
    new TransportMode(this).show();

    // Show EULA
    new AppEULA(this).show();

    //displayFeedbackDialog();

    //avtivity recognition start
    mActivityRecognitionScan = new ActivityRecognitionUtil(this);
    mActivityRecognitionScan.startActivityRecognitionScan();
    //Filter the Intent and register broadcast receiver
    registerReceiver(ActivityRecognitionReceiver, new IntentFilter("ImActive"));

    //gps
    gpsStatusCheck();

    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    locationListener = new MyLocationListener();
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 3, locationListener);

    //bt
    mBluetoothUtils = new BluetoothUtils(this);

    //ble
    mLeDeviceStore = new BluetoothLeDeviceStore();
    mLeScanner = new BluetoothLeScanner(mLeScanCallback, mBluetoothUtils);
    //bc
    mBcDeviceList = new ArrayList<>();

    final Handler h = new Handler();
    final int delay = 60000;

    h.postDelayed(new Runnable() {
        public void run() {
            syncServerDatabase();

            h.postDelayed(this, delay);
        }
    }, delay);

    //Clean BLE table in case device last timestamp is > 10 seconds
    final Handler h2 = new Handler();
    h2.postDelayed(new Runnable() {
        public void run() {
            //clear old ble devices
            for (BluetoothLeDevice device : mLeDeviceStore.getDeviceList()) {
                long diff = System.currentTimeMillis() - device.getTimestamp();
                if (diff > 10000) {
                    mLeDeviceStore.removeDevice(device);
                    //Refresh the listview
                    final EasyObjectCursor<BluetoothLeDevice> c = mLeDeviceStore.getDeviceCursor();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mLeDeviceListAdapter.swapCursor(c);
                        }
                    });
                }
            }

            h2.postDelayed(this, 1000);//1 sec
        }
    }, 1000);
}

From source file:org.ohmage.reminders.types.location.LocTrigService.java

private static void acquireRecvrWakeLock(Context context) {

    if (mRecvrWakeLock == null) {
        PowerManager powerMan = (PowerManager) context.getSystemService(POWER_SERVICE);

        mRecvrWakeLock = powerMan.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, RECR_WAKE_LOCK_TAG);
        mRecvrWakeLock.setReferenceCounted(true);
    }//w ww. j  av a2s.c  om

    if (!mRecvrWakeLock.isHeld()) {
        mRecvrWakeLock.acquire();
    }
}

From source file:com.prod.intelligent7.engineautostart.ConnectDaemonService.java

private IBinder confirmJob(Intent intent, int flags, int startId) {
    // A client is binding to the service with bindService()
    String command = intent.getExtras().getString(DAEMON_COMMAND);
    //Object obj1=intent.getExtras().getClassLoader();
    //confirmDaemonAlive();
    if (command != null) {
        if (command.length() < 3)
            return null;
        intent.putExtra(DAEMON_COMMAND, "EXECUTED");
        if (command.equalsIgnoreCase(GET_BINDER)) {
            String sType = intent.getExtras().getString(SERVICE_TYPE);
            if (sType != null && sType.equalsIgnoreCase(URGENT)) {
                serverHeartBit = 10 * 1000;
                urgentMailBox.clear();/*w ww.  ja v  a 2s.  c om*/
            }
            return new UrgentMailBinder();
        }
        sendCommand(command);
        return null;
    }
    command = intent.getExtras().getString(ALARM_DONE);
    if (command == null)
        return null;
    PowerManager.WakeLock wlR = ((PowerManager) getSystemService(Context.POWER_SERVICE))
            .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "KEEP_THREAD_ALIVE");
    wlR.acquire();
    switch (command) {
    case ALARM_BIT:
        //mDaemon.hasCommand=true;
        //mDaemon.interrupt();
        confirmDaemonAlive();
        //startServerHearBeatAlarm();
        break;
    case ALARM_1BOOT:
        String param = intent.getExtras().getString(ALARM_1BOOT);
        long on_time = Long.parseLong(param);
        sendCommand("M5-" + new DecimalFormat("00").format(on_time / 60000));
        //startOneBootAlarm();
        break;
    case ALARM_NBOOT:
        Log.i("ALARM_SET", "got recurring start intent");
        GregorianCalendar gToday = new GregorianCalendar(
                TimeZone.getTimeZone(getResources().getString(R.string.my_time_zone_en)));
        if (gToday.get(Calendar.HOUR_OF_DAY) >= 7 && gToday.get(Calendar.HOUR_OF_DAY) < 19)
            break;
        String params = intent.getExtras().getString(ALARM_NBOOT);
        int idx = params.indexOf("-");
        long last4 = Long.parseLong(params.substring(0, idx));
        sendCommand("M5-" + new DecimalFormat("00").format(last4 / 60000));
        long off_time = Long.parseLong(params.substring(idx + 1));
        setRecurringBootAlarm(last4, off_time);
        break;
    case ALARM_HOUR:
        //if (heartBitIntent==null) startServerHearBeatAlarm();
        if (oneBootIntent == null)
            startOneBootAlarm();
        if (recurringBootIntent == null)
            startRecurringBootAlarm();
        //reStartScheduleAlarms();
        startHourlyCheckAlarm();
        break;
    default:
        break;
    }
    wlR.release();

    return null;//mBinder;
}

From source file:com.inloc.dr.StepService.java

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

From source file:edu.missouri.bas.service.SensorService.java

@SuppressWarnings("deprecation")
@Override/*ww w  .  ja  v a2  s  .co  m*/
public void onCreate() {

    super.onCreate();
    Log.d(TAG, "Starting sensor service");
    mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
    soundsMap = new HashMap<Integer, Integer>();
    soundsMap.put(SOUND1, mSoundPool.load(this, R.raw.bodysensor_alarm, 1));
    soundsMap.put(SOUND2, mSoundPool.load(this, R.raw.voice_notification, 1));

    serviceContext = this;

    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    bluetoothMacAddress = mBluetoothAdapter.getAddress();
    mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    //Get location manager
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    activityRecognition = new ActivityRecognitionScan(getApplicationContext());
    activityRecognition.startActivityRecognitionScan();

    mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

    serviceWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "SensorServiceLock");
    serviceWakeLock.acquire();

    //Initialize start time
    stime = System.currentTimeMillis();

    //Setup calendar object
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(stime);

    /*
     * Setup notification manager
     */

    notification = new Notification(R.drawable.icon2, "Recorded", System.currentTimeMillis());
    notification.defaults = 0;
    notification.flags |= Notification.FLAG_ONGOING_EVENT;
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    Intent notifyIntent = new Intent(Intent.ACTION_MAIN);
    notifyIntent.setClass(this, MainActivity.class);

    /*
     * Display notification that service has started
     */
    notification.tickerText = "Sensor Service Running";
    PendingIntent contentIntent = PendingIntent.getActivity(SensorService.this, 0, notifyIntent,
            Notification.FLAG_ONGOING_EVENT);
    notification.setLatestEventInfo(SensorService.this, getString(R.string.app_name),
            "Recording service started at: " + cal.getTime().toString(), contentIntent);

    notificationManager.notify(SensorService.SERVICE_NOTIFICATION_ID, notification);

    // locationControl = new LocationControl(this, mLocationManager, 1000 * 60, 200, 5000);   

    IntentFilter activityResultFilter = new IntentFilter(XMLSurveyActivity.INTENT_ACTION_SURVEY_RESULTS);
    SensorService.this.registerReceiver(alarmReceiver, activityResultFilter);

    IntentFilter sensorDataFilter = new IntentFilter(SensorService.ACTION_SENSOR_DATA);
    SensorService.this.registerReceiver(alarmReceiver, sensorDataFilter);
    Log.d(TAG, "Sensor service created.");

    try {
        prepareIO();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    prepareAlarms();

    Intent startSensors = new Intent(SensorService.ACTION_START_SENSORS);
    this.sendBroadcast(startSensors);

    Intent scheduleCheckConnection = new Intent(SensorService.ACTION_SCHEDULE_CHECK);
    scheduleCheck = PendingIntent.getBroadcast(serviceContext, 0, scheduleCheckConnection, 0);
    mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + 1000 * 60 * 5, 1000 * 60 * 5, scheduleCheck);
    mLocationClient = new LocationClient(this, this, this);
}

From source file:com.adityarathi.muo.services.AudioPlaybackService.java

/**
 * Initializes the MediaPlayer objects for this service session.
 *///from w w  w. ja  v a  2 s  .  com
private void initMediaPlayers() {

    /*
     * Release the MediaPlayer objects if they are still valid.
     */
    if (mMediaPlayer != null) {
        mMediaPlayer.release();
        mMediaPlayer = null;
    }

    if (mMediaPlayer2 != null) {
        getMediaPlayer2().release();
        mMediaPlayer2 = null;
    }

    mMediaPlayer = new MediaPlayer();
    mMediaPlayer2 = new MediaPlayer();
    setCurrentMediaPlayer(1);

    getMediaPlayer().reset();
    getMediaPlayer2().reset();

    //Loop the players if the repeat mode is set to repeat the current song.
    if (getRepeatMode() == Common.REPEAT_SONG) {
        getMediaPlayer().setLooping(true);
        getMediaPlayer2().setLooping(true);
    }

    try {
        mMediaPlayer.setWakeMode(mContext, PowerManager.PARTIAL_WAKE_LOCK);
        getMediaPlayer2().setWakeMode(mContext, PowerManager.PARTIAL_WAKE_LOCK);
    } catch (Exception e) {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer2 = new MediaPlayer();
        setCurrentMediaPlayer(1);
    }

    //Set the mediaPlayers' stream sources.
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    getMediaPlayer2().setAudioStreamType(AudioManager.STREAM_MUSIC);

}

From source file:com.owncloud.android.media.MediaService.java

/**
 * Makes sure the media player exists and has been reset. This will create the media player
 * if needed. reset the existing media player if one already exists.
 *//*from  www. j a va2  s.co m*/
protected void createMediaPlayerIfNeeded() {
    if (mPlayer == null) {
        mPlayer = new MediaPlayer();

        // make sure the CPU won't go to sleep while media is playing
        mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

        // the media player will notify the service 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.fastbootmobile.encore.service.PlaybackService.java

/**
 * Called when the service is created//ww w .ja  v  a  2 s  .c  om
 */
@Override
public void onCreate() {
    super.onCreate();
    mListenLogger = new ListenLogger(this);
    mPrefetcher = new Prefetcher(this);

    mCommandsHandlerThread = new HandlerThread("PlaybackServiceCommandsHandler");
    mCommandsHandlerThread.start();

    mCommandsHandler = new CommandHandler(this, mCommandsHandlerThread);

    // Register package manager to receive updates
    mPacManReceiver = new PacManReceiver();
    IntentFilter pacManFilter = new IntentFilter();
    pacManFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
    pacManFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
    pacManFilter.addAction(Intent.ACTION_PACKAGE_FULLY_REMOVED);
    pacManFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
    pacManFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
    pacManFilter.addDataScheme("package");
    registerReceiver(mPacManReceiver, pacManFilter);

    // Really Google, I'd love to use your new APIs... But they're not working. If you use
    // the new Lollipop metadata system, you lose Bluetooth AVRCP since the Bluetooth
    // package still use the old RemoteController system.
    /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    mRemoteMetadata = new RemoteMetadataManagerv21(this);
    } else*/ {
        mRemoteMetadata = new RemoteMetadataManager(this);
    }

    ProviderAggregator.getDefault().addUpdateCallback(this);

    // Native playback initialization
    mNativeHub = new NativeHub(getApplicationContext());
    mNativeSink = new NativeAudioSink();
    mNativeHub.setSinkPointer(mNativeSink.getPlayer().getHandle());
    mNativeHub.setOnAudioWrittenListener(this);
    mNativeHub.onStart();

    mDSPProcessor = new DSPProcessor(this);
    mDSPProcessor.restoreChain(this);

    // Plugins initialization
    PluginsLookup.getDefault().initialize(getApplicationContext());
    PluginsLookup.getDefault().registerProviderListener(this);

    List<ProviderConnection> connections = PluginsLookup.getDefault().getAvailableProviders();
    for (ProviderConnection conn : connections) {
        if (conn.getBinder(false) != null) {
            assignProviderAudioSocket(conn);
        } else {
            Log.w(TAG, "Cannot assign audio socket to " + conn.getIdentifier() + ", binder is null");
        }
    }

    // Setup
    mIsStopping = false;

    // Bind to all provider
    List<ProviderConnection> providers = PluginsLookup.getDefault().getAvailableProviders();
    for (ProviderConnection pc : providers) {
        try {
            IMusicProvider binder = pc.getBinder(false);
            if (binder != null) {
                binder.registerCallback(mProviderCallback);
            }
        } catch (RemoteException e) {
            Log.e(TAG, "Cannot register callback", e);
        }
    }

    // Register AutoMix manager
    mCallbacks.add(AutoMixManager.getDefault());

    // Setup notification system
    mNotification = new ServiceNotification(this);
    mNotification.setOnNotificationChangedListener(new ServiceNotification.NotificationChangedListener() {
        @Override
        public void onNotificationChanged(ServiceNotification notification) {
            NotificationManagerCompat nmc = NotificationManagerCompat.from(PlaybackService.this);
            if (mIsForeground) {
                notification.notify(nmc);
                mIsForeground = true;
            } else {
                notification.notify(PlaybackService.this);
            }

            BitmapDrawable albumArt = notification.getAlbumArt();
            mRemoteMetadata.setAlbumArt(albumArt);
        }
    });

    // Setup lockscreen remote controls
    mRemoteMetadata.setup();

    // Setup playback wakelock (but don't acquire it yet)
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "OmniMusicPlayback");

    // Restore preferences
    SharedPreferences prefs = getSharedPreferences(SERVICE_SHARED_PREFS, MODE_PRIVATE);
    mRepeatMode = prefs.getBoolean(PREF_KEY_REPEAT, false);
    mShuffleMode = prefs.getBoolean(PREF_KEY_SHUFFLE, false);

    // TODO: Use callbacks
    // Restore playback queue after one second - we have multiple things to wait here:
    //  - The callbacks of the main app's UI
    //  - The providers connecting
    //  - The providers ready to send us data
    mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            SharedPreferences queuePrefs = getSharedPreferences(QUEUE_SHARED_PREFS, MODE_PRIVATE);
            mPlaybackQueue.restore(queuePrefs);
            mCurrentTrack = queuePrefs.getInt("current", -1);
            mCurrentTrackLoaded = false;
            mNotification.setHasNext(mPlaybackQueue.size() > 1 || (mPlaybackQueue.size() > 0 && mRepeatMode));
        }
    }, 1000);
}