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:com.frostwire.android.gui.NotificationUpdateDemon.java

@SuppressWarnings("deprecation")
private boolean isScreenOn() {
    PowerManager pm = (PowerManager) mParentContext.getSystemService(Context.POWER_SERVICE);
    return pm != null && pm.isScreenOn();
}

From source file:com.terminal.ide.TermService.java

@Override
public void onCreate() {
    compat = new ServiceForegroundCompat(this);
    mTermSessions = new ArrayList<TermSession>();

    /**/*w w w.  j  a  v a2 s  . c  o m*/
     * ??
     * @author wanghao
     * @date 2015-3-27
     * ???Activity
     */
    //?intent
    //warning??start.class
    //?mainActivity
    Intent openMainActivityIntent = new Intent(this, mainAvtivity.class);
    Intent openTerminalActivityIntent = new Intent(this, Term.class);
    openTerminalActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    openMainActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    Intent exitTerminalIntent = new Intent(this, ExitService.class);
    Notification sessionBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(getText(R.string.application_terminal))
            .setContentText(getText(R.string.service_notify_text))
            .setContentIntent(PendingIntent.getActivity(this, 0, openMainActivityIntent, 0))
            .setStyle(new NotificationCompat.BigTextStyle().bigText(getText(R.string.service_notify_text)))
            .addAction(R.drawable.ic_action_iconfont_terminal, getText(R.string.notification_open_termianl),
                    PendingIntent.getActivity(this, 0, openTerminalActivityIntent,
                            Intent.FLAG_ACTIVITY_CLEAR_TOP))
            .addAction(R.drawable.ic_action_iconfont_exit, getText(R.string.notification_exit_app),
                    PendingIntent.getService(this, 0, exitTerminalIntent, 0))
            .setOngoing(true).build();
    compat.startForeground(RUNNING_NOTIFICATION, sessionBuilder);

    mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    mPrefs.registerOnSharedPreferenceChangeListener(this);
    mHardKeys.setKeyMappings(mPrefs);

    //Setup the Hard Key Mappings..
    mSettings = new TermSettings(mPrefs);

    //Need to set the HOME Folder and Bash startup..
    //Sometime getfilesdir return NULL ?
    mSessionInit = false;
    File home = getFilesDir();
    if (home != null) {
        initSessions(home);
    }

    //Start a webserver for comms..
    //        mServer = new webserver(this);
    //        mServer.start();

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    //Get a wake lock
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TermDebug.LOG_TAG);
    mScreenLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TermDebug.LOG_TAG);
    mWifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL, TermDebug.LOG_TAG);

    //Get the Initial Values
    //        boolean cpulock     = getStringPref("cpulock","1") == 1 ? true : false;
    //        boolean wifilock    = getStringPref("wifilock","0") == 1 ? true : false;
    //        boolean screenlock  = getStringPref("screenlock","0") == 1 ? true : false;
    setupWakeLocks();

    Log.d(TermDebug.LOG_TAG, "TermService started");

    return;
}

From source file:org.LK8000.LK8000.java

public void initSDL() {
    if (!Loader.loaded)
        return;/*from  www . j a v a 2 s  . c o m*/

    /* check if external storage is available; LK8000 doesn't work as
       long as external storage is being forwarded to a PC */
    String state = Environment.getExternalStorageState();
    Log.d(TAG, "getExternalStorageState() = " + state);
    if (!Environment.MEDIA_MOUNTED.equals(state)) {
        TextView tv = new TextView(this);
        tv.setText("External storage is not available (state='" + state + "').  Please turn off USB storage.");
        setContentView(tv);
        return;
    }

    nativeView = new NativeView(this, quitHandler, errorHandler);
    setContentView(nativeView);
    // Receive keyboard events
    nativeView.setFocusableInTouchMode(true);
    nativeView.setFocusable(true);
    nativeView.requestFocus();

    // Obtain an instance of the Android PowerManager class
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);

    // Create a WakeLock instance to keep the screen from timing out
    final String LKTAG = "LK8000:" + BuildConfig.BUILD_TYPE;
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, LKTAG);

    // Activate the WakeLock
    wakeLock.acquire();
}

From source file:com.achep.acdisplay.ui.activities.MainActivity.java

/**
 * Turns screen off and sends a test notification.
 *
 * @param cheat {@code true} if it simply starts {@link AcDisplayActivity},
 *              {@code false} if it turns device off and then uses notification
 *              to wake it up./*from w  w w . j a v  a 2  s. c  o m*/
 */
private void startAcDisplayTest(boolean cheat) {
    if (cheat) {
        startActivity(new Intent(this, AcDisplayActivity.class));
        sendTestNotification(this);
        return;
    }

    int delay = getResources().getInteger(R.integer.config_test_notification_delay);

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Test notification.");
    wakeLock.acquire(delay);

    try {
        // Go sleep
        DevicePolicyManager dpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        dpm.lockNow();

        new Handler().postDelayed(new Runnable() {

            private final Context context = getApplicationContext();

            @Override
            public void run() {
                sendTestNotification(context);
            }
        }, delay);
    } catch (SecurityException e) {
        Log.wtf(TAG, "Failed to turn screen off!");
        wakeLock.release();
    }
}

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

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

    // Get libVLC instance
    try {/*www .  ja va 2s  .  co m*/
        mLibVLC = VLCInstance.getLibVlcInstance();
    } catch (LibVlcException e) {
        e.printStackTrace();
    }

    mCallback = new HashMap<IAudioServiceCallback, Integer>();
    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(VLCApplication.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);
    }
}

From source file:org.videolan.vlc2.audio.AudioService.java

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

    // Get libVLC instance
    try {//from  w w  w  .j a  v a 2s  .  c  om
        mLibVLC = VLCInstance.getLibVlcInstance();
    } catch (LibVlcException e) {
        e.printStackTrace();
    }

    mCallback = new HashMap<IAudioServiceCallback, Integer>();
    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(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 (!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);
    }
}

From source file:com.metinkale.prayerapp.vakit.AlarmReceiver.java

public void fireAlarm(Intent intent) throws InterruptedException {

    Context c = App.getContext();

    if ((intent == null) || !intent.hasExtra("json")) {

        return;/*w w w.ja va2  s .co  m*/
    }
    Alarm next = Alarm.fromString(intent.getStringExtra("json"));
    intent.removeExtra("json");

    if (next.city == 0) {
        return;
    }

    Times t = Times.getTimes(next.city);
    if (t == null)
        return;
    boolean active;
    if (next.cuma) {
        active = t.isCumaActive();
    } else if (next.early) {
        active = t.isEarlyNotificationActive(next.vakit);
    } else {
        active = t.isNotificationActive(next.vakit);
    }
    if (!active) {
        return;
    }

    boolean vibrate;
    String sound;
    String dua;
    long silenter;
    if (next.cuma) {
        vibrate = t.hasCumaVibration();
        sound = t.getCumaSound();
        dua = "silent";
        silenter = t.getCumaSilenterDuration();
    } else if (next.early) {
        vibrate = t.hasEarlyVibration(next.vakit);
        sound = t.getEarlySound(next.vakit);
        dua = "silent";
        silenter = t.getEarlySilenterDuration(next.vakit);
    } else {
        vibrate = t.hasVibration(next.vakit);
        sound = t.getSound(next.vakit);
        dua = t.getDua(next.vakit);
        silenter = t.getSilenterDuration(next.vakit);
    }

    NotificationManager nm = (NotificationManager) c.getSystemService(Context.NOTIFICATION_SERVICE);

    nm.cancel(next.city + "", NotIds.ALARM);
    String text;

    text = t.getName() + " (" + t.getSource() + ")";

    String txt = "";
    if (next.early) {
        String[] left_part = App.getContext().getResources().getStringArray(R.array.lefttext_part);
        txt = App.getContext().getString(R.string.earlyText, left_part[next.vakit.index],
                "" + t.getEarlyTime(next.vakit));
    } else if (next.cuma) {
        String[] left_part = App.getContext().getResources().getStringArray(R.array.lefttext_part);
        txt = App.getContext().getString(R.string.earlyText, left_part[next.vakit.index], "" + t.getCumaTime());
    } else if (next.vakit != null) {
        txt = next.vakit.getString();
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(c).setContentTitle(text)
            .setContentText(txt).setContentIntent(Main.getPendingIntent(t)).setSmallIcon(R.drawable.ic_abicon);
    Notification not = builder.build();

    if (vibrate) {
        not.vibrate = VibrationPreference.getPattern(c, "vibration");
    }

    AudioManager am = (AudioManager) c.getSystemService(Context.AUDIO_SERVICE);

    class MPHolder {
        MediaPlayer mp;
    }
    not.deleteIntent = PendingIntent.getBroadcast(c, 0, new Intent(c, Audio.class),
            PendingIntent.FLAG_UPDATE_CURRENT);

    nm.notify(next.city + "", NotIds.ALARM, not);

    final MPHolder mp = new MPHolder();

    if (Prefs.showNotificationScreen() && (sound != null) && !sound.startsWith("silent")) {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (!pm.isScreenOn()) {
            Intent i = new Intent(c, NotificationPopup.class);
            i.putExtra("city", next.city);
            i.putExtra("name", text);
            i.putExtra("vakit", txt);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP
                    | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            c.startActivity(i);

            Thread.sleep(1000);
        }
    }

    sInterrupt = false;
    boolean hasSound = false;
    while ((sound != null) && !sound.startsWith("silent") && !sInterrupt) {
        int volume = -2;
        hasSound = true;

        if (!sound.startsWith("silent") && !sound.startsWith("picker")) {

            if (sound.contains("$volume")) {
                volume = Integer.parseInt(sound.substring(sound.indexOf("$volume") + 7));
                sound = sound.substring(0, sound.indexOf("$volume"));
            }
            if (volume != -2) {
                int oldvalue = am.getStreamVolume(getStreamType(c));
                am.setStreamVolume(getStreamType(c), volume, 0);
                volume = oldvalue;
            }

            try {
                mp.mp = play(c, sound);
            } catch (IOException e) {
                e.printStackTrace();
                if (next.cuma) {
                    t.setCumaSound("silent");
                } else if (next.early) {
                    t.setEarlySound(next.vakit, "silent");
                } else {
                    if ("sound".equals(t.getSound(next.vakit))) {
                        t.setSound(next.vakit, "silent");
                    } else {
                        t.setDua(next.vakit, "silent");
                    }
                }
                mp.mp = null;
            }

            if (mp.mp != null) {

                mp.mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        if (mp.mp == null) {
                            return;
                        }
                        mp.mp.stop();
                        mp.mp.release();
                        mp.mp = null;
                    }
                });

                mp.mp.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                    @Override
                    public void onSeekComplete(MediaPlayer mediaPlayer) {
                        if (mp.mp == null) {
                            return;
                        }
                        mp.mp.stop();
                        mp.mp.release();
                        mp.mp = null;
                    }
                });

            }

            sInterrupt = false;

            while ((mp.mp != null) && mp.mp.isPlaying()) {
                if (sInterrupt) {
                    mp.mp.stop();
                    mp.mp.release();
                    mp.mp = null;

                    dua = null;
                } else {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException ignore) {
                    }
                }
            }
            sInterrupt = false;

        }

        if (volume != -2) {
            am.setStreamVolume(getStreamType(c), volume, 0);
        }
        sound = dua;
        dua = null;
    }

    if (hasSound && Prefs.autoRemoveNotification()) {
        nm.cancel(next.city + "", NotIds.ALARM);
    }
    if (silenter != 0) {
        silenter(c, silenter);
    }

}

From source file:com.bullmobi.message.ui.activities.MainActivity.java

/**
 * Turns screen off and sends a test notification.
 *
 * @param cheat {@code true} if it simply starts {@link EasyNotificationActivity},
 *              {@code false} if it turns device off and then uses notification
 *              to wake it up.//w w w  .  j a  va 2  s .  com
 */
private void startEasyNotificationTest(boolean cheat) {
    if (cheat) {
        startActivity(new Intent(this, EasyNotificationActivity.class));
        sendTestNotification(this);
        return;
    }

    int delay = getResources().getInteger(R.integer.config_test_notification_delay);

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Test notification.");
    wakeLock.acquire(delay);

    try {
        // Go sleep
        DevicePolicyManager dpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        dpm.lockNow();

        new Handler().postDelayed(new Runnable() {

            private final Context context = getApplicationContext();

            @Override
            public void run() {
                sendTestNotification(context);
            }
        }, delay);
    } catch (SecurityException e) {
        Log.wtf(TAG, "Failed to turn screen off!");
        wakeLock.release();
    }
}

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

public void streamTorrent(@NonNull final String torrentUrl) {
    Timber.d("streamTorrent");

    //attempt to initialize service
    initialize();//from  w ww . j a v  a2s  .  c o m

    if (mHandler == null || mIsStreaming)
        return;

    mIsCanceled = false;
    mReady = false;

    Timber.d("Starting streaming");

    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, THREAD_NAME);
    mWakeLock.acquire();

    SessionSettings sessionSettings = mTorrentSession.getSettings();
    sessionSettings.setActiveDHTLimit(PrefUtils.get(this, Prefs.LIBTORRENT_DHT_LIMIT, 200));
    sessionSettings.setConnectionsLimit(PrefUtils.get(this, Prefs.LIBTORRENT_CONNECTION_LIMIT, 200));
    sessionSettings.setDownloadRateLimit(PrefUtils.get(this, Prefs.LIBTORRENT_DOWNLOAD_LIMIT, 0));
    sessionSettings.setUploadRateLimit(PrefUtils.get(this, Prefs.LIBTORRENT_UPLOAD_LIMIT, 0));
    mTorrentSession.setSettings(sessionSettings);

    mHandler.post(new Runnable() {
        @Override
        public void run() {
            Timber.d("streaming runnable");
            mIsStreaming = true;
            mCurrentTorrentUrl = torrentUrl;

            File saveDirectory = new File(PopcornApplication.getStreamDir());
            saveDirectory.mkdirs();

            File torrentFileDir = new File(saveDirectory, "files");
            torrentFileDir.mkdirs();

            File torrentFile = new File(torrentFileDir, System.currentTimeMillis() + ".torrent");

            if (!torrentFile.exists()) {
                int fileCreationTries = 0;
                while (fileCreationTries < 4) {
                    try {
                        fileCreationTries++;
                        if (torrentFileDir.mkdirs() || torrentFileDir.isDirectory()) {
                            Timber.d("Creating torrent file");
                            torrentFile.createNewFile();
                        }
                    } catch (IOException e) {
                        Timber.e(e, "Error on file create");
                    }
                }

                if (!getTorrentFile(torrentUrl, torrentFile)) {
                    for (final Listener listener : mListener) {
                        ThreadUtils.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                listener.onStreamError(new IOException("Write error"));
                            }
                        });
                    }
                    return;
                } else if (!torrentFile.exists()) {
                    for (final Listener listener : mListener) {
                        ThreadUtils.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                listener.onStreamError(new IOException("Write error"));
                            }
                        });
                    }
                    return;
                }
            }

            if (!mCurrentTorrentUrl.equals(torrentUrl) || mIsCanceled) {
                return;
            }

            mCurrentTorrent = mTorrentSession.addTorrent(torrentFile, saveDirectory);
            mCurrentListener = new TorrentAlertAdapter(mCurrentTorrent);
            mTorrentSession.addListener(mCurrentListener);

            TorrentInfo torrentInfo = mCurrentTorrent.getTorrentInfo();
            FileStorage fileStorage = torrentInfo.getFiles();
            long highestFileSize = 0;
            int selectedFile = -1;
            for (int i = 0; i < fileStorage.geNumFiles(); i++) {
                long fileSize = fileStorage.getFileSize(i);
                if (highestFileSize < fileSize) {
                    highestFileSize = fileSize;
                    selectedFile = i;
                }
            }

            mCurrentVideoLocation = new File(saveDirectory, torrentInfo.getFileAt(selectedFile).getPath());

            Timber.d("Video location: %s", mCurrentVideoLocation);

            //post a new runnable which will potentially take along time.
            //this is the runnable which actually starts the streaming.
            //posting this as a runnable will allow other runnables that have been posted
            //execute before this potentially blocking runnable
            mHandler.post(new Runnable() {
                @Override
                public void run() {

                    //blocking call.
                    mDHT.waitNodes(30);
                    mCurrentTorrent.setSequentialDownload(true);
                    mCurrentTorrent.resume();
                    for (final Listener listener : mListener) {
                        ThreadUtils.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                listener.onStreamStarted();
                            }
                        });
                    }
                }
            });
        }
    });
}

From source file:ch.ethz.twimight.net.opportunistic.ScanningService.java

/**
 * Acquire the Wake Lock
 * /* w w w.  jav a 2 s .co m*/
 * @param context
 */
void getWakeLock(Context context) {

    releaseWakeLock();

    PowerManager mgr = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKE_LOCK);
    wakeLock.acquire();
}