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.andreadec.musicplayer.MusicService.java

/**
 * Called when the service is created.//from   w  ww. j  av  a  2  s.c o  m
 */
@Override
public void onCreate() {
    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MusicServiceWakelock");

    // Initialize the telephony manager
    telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    phoneStateListener = new MusicPhoneStateListener();
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // Initialize pending intents
    quitPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.andreadec.musicplayer.quit"), 0);
    previousPendingIntent = PendingIntent.getBroadcast(this, 0,
            new Intent("com.andreadec.musicplayer.previous"), 0);
    playpausePendingIntent = PendingIntent.getBroadcast(this, 0,
            new Intent("com.andreadec.musicplayer.playpause"), 0);
    nextPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.andreadec.musicplayer.next"), 0);
    pendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP),
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Read saved user preferences
    preferences = PreferenceManager.getDefaultSharedPreferences(this);

    // Initialize the media player
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK); // Enable the wake lock to keep CPU running when the screen is switched off

    shuffle = preferences.getBoolean(Constants.PREFERENCE_SHUFFLE, Constants.DEFAULT_SHUFFLE);
    repeat = preferences.getBoolean(Constants.PREFERENCE_REPEAT, Constants.DEFAULT_REPEAT);
    repeatAll = preferences.getBoolean(Constants.PREFERENCE_REPEATALL, Constants.DEFAULT_REPEATALL);
    try { // This may fail if the device doesn't support bass boost
        bassBoost = new BassBoost(1, mediaPlayer.getAudioSessionId());
        bassBoost.setEnabled(
                preferences.getBoolean(Constants.PREFERENCE_BASSBOOST, Constants.DEFAULT_BASSBOOST));
        setBassBoostStrength(preferences.getInt(Constants.PREFERENCE_BASSBOOSTSTRENGTH,
                Constants.DEFAULT_BASSBOOSTSTRENGTH));
        bassBoostAvailable = true;
    } catch (Exception e) {
        bassBoostAvailable = false;
    }
    try { // This may fail if the device doesn't support equalizer
        equalizer = new Equalizer(1, mediaPlayer.getAudioSessionId());
        equalizer.setEnabled(
                preferences.getBoolean(Constants.PREFERENCE_EQUALIZER, Constants.DEFAULT_EQUALIZER));
        setEqualizerPreset(
                preferences.getInt(Constants.PREFERENCE_EQUALIZERPRESET, Constants.DEFAULT_EQUALIZERPRESET));
        equalizerAvailable = true;
    } catch (Exception e) {
        equalizerAvailable = false;
    }
    random = new Random(System.nanoTime()); // Necessary for song shuffle

    shakeListener = new ShakeListener(this);
    if (preferences.getBoolean(Constants.PREFERENCE_SHAKEENABLED, Constants.DEFAULT_SHAKEENABLED)) {
        shakeListener.enable();
    }

    telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); // Start listen for telephony events

    // Inizialize the audio manager
    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mediaButtonReceiverComponent = new ComponentName(getPackageName(), MediaButtonReceiver.class.getName());
    audioManager.registerMediaButtonEventReceiver(mediaButtonReceiverComponent);
    audioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    // Initialize remote control client
    if (Build.VERSION.SDK_INT >= 14) {
        icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        mediaButtonIntent.setComponent(mediaButtonReceiverComponent);
        PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
                mediaButtonIntent, 0);

        remoteControlClient = new RemoteControlClient(mediaPendingIntent);
        remoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
                | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_NEXT);
        audioManager.registerRemoteControlClient(remoteControlClient);
    }

    updateNotificationMessage();

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("com.andreadec.musicplayer.quit");
    intentFilter.addAction("com.andreadec.musicplayer.previous");
    intentFilter.addAction("com.andreadec.musicplayer.previousNoRestart");
    intentFilter.addAction("com.andreadec.musicplayer.playpause");
    intentFilter.addAction("com.andreadec.musicplayer.next");
    intentFilter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("com.andreadec.musicplayer.quit")) {
                sendBroadcast(new Intent("com.andreadec.musicplayer.quitactivity"));
                stopSelf();
                return;
            } else if (action.equals("com.andreadec.musicplayer.previous")) {
                previousItem(false);
            } else if (action.equals("com.andreadec.musicplayer.previousNoRestart")) {
                previousItem(true);
            } else if (action.equals("com.andreadec.musicplayer.playpause")) {
                playPause();
            } else if (action.equals("com.andreadec.musicplayer.next")) {
                nextItem();
            } else if (action.equals(AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {
                if (preferences.getBoolean(Constants.PREFERENCE_STOPPLAYINGWHENHEADSETDISCONNECTED,
                        Constants.DEFAULT_STOPPLAYINGWHENHEADSETDISCONNECTED)) {
                    pause();
                }
            }
        }
    };
    registerReceiver(broadcastReceiver, intentFilter);

    if (!isPlaying()) {
        loadLastSong();
    }

    startForeground(Constants.NOTIFICATION_MAIN, notification);
}

From source file:fr.inria.ucn.collectors.SysStateCollector.java

/**
 * //from   www  .jav  a2  s.  c  o m
 * @param c
 * @param ts
 * @param change
 */
@SuppressLint("NewApi")
public void run(Context c, long ts, boolean change) {
    try {
        JSONObject data = new JSONObject();
        data.put("on_screen_state_change", change); // this collection run was triggered by screen state change

        data.put("hostname", Helpers.getSystemProperty("net.hostname", "unknown hostname"));
        data.put("current_timezone", Time.getCurrentTimezone());

        // general memory state
        ActivityManager am = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE);
        MemoryInfo mi = new MemoryInfo();
        am.getMemoryInfo(mi);

        JSONObject mem = new JSONObject();
        mem.put("available", mi.availMem);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            mem.put("total", mi.totalMem);
        }
        mem.put("is_low", mi.lowMemory);
        data.put("memory", mem);

        // screen state
        PowerManager pm = (PowerManager) c.getSystemService(Context.POWER_SERVICE);
        data.put("screen_on", pm.isScreenOn());

        // battery state
        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent battery = c.registerReceiver(null, ifilter);
        int level = battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = battery.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        float pct = (float) (100.0 * level) / scale;
        int status = battery.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging = (status == BatteryManager.BATTERY_STATUS_CHARGING
                || status == BatteryManager.BATTERY_STATUS_FULL);
        int chargePlug = battery.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

        JSONObject batt = new JSONObject();
        batt.put("level", level);
        batt.put("scale", scale);
        batt.put("pct", pct);
        batt.put("is_charging", isCharging);
        batt.put("usb_charge", usbCharge);
        batt.put("ac_charge", acCharge);
        data.put("battery", batt);

        // some proc stats
        data.put("cpu", getCpuStat());
        data.put("loadavg", getLoadStat());
        data.put("uptime", getUptimeStat());

        // audio state
        data.put("audio", getAudioState(c));

        // done
        Helpers.sendResultObj(c, "system_state", ts, data);

    } catch (JSONException jex) {
        Log.w(Constants.LOGTAG, "failed to create json object", jex);
    }
}

From source file:cm.aptoide.pt.DownloadQueueService.java

@Override
public void onCreate() {
    super.onCreate();
    notifications = new HashMap<Integer, HashMap<String, String>>();

    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    keepScreenOn = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,
            "Full Power");
    Log.d("Aptoide-DowloadQueueService", "Created");
}

From source file:jp.morihirosoft.twwb.TwwbService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (DEBUG)/*from   ww  w. ja v  a2  s  . c  o  m*/
        Log.d(TAG, "onStartCommand: intent=" + intent);
    registerReceivers();
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    if (pm.isScreenOn()) {
        startRecognition();
    }
    return super.onStartCommand(intent, flags, startId);
}

From source file:com.doctoror.surprise.SurpriseService.java

@Override
public void onCreate() {
    super.onCreate();
    mToastMessageHandler = new ToastMessageHandler(getApplicationContext());
    mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
    mNotificationManagerHandler = NotificationManagerHandler.getInstance(this);

    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    mWakeLock.acquire();//from   w w w  .  j  a  v a  2 s  .c  o m
}

From source file:com.android.antitheft.activities.ParseSettingsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.parse_settings_activity);

    final EditText parseAppId = (EditText) findViewById(R.id.parse_app_id);

    final EditText parseClientKey = (EditText) findViewById(R.id.parse_client_key);

    Button btnUpdateParse = (Button) findViewById(R.id.btn_update_parse_setup);
    btnUpdateParse.setOnClickListener(new OnClickListener() {

        @Override/* www.  j av  a  2s . co  m*/
        public void onClick(View v) {
            String savedClientKey = PrefUtils.getInstance().getStringPreference(PrefUtils.PARSE_CLIENT_KEY, "");
            String savedAppId = PrefUtils.getInstance().getStringPreference(PrefUtils.PARSE_APP_ID, "");
            String newClientKey = parseClientKey.getText().toString();
            String newAppId = parseAppId.getText().toString();
            if (!newAppId.equals(savedAppId) && !newClientKey.equals(savedClientKey)) {
                PrefUtils.getInstance().setStringPreference(PrefUtils.PARSE_APP_ID, newAppId);
                PrefUtils.getInstance().setStringPreference(PrefUtils.PARSE_CLIENT_KEY, newClientKey);
                Toast.makeText(ParseSettingsActivity.this, "Your device will now reboot!", Toast.LENGTH_LONG)
                        .show();
                //PrefUtils.getInstance().setBoolPreference(PrefUtils.PARSE_CONFIG_CHANGED, true);
                try {
                    IPowerManager pm = IPowerManager.Stub
                            .asInterface(ServiceManager.getService(Context.POWER_SERVICE));
                    pm.reboot(false, null, false);
                } catch (RemoteException e) {
                    Log.e(TAG, "PowerManager service died!", e);
                    return;
                }
            }
        }
    });

}

From source file:slimchat.android.SlimChat.java

/**
 * Power Manager
 * 
 * @return
 */
public PowerManager powerManager() {
    return (PowerManager) appContext.getSystemService(Context.POWER_SERVICE);
}

From source file:com.av.remusic.receiver.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, "Timber headset button");
        mWakeLock.setReferenceCounted(false);
    }//from w w  w.j av a  2s.  c  o 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);
}

From source file:ufms.br.com.ufmsapp.task.DownloadTask.java

@Override
protected void onPreExecute() {
    super.onPreExecute();
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
    mWakeLock.acquire();/*w  ww  . j ava 2 s.  c om*/

    builder.setProgress(100, 0, false);
    manager.notify(NOTIFICATION_ID, builder.build());
}

From source file:com.TwentyCodes.android.IOIOTruck.CameraActivity.java

/**
 * Called when the activity is resuming//from  ww w  .  j  av  a  2 s  . co m
 * (non-Javadoc)
 * @see android.support.v4.app.FragmentActivity#onResume()
 */
@Override
protected void onResume() {

    PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, TAG);
    mWakeLock.acquire();
    super.onResume();
}