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:org.videolan.vlc.PlaybackService.java

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

    if (!VLCInstance.testCompatibleCPU(this)) {
        stopSelf();// w  w w .j  av a  2s  .com
        return;
    }

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    mDetectHeadset = prefs.getBoolean("enable_headset_detection", true);

    mMediaListPlayer = MediaWrapperListPlayer.getInstance();

    mCallback = new HashMap<IPlaybackServiceCallback, Integer>();
    mCurrentIndex = -1;
    mPrevIndex = -1;
    mNextIndex = -1;
    mPrevious = new Stack<Integer>();
    mEventHandler = EventHandler.getInstance();
    mRemoteControlClientReceiverComponent = new ComponentName(BuildConfig.APPLICATION_ID,
            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) VLCApplication.getAppContext().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(ACTION_WIDGET_INIT);
    filter.addAction(Intent.ACTION_HEADSET_PLUG);
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    filter.addAction(VLCApplication.SLEEP_INTENT);
    filter.addAction(VLCApplication.INCOMING_CALL_INTENT);
    filter.addAction(VLCApplication.CALL_ENDED_INTENT);
    registerReceiver(serviceReceiver, filter);

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

    if (!AndroidUtil.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);
    }
    try {
        getPackageManager().getPackageInfo("com.getpebble.android", PackageManager.GET_ACTIVITIES);
        mPebbleEnabled = true;
    } catch (PackageManager.NameNotFoundException e) {
        mPebbleEnabled = false;
    }
}

From source file:github.daneren2005.dsub.service.DownloadServiceImpl.java

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

    new Thread(new Runnable() {
        public void run() {
            Looper.prepare();/*from   w  w  w.  j  a va  2  s.  co m*/

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

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
                    handleError(new Exception("MediaPlayer error: " + what + " (" + more + ")"));
                    return false;
                }
            });

            try {
                Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
                i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, mediaPlayer.getAudioSessionId());
                i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
                sendBroadcast(i);
            } catch (Throwable e) {
                // Froyo or lower
            }

            mediaPlayerLooper = Looper.myLooper();
            mediaPlayerHandler = new Handler(mediaPlayerLooper);
            Looper.loop();
        }
    }).start();

    Util.registerMediaButtonEventReceiver(this);

    if (mRemoteControl == null) {
        // Use the remote control APIs (if available) to set the playback state
        mRemoteControl = RemoteControlClientHelper.createInstance();
        ComponentName mediaButtonReceiverComponent = new ComponentName(getPackageName(),
                MediaButtonIntentReceiver.class.getName());
        mRemoteControl.register(this, mediaButtonReceiverComponent);
    }

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

    SharedPreferences prefs = Util.getPreferences(this);
    try {
        timerDuration = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_SLEEP_TIMER_DURATION, "5"));
    } catch (Throwable e) {
        timerDuration = 5;
    }
    sleepTimer = null;

    keepScreenOn = prefs.getBoolean(Constants.PREFERENCES_KEY_KEEP_SCREEN_ON, false);

    instance = this;
    lifecycleSupport.onCreate();

    if (prefs.getBoolean(Constants.PREFERENCES_EQUALIZER_ON, false)) {
        getEqualizerController();
    }
}

From source file:com.dzt.musicplay.player.AudioService.java

@Override
public void onCreate() {
    super.onCreate();
    GlobalConstants.print_i(getClass(), "onCreate");
    // Get libVLC instance
    try {/*  ww  w . j  a va  2s.c o  m*/
        mLibVLC = VLCInstance.getLibVlcInstance(getApplicationContext());
    } catch (LibVlcException e) {
        e.printStackTrace();
    }
    StartLoadFileThread();

    mCallback = new HashMap<IAudioServiceCallback, Integer>();
    mMediaList = new ArrayList<Media>();
    mCurrentIndex = -1;
    mPrevIndex = -1;
    mNextIndex = -1;
    mPrevious = new Stack<Integer>();
    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(ACTION_WIDGET_INIT);
    filter.addAction(Intent.ACTION_HEADSET_PLUG);
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    filter.addAction(SLEEP_INTENT);
    registerReceiver(serviceReceiver, filter);

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

    if (!LibVlcUtil.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);
    }
    GlobalConstants.print_i(getClass(), "onCreate----end");
}

From source file:at.alladin.rmbt.android.test.RMBTLoopService.java

@Override
public void onCreate() {
    Log.d(TAG, "created");
    super.onCreate();

    partialWakeLock = ((PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE))
            .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "RMBTLoopWakeLock");
    partialWakeLock.acquire();/*from w  w  w .  ja v a 2 s.co  m*/

    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    readConfig();

    geoLocation = new LocalGeoLocation(this);
    geoLocation.start();

    notificationBuilder = createNotificationBuilder();

    startForeground(NotificationIDs.LOOP_ACTIVE, notificationBuilder.build());
    final IntentFilter actionFilter = new IntentFilter(RMBTService.BROADCAST_TEST_FINISHED);
    actionFilter.addAction(RMBTService.BROADCAST_TEST_ABORTED);
    registerReceiver(receiver, actionFilter);

    final IntentFilter rmbtTaskActionFilter = new IntentFilter(RMBTTask.BROADCAST_TEST_START);
    registerReceiver(rmbtTaskReceiver, rmbtTaskActionFilter);

    final Intent alarmIntent = new Intent(ACTION_ALARM, null, this, getClass());
    alarm = PendingIntent.getService(this, 0, alarmIntent, 0);

    if (ConfigHelper.isLoopModeWakeLock(this)) {
        Log.d(TAG, "using dimWakeLock");
        dimWakeLock = ((PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE))
                .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP
                        | PowerManager.ON_AFTER_RELEASE, "RMBTLoopDimWakeLock");
        dimWakeLock.acquire();

        final Intent wakeupAlarmIntent = new Intent(ACTION_WAKEUP_ALARM, null, this, getClass());
        wakeupAlarm = PendingIntent.getService(this, 0, wakeupAlarmIntent, 0);

        final long now = SystemClock.elapsedRealtime();
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, now + 10000, 10000, wakeupAlarm);
    }

    bindService(new Intent(getApplicationContext(), RMBTService.class), this, BIND_AUTO_CREATE);
}

From source file:org.akvo.caddisfly.sensor.colorimetry.liquid.ColorimetryLiquidActivity.java

/**
 * Acquire a wake lock to prevent the screen from turning off during the analysis process.
 *///from  w  ww .j a  v  a  2s  .c om
private void acquireWakeLock() {
    if (wakeLock == null || !wakeLock.isHeld()) {
        PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
        //noinspection deprecation
        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP
                | PowerManager.ON_AFTER_RELEASE, "CameraSensorWakeLock");
        wakeLock.acquire();
    }
}

From source file:com.wifiafterconnect.WifiAuthenticator.java

protected void requestUserParams(ParsedHttpInput parsedPage) {

    debug("Need user input for authentication credentials.");

    if (getContext() == null) {
        error("Context is not set - cannot start WifiAuthenticationActivity");
        return;// w  w  w .ja va  2  s .c om
    }
    // Need to check that screen is not off:
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    if (!pm.isScreenOn()) {
        /** Screen is Off
         * if Disable Wifi is enabled :  
         *    1) Disable wifi (if configured).
         *    2) Post notification with intent to re-enable wifi.
         * otherwise : 
         *  setup Broadcast receiver waiting for SCREEN_ON event, 
         *  which will restart the service on wake-up if wifi is still connected. 
         *  Don't just want to pop the Activity and let it sit there, 
         *  as Wifi may get disconnected and device moved to another location meanwhile 
         **/
        boolean disableWifiOnLock = prefs.getAutoDisableWifi();

        debug("Screen is off and disableWifiOnLock is " + disableWifiOnLock);

        if (disableWifiOnLock) {
            WifiTools.disableWifi(getContext());
            notifyWifiDisabled();
        } else {
            ScreenOnReceiver.register(getContext());
            // don't want to receive repeat notifications - will re-enable when screen comes on
            WifiBroadcastReceiver.setEnabled(getContext(), false);
        }
    } else {
        debug("Screen is on - Starting new activity.");
        /**
         *  Screen is On - so proceeding displaying activity asking for credentials.
         */
        Intent intent = makeIntent(WifiAuthenticatorActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(OPTION_URL, parsedPage.getURL().toString());
        intent.putExtra(OPTION_PAGE, parsedPage.getHtml());
        toIntent(intent);
        debug("Starting activity for intent:" + intent.toString());
        startActivity(intent);
    }
}

From source file:cn.ucai.wechat.ui.MainActivity.java

private void savePower() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        String packageName = getPackageName();
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (!pm.isIgnoringBatteryOptimizations(packageName)) {
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + packageName));
            startActivity(intent);/*from   w w  w  .  ja v  a2s.c o  m*/
        }
    }
}

From source file:dk.bearware.gui.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String serverName = getIntent().getStringExtra(ServerEntry.KEY_SERVERNAME);
    if ((serverName != null) && !serverName.isEmpty())
        setTitle(serverName);//  w w w .j av  a2 s. co  m
    getActionBar().setDisplayHomeAsUpEnabled(true);

    restarting = (savedInstanceState != null);
    accessibilityAssistant = new AccessibilityAssistant(this);
    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mediaButtonEventReceiver = new ComponentName(getPackageName(), MediaButtonEventReceiver.class.getName());
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
            .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    wakeLock.setReferenceCounted(false);

    channelsAdapter = new ChannelListAdapter(this.getBaseContext());
    filesAdapter = new FileListAdapter(this, this, accessibilityAssistant);
    textmsgAdapter = new TextMessageAdapter(this.getBaseContext(), accessibilityAssistant);
    mediaAdapter = new MediaAdapter(this.getBaseContext());

    // Create the adapter that will return a fragment for each of the five
    // primary sections of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    mViewPager.setOnPageChangeListener(mSectionsPagerAdapter);

    setupButtons();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        final MediaPlayer mMediaPlayer;
        mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.silence);
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mMediaPlayer.release();
            }
        });
        mMediaPlayer.start();
    }
}

From source file:org.physical_web.physicalweb.UriBeaconDiscoveryService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // Since sometimes the lists have values when onStartCommand gets called
    initializeLists();//www  .j a  va 2s .c o  m
    // Start scanning only if the screen is on
    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    if (powerManager.isScreenOn()) {
        mCanUpdateNotifications = false;
        mHandler.postDelayed(mNotificationUpdateGateTimeout, NOTIFICATION_UPDATE_GATE_DURATION);
        startSearchingForUriBeacons();
        mMdnsUrlDiscoverer.startScanning();
    }

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

From source file:org.openbmap.services.MasterBrainService.java

/**
 * Acquires wakelock to prevent CPU falling asleep
 *///from w ww. ja va 2s  .  co m
private void requirePowerLock() {
    final PowerManager mgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
    try {
        Log.i(TAG, "Acquiring wakelock " + WAKELOCK_NAME);
        mWakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_NAME);
        mWakeLock.setReferenceCounted(true);
    } catch (final Exception e) {
        Log.e(TAG, "Error acquiring wakelock " + WAKELOCK_NAME + e.toString(), e);
    }
}