Example usage for android.content Context POWER_SERVICE

List of usage examples for android.content Context POWER_SERVICE

Introduction

In this page you can find the example usage for android.content Context POWER_SERVICE.

Prototype

String POWER_SERVICE

To view the source code for android.content Context POWER_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.os.PowerManager for controlling power management, including "wake locks," which let you keep the device on while you're running long tasks.

Usage

From source file:the.joevlc.AudioService.java

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

    // Get libVLC instance
    try {/* w  ww  . ja  v  a2 s  . co m*/
        mLibVLC = LibVLC.getInstance();
    } catch (LibVlcException e) {
        e.printStackTrace();
    }

    Thread.setDefaultUncaughtExceptionHandler(new VlcCrashHandler());

    mCallback = new HashMap<IAudioServiceCallback, Integer>();
    mMediaList = new ArrayList<Media>();
    mPrevious = new Stack<Media>();
    mEventManager = EventManager.getInstance();
    mRemoteControlClientReceiverComponent = new ComponentName(getPackageName(),
            RemoteControlClientReceiver.class.getName());

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

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

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

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

    AudioUtil.prepareCacheFolder(this);
}

From source file:org.videolan.vlc.AudioService.java

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

    // Get libVLC instance
    try {//from   w  ww  . j  a v a2 s . com
        mLibVLC = Util.getLibVlcInstance();
    } catch (LibVlcException e) {
        e.printStackTrace();
    }

    Thread.setDefaultUncaughtExceptionHandler(new VlcCrashHandler());

    mCallback = new HashMap<IAudioServiceCallback, Integer>();
    mMediaList = new ArrayList<Media>();
    mPrevious = new Stack<Media>();
    mEventHandler = EventHandler.getInstance();
    mRemoteControlClientReceiverComponent = new ComponentName(getPackageName(),
            RemoteControlClientReceiver.class.getName());

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

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

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

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

    AudioUtil.prepareCacheFolder(this);
}

From source file:com.dattasmoon.pebble.plugin.NotificationService.java

@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
    // handle the prefs changing, because of how accessibility services
    // work, sharedprefsonchange listeners don't work
    if (watchFile.lastModified() > lastChange) {
        loadPrefs();/*w  w  w .ja va2 s.  c  om*/
    }
    if (Constants.IS_LOGGABLE) {
        Log.i(Constants.LOG_TAG, "Service: Mode is: " + String.valueOf(mode.ordinal()));
    }
    // if we are off, don't do anything.
    if (mode == Mode.OFF) {
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Service: Mode is off, not sending any notifications");
        }
        return;
    }

    //handle quiet hours
    if (quiet_hours) {

        Calendar c = Calendar.getInstance();
        Date now = new Date(0, 0, 0, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE));
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Checking quiet hours. Now: " + now.toString() + " vs "
                    + quiet_hours_before.toString() + " and " + quiet_hours_after.toString());
        }

        if (quiet_hours_before.after(quiet_hours_after)) {
            if (now.after(quiet_hours_after) && now.before(quiet_hours_before)) {
                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG, "Time is during quiet time. Returning.");
                }
                return;
            }

        } else if (now.before(quiet_hours_before) || now.after(quiet_hours_after)) {
            if (Constants.IS_LOGGABLE) {
                Log.i(Constants.LOG_TAG, "Time is before or after the quiet hours time. Returning.");
            }
            return;
        }

    }

    // handle if they only want notifications
    if (notifications_only) {
        if (event != null) {
            Parcelable parcelable = event.getParcelableData();
            if (!(parcelable instanceof Notification)) {

                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG,
                            "Event is not a notification and notifications only is enabled. Returning.");
                }
                return;
            }
        }
    }
    if (no_ongoing_notifs) {
        Parcelable parcelable = event.getParcelableData();
        if (parcelable instanceof Notification) {
            Notification notif = (Notification) parcelable;
            if ((notif.flags & Notification.FLAG_ONGOING_EVENT) == Notification.FLAG_ONGOING_EVENT) {
                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG,
                            "Event is a notification, notification flag contains ongoing, and no ongoing notification is true. Returning.");
                }
                return;
            }
        } else {
            if (Constants.IS_LOGGABLE) {
                Log.i(Constants.LOG_TAG, "Event is not a notification.");
            }
        }
    }

    // Handle the do not disturb screen on settings
    PowerManager powMan = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
    if (Constants.IS_LOGGABLE) {
        Log.d(Constants.LOG_TAG, "NotificationService.onAccessibilityEvent: notifScreenOn=" + notifScreenOn
                + "  screen=" + powMan.isScreenOn());
    }
    if (!notifScreenOn && powMan.isScreenOn()) {
        return;
    }

    if (event == null) {
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Event is null. Returning.");
        }
        return;
    }
    if (Constants.IS_LOGGABLE) {
        Log.i(Constants.LOG_TAG, "Event: " + event.toString());
    }

    // main logic
    PackageManager pm = getPackageManager();

    String eventPackageName;
    if (event.getPackageName() != null) {
        eventPackageName = event.getPackageName().toString();
    } else {
        eventPackageName = "";
    }
    if (Constants.IS_LOGGABLE) {
        Log.i(Constants.LOG_TAG, "Service package list is: ");
        for (String strPackage : packages) {
            Log.i(Constants.LOG_TAG, strPackage);
        }
        Log.i(Constants.LOG_TAG, "End Service package list");
    }

    switch (mode) {
    case EXCLUDE:
        // exclude functionality
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Mode is set to exclude");
        }

        for (String packageName : packages) {
            if (packageName.equalsIgnoreCase(eventPackageName)) {
                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG, packageName + " == " + eventPackageName
                            + " which is on the exclude list. Returning.");
                }
                return;
            }
        }
        break;
    case INCLUDE:
        // include only functionality
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Mode is set to include only");
        }
        boolean found = false;
        for (String packageName : packages) {
            if (packageName.equalsIgnoreCase(eventPackageName)) {
                found = true;
                break;
            }
        }
        if (!found) {
            Log.i(Constants.LOG_TAG, eventPackageName + " was not found in the include list. Returning.");
            return;
        }
        break;
    }

    // get the title
    String title = "";
    try {
        boolean renamed = false;
        for (int i = 0; i < pkg_renames.length(); i++) {
            if (pkg_renames.getJSONObject(i).getString("pkg").equalsIgnoreCase(eventPackageName)) {
                renamed = true;
                title = pkg_renames.getJSONObject(i).getString("to");
            }
        }
        if (!renamed) {
            title = pm.getApplicationLabel(pm.getApplicationInfo(eventPackageName, 0)).toString();
        }
    } catch (NameNotFoundException e) {
        title = eventPackageName;
    } catch (JSONException e) {
        title = eventPackageName;
    }

    // get the notification text
    String notificationText = event.getText().toString();
    // strip the first and last characters which are [ and ]
    notificationText = notificationText.substring(1, notificationText.length() - 1);

    if (notification_extras) {
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Fetching extras from notification");
        }
        Parcelable parcelable = event.getParcelableData();
        if (parcelable instanceof Notification) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                notificationText += "\n" + getExtraBigData((Notification) parcelable, notificationText.trim());
            } else {
                notificationText += "\n" + getExtraData((Notification) parcelable, notificationText.trim());
            }

        }
    }

    // Check ignore lists
    for (int i = 0; i < ignores.length(); i++) {
        try {
            JSONObject ignore = ignores.getJSONObject(i);
            String app = ignore.getString("app");
            boolean exclude = ignore.optBoolean("exclude", true);
            boolean case_insensitive = ignore.optBoolean("insensitive", true);
            if ((!app.equals("-1")) && (!eventPackageName.equalsIgnoreCase(app))) {
                //this rule doesn't apply to all apps and this isn't the app we're looking for.
                continue;
            }
            String regex = "";
            if (case_insensitive) {
                regex += "(?i)";
            }
            if (!ignore.getBoolean("raw")) {
                regex += Pattern.quote(ignore.getString("match"));
            } else {
                regex += ignore.getString("match");
            }
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(notificationText);
            if (m.find()) {
                if (exclude) {
                    if (Constants.IS_LOGGABLE) {
                        Log.i(Constants.LOG_TAG, "Notification text of '" + notificationText + "' matches: '"
                                + regex + "' and exclude is on. Returning");
                    }
                    return;
                }
            } else {
                if (!exclude) {
                    if (Constants.IS_LOGGABLE) {
                        Log.i(Constants.LOG_TAG, "Notification text of '" + notificationText
                                + "' does not match: '" + regex + "' and include is on. Returning");
                    }
                    return;
                }

            }
        } catch (JSONException e) {
            continue;
        }
    }

    // Send the alert to Pebble

    sendToPebble(title, notificationText);

    if (Constants.IS_LOGGABLE) {
        Log.i(Constants.LOG_TAG, event.toString());
        Log.i(Constants.LOG_TAG, event.getPackageName().toString());
    }
}

From source file:org.interactiverobotics.headset_launcher.LauncherService.java

/**
 *    ?.//from  w w  w . ja v  a  2s  .co  m
 *
 */
@SuppressWarnings("deprecation")
private void unlockScreen() {

    final KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);

    mKeyguardLock = keyguardManager.newKeyguardLock("HeadsetLauncherLock");

    mKeyguardLock.disableKeyguard();

    final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

    mWakeLock = powerManager.newWakeLock(
            PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE,
            "HeadsetLauncherWakeLock");

    mWakeLock.acquire();

    // ?  ?  ?

    mTimeoutHandler.postDelayed(mTimeoutRunnable, Constants.NOTIFICATION_TIMEOUT * 1000);
}

From source file:com.example.activitydemo.app.service.GameService.java

public void startGame(final GameConfig config) {
    // Start ourselves!
    startService(new Intent(this, GameService.class));

    synchronized (mBinderService) {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (mWakeLock == null) {
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityGameService");
            mWakeLock.setReferenceCounted(false);
        }/*from www .  j  a v a2  s.co m*/

        mWakeLock.acquire();
    }

    mTextToSpeechEnabled = config.useSound;

    Log.d(TAG, "Starting game!");
    sayString(getString(R.string.game_started));
    setGameCallbacks(new GameLogic(this, config, GameTrack.BASIC_TRACK));

    startForeground();
    registerActivityUpdates();
    mGameHandler.startGame();

    if (mBinderService.isConnected()) {
        try {
            mBinderService.mCallbacks.onStartGame();
        } catch (RemoteException e) {
        }
    }
}

From source file:com.linroid.pushapp.service.DownloadService.java

/**
 * ?/*from w ww  .ja v  a  2 s  . co  m*/
 * @param pack 
 */
private void onDownloadComplete(Pack pack) {
    Timber.d("%s ?,?:%s", pack.getAppName(), pack.getPath());
    int toastResId = R.string.toast_download_complete;
    if (autoInstall.getValue()) {
        startActivity(IntentUtil.installApk(pack.getPath()));
        if (AndroidUtil.isAccessibilitySettingsOn(this, ApkAutoInstallService.class.getCanonicalName())) {
            PowerManager powermanager = ((PowerManager) getSystemService(Context.POWER_SERVICE));
            PowerManager.WakeLock wakeLock = powermanager.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                    | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP),
                    "Install Worker, FULL WAKE LOCK");
            wakeLock.acquire();
            wakeLock.release();
            KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
            //                if(keyguardManager.isDeviceLocked()) {
            final KeyguardManager.KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("unLock");
            keyguardLock.disableKeyguard();
            //                }
            ApkAutoInstallService.addInstallPackage(pack);
            toastResId = R.string.toast_start_install;
        } else {
            toastResId = R.string.toast_download_complete;
        }
    }
    Toast.makeText(this, getString(toastResId, pack.getAppName()), Toast.LENGTH_SHORT).show();

}

From source file:net.sourceforge.kalimbaradio.androidapp.service.DownloadServiceImpl.java

@Override
public void onCreate() {
    Util.setUncaughtExceptionHandler(this);
    super.onCreate();

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

    mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
        @Override//from  www . jav a  2s.  c o  m
        public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
            handleError(new Exception("MediaPlayer error: " + what + " (" + more + ")"));
            return false;
        }
    });

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

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

    instance = this;
    lifecycleSupport.onCreate();
}

From source file:com.tfg.sawan.bsecure.beacon.UriBeaconDiscoveryService.java

@Override
@SuppressWarnings("deprecation")
public int onStartCommand(Intent intent, int flags, int startId) {
    // Since sometimes the lists have values when onStartCommand gets called
    initializeLists();//  w  w w.  ja  v a2  s  .co m
    // Start scanning only if the screen is on
    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    // NOTE: use powerManager.isInteractive() when minsdk >= 20
    if (powerManager.isScreenOn()) {
        mCanUpdateNotifications = false;
        mHandler.postDelayed(mNotificationUpdateGateTimeout, NOTIFICATION_UPDATE_GATE_DURATION);
        startSearchingForUriBeacons();
        mMdnsUrlDiscoverer.startScanning();
        mSsdpUrlDiscoverer.startScanning();
    }

    //make sure the service keeps running
    return START_STICKY;
}

From source file:butter.droid.base.torrent.TorrentService.java

public void streamTorrent(@NonNull final String torrentUrl) {
    Timber.d("streamTorrent");
    mStopped = false;/*from  w  w  w .j  a  v  a  2s  .c o m*/

    if (mTorrentStream.isStreaming())
        return;

    Timber.d("Starting streaming");

    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    if (mWakeLock != null && mWakeLock.isHeld()) {
        mWakeLock.release();
        mWakeLock = null;
    }
    mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKE_LOCK);
    mWakeLock.acquire();

    TorrentOptions options = mTorrentStream.getOptions();
    options.setRemoveFilesAfterStop(true);
    options.setMaxConnections(PrefUtils.get(this, Prefs.LIBTORRENT_CONNECTION_LIMIT, 200));
    options.setMaxDownloadSpeed(PrefUtils.get(this, Prefs.LIBTORRENT_DOWNLOAD_LIMIT, 0));
    options.setMaxUploadSpeed(PrefUtils.get(this, Prefs.LIBTORRENT_UPLOAD_LIMIT, 0));
    options.setSaveLocation(PrefUtils.get(this, Prefs.STORAGE_LOCATION, ButterApplication.getStreamDir()));
    mTorrentStream.setOptions(options);

    mIsReady = false;
    mTorrentStream.addListener(this);
    mTorrentStream.startStream(torrentUrl);
}

From source file:com.gecq.musicwave.player.MediaButtonIntentReceiver.java

private static void acquireWakeLockAndSendMessage(Context context, Message msg, long delay) {
    if (mWakeLock == null) {
        Context appContext = context.getApplicationContext();
        PowerManager pm = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "music wave headset button");
        mWakeLock.setReferenceCounted(false);
    }//  ww  w  .  ja  v a 2  s  .  co  m
    if (DEBUG)
        Log.v(TAG, "Acquiring wake lock and sending " + msg.what);
    // Make sure we don't indefinitely hold the wake lock under any circumstances
    mWakeLock.acquire(10000);

    mHandler.sendMessageDelayed(msg, delay);
}