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.google.android.vending.expansion.downloader.impl.DownloadThread.java

/**
 * Executes the download in a separate thread
 *///from   w ww  .  ja  v a2  s  .  c o m
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    State state = new State(mInfo, mService);
    AndroidHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR;

    try {
        PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
        wakeLock.acquire();

        if (Constants.LOGV) {
            Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName);
            Log.v(Constants.TAG, "  at " + mInfo.mUri);
        }

        client = AndroidHttpClient.newInstance(userAgent(), mContext);

        boolean finished = false;
        while (!finished) {
            if (Constants.LOGV) {
                Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName);
                Log.v(Constants.TAG, "  at " + mInfo.mUri);
            }
            // Set or unset proxy, which may have changed since last GET
            // request.
            // setDefaultProxy() supports null as proxy parameter.
            ConnRouteParams.setDefaultProxy(client.getParams(),
                    getPreferredHttpHost(mContext, state.mRequestUri));
            HttpGet request = new HttpGet(state.mRequestUri);
            try {
                executeDownload(state, client, request);
                finished = true;
            } catch (RetryDownload exc) {
                // fall through
            } finally {
                request.abort();
                request = null;
            }
        }

        if (Constants.LOGV) {
            Log.v(Constants.TAG, "download completed for " + mInfo.mFileName);
            Log.v(Constants.TAG, "  at " + mInfo.mUri);
        }
        finalizeDestinationFile(state);
        finalStatus = DownloaderService.STATUS_SUCCESS;
    } catch (StopRequest error) {
        // remove the cause before printing, in case it contains PII
        Log.w(Constants.TAG, "Aborting request for download " + mInfo.mFileName + ": " + error.getMessage());
        error.printStackTrace();
        finalStatus = error.mFinalStatus;
        // fall through to finally block
    } catch (Throwable ex) { // sometimes the socket code throws unchecked
                             // exceptions
        Log.w(Constants.TAG, "Exception for " + mInfo.mFileName + ": " + ex);
        finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR;
        // falls through to the code that reports an error
    } finally {
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        if (client != null) {
            client.close();
            client = null;
        }
        cleanupDestination(state, finalStatus);
        notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mRedirectCount,
                state.mGotData, state.mFilename);
    }
}

From source file:com.google.android.gcm.GCMBaseIntentService.java

/**
 * Called from the broadcast receiver./*  w ww .ja  va 2  s. c o m*/
 * <p>
 * Will process the received intent, call handleMessage(), registered(),
 * etc. in background threads, with a wake lock, while keeping the service
 * alive.
 */
static void runIntentInService(Context context, Intent intent, String className) {
    synchronized (LOCK) {
        if (sWakeLock == null) {
            // This is called from BroadcastReceiver, there is no init.
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY);
        }
    }
    Log.v(TAG, "Acquiring wakelock");
    sWakeLock.acquire();
    intent.setClassName(context, className);
    context.startService(intent);
}

From source file:com.nanostuffs.yurdriver.GCMIntentService.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *///from   w  w w.j av  a 2  s . c o  m
private void generateNotification(Context context, String message) {
    int icon = R.drawable.ic_launcher;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);
    String title = context.getString(R.string.app_name);
    Intent notificationIntent = new Intent(context, MapActivity.class);
    notificationIntent.putExtra("fromNotification", "notification");
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    System.out.println("notification====>" + message);
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    // notification.defaults |= Notification.DEFAULT_LIGHTS;
    notification.flags |= Notification.FLAG_SHOW_LIGHTS;
    notification.ledARGB = 0x00000000;
    notification.ledOnMS = 0;
    notification.ledOffMS = 0;
    notificationManager.notify(AndyConstants.NOTIFICATION_ID, notification);
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = pm.newWakeLock(
            PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE,
            "WakeLock");
    wakeLock.acquire();
    wakeLock.release();

}

From source file:org.videolan.myvlc.core.mediaController.AudioService.java

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

    // Get libVLC instance
    //        try {
    //            mLibVLC = Util.getLibVlcInstance();
    //        } catch (LibVlcException e) {
    //            e.printStackTrace();
    //        }//from   w  w  w . ja  va 2 s .com

    //        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(ACTION_WIDGET_INIT);
    filter.addAction(Intent.ACTION_HEADSET_PLUG);
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    filter.addAction(MyVLCApp.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.marianhello.cordova.bgloc.LocationUpdateService.java

@Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "OnCreate");

        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        toneGenerator = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
        connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        // Stop-detection PI
        stationaryAlarmPI = PendingIntent.getBroadcast(this, 0, new Intent(STATIONARY_ALARM_ACTION), 0);
        registerReceiver(stationaryAlarmReceiver, new IntentFilter(STATIONARY_ALARM_ACTION));

        // Stationary region PI
        stationaryRegionPI = PendingIntent.getBroadcast(this, 0, new Intent(STATIONARY_REGION_ACTION),
                PendingIntent.FLAG_CANCEL_CURRENT);
        registerReceiver(stationaryRegionReceiver, new IntentFilter(STATIONARY_REGION_ACTION));

        // Stationary location monitor PI
        stationaryLocationPollingPI = PendingIntent.getBroadcast(this, 0,
                new Intent(STATIONARY_LOCATION_MONITOR_ACTION), 0);
        registerReceiver(stationaryLocationMonitorReceiver, new IntentFilter(STATIONARY_LOCATION_MONITOR_ACTION));

        // One-shot PI (TODO currently unused)
        singleUpdatePI = PendingIntent.getBroadcast(this, 0, new Intent(SINGLE_LOCATION_UPDATE_ACTION),
                PendingIntent.FLAG_CANCEL_CURRENT);
        registerReceiver(singleUpdateReceiver, new IntentFilter(SINGLE_LOCATION_UPDATE_ACTION));

        //////w  w w. jav  a  2  s  .  c  o m
        // DISABLED
        // Listen to Cell-tower switches (NOTE does not operate while suspended)
        //telephonyManager.listen(phoneStateListener, LISTEN_CELL_LOCATION);
        //

        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

        wakeLock.acquire();

        // Location criteria
        criteria = new Criteria();
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setSpeedRequired(true);
        criteria.setCostAllowed(true);
    }

From source file:org.metawatch.manager.MetaWatchService.java

@Override
public void onCreate() {
    super.onCreate();
    if (Preferences.logging)
        Log.d(MetaWatchStatus.TAG, "MetaWatchService.onCreate()");

    if (!Preferences.loaded)
        loadPreferences(this);

    PreferenceManager.getDefaultSharedPreferences(MetaWatchService.this)
            .registerOnSharedPreferenceChangeListener(prefChangeListener);

    createNotification();/*  w w  w .  j a  va 2s .c o m*/

    connectionState = ConnectionState.CONNECTING;

    watchMode.clear();
    watchMode.push(WatchModes.IDLE);

    watchType = WatchType.UNKNOWN;
    watchGen = WatchGen.UNKNOWN;
    Monitors.getInstance().getRTCTimestamp = 0;

    if (bluetoothAdapter == null)
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

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

    Notification.getInstance().startNotificationSender(this);
    Monitors.getInstance().start(this/* , telephonyManager */);

    watchReceiverThread = new WatchReceiverThread("MetaWatch Service Thread");
    watchReceiverThread.setPriority(7);
    watchReceiverThread.start();

    watchSenderThread.execute(protocolSender);
    weatherBatteryPollHandler.post(pollWeatherBattery);

    mIsRunning = true;
}

From source file:org.computeforcancer.android.client.Monitor.java

@Override
public void onCreate() {

    Log.d(Logging.TAG, "Monitor onCreate()");

    // populate attributes with XML resource values
    boincWorkingDir = getString(R.string.client_path);
    fileNameClient = getString(R.string.client_name);
    fileNameCLI = getString(R.string.client_cli);
    fileNameCABundle = getString(R.string.client_cabundle);
    fileNameClientConfig = getString(R.string.client_config);
    fileNameGuiAuthentication = getString(R.string.auth_file_name);
    fileNameAllProjectsList = getString(R.string.all_projects_list);
    clientStatusInterval = getResources().getInteger(R.integer.status_update_interval_ms);
    deviceStatusIntervalScreenOff = getResources()
            .getInteger(R.integer.device_status_update_screen_off_every_X_loop);
    clientSocketAddress = getString(R.string.client_socket_address);

    // initialize singleton helper classes and provide application context
    clientStatus = new ClientStatus(this);
    getAppPrefs().readPrefs(this);
    deviceStatus = new DeviceStatus(this, getAppPrefs());
    if (Logging.ERROR)
        Log.d(Logging.TAG, "Monitor onCreate(): singletons initialized");

    // set current screen on/off status
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    screenOn = pm.isScreenOn();//from w  w  w .  jav  a 2s  . co m

    // initialize DeviceStatus wrapper
    deviceStatus = new DeviceStatus(getApplicationContext(), getAppPrefs());

    // register screen on/off receiver
    IntentFilter onFilter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    IntentFilter offFilter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
    registerReceiver(screenOnOffReceiver, onFilter);
    registerReceiver(screenOnOffReceiver, offFilter);
}

From source file:step.StepService.java

private void acquireWakeLock() {
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    int wakeFlags;
    wakeFlags = PowerManager.PARTIAL_WAKE_LOCK;
    wakeLock = pm.newWakeLock(wakeFlags, TAG);
    wakeLock.acquire();/* w  w w.  ja v  a2s. c  om*/
}

From source file:tree.love.providers.downloads.DownloadThread.java

private void runInternal() {
    // Skip when download already marked as finished; this download was
    // probably started again while racing with UpdateThread.
    if (DownloadInfo.queryDownloadStatus(mContext.getContentResolver(),
            mInfo.mId) == Downloads.Impl.STATUS_SUCCESS) {
        Log.d(TAG, "Download " + mInfo.mId + " already finished; skipping");
        return;/*from  www . j av  a2  s .c  o  m*/
    }

    State state = new State(mInfo);
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;
    int numFailed = mInfo.mNumFailed;
    String errorMsg = null;

    // final NetworkPolicyManager netPolicy =
    // NetworkPolicyManager.from(mContext);
    final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);

    try {
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
        // wakeLock.setWorkSource(new WorkSource(mInfo.mUid));
        wakeLock.acquire();

        // while performing download, register for rules updates
        // netPolicy.registerListener(mPolicyListener);

        Log.i(Constants.TAG, "Download " + mInfo.mId + " starting");

        // Remember which network this download started on; used to
        // determine if errors were due to network changes.
        final NetworkInfo info = mSystemFacade.getActiveNetworkInfo(mInfo.mUid);
        if (info != null) {
            state.mNetworkType = info.getType();
        }

        // Network traffic on this thread should be counted against the
        // requesting UID, and is tagged with well-known value.
        TrafficStatsCompat.setThreadStatsTag(TrafficStatsCompat.getThreadStatsTag());
        // TrafficStatsCompat.setThreadStatsUid(mInfo.mUid);

        try {
            // TODO: migrate URL sanity checking into client side of API
            state.mUrl = new URL(state.mRequestUri);
        } catch (MalformedURLException e) {
            throw new StopRequestException(STATUS_BAD_REQUEST, e);
        }

        executeDownload(state);

        finalizeDestinationFile(state);
        finalStatus = Downloads.Impl.STATUS_SUCCESS;
    } catch (StopRequestException error) {
        // remove the cause before printing, in case it contains PII
        errorMsg = error.getMessage();
        String msg = "Aborting request for download " + mInfo.mId + ": " + errorMsg;
        Log.w(Constants.TAG, msg);
        if (Constants.LOGV) {
            Log.w(Constants.TAG, msg, error);
        }
        finalStatus = error.getFinalStatus();

        // Nobody below our level should request retries, since we handle
        // failure counts at this level.
        if (finalStatus == STATUS_WAITING_TO_RETRY) {
            throw new IllegalStateException("Execution should always throw final error codes");
        }

        // Some errors should be retryable, unless we fail too many times.
        if (isStatusRetryable(finalStatus)) {
            if (state.mGotData) {
                numFailed = 1;
            } else {
                numFailed += 1;
            }

            if (numFailed < Constants.MAX_RETRIES) {
                final NetworkInfo info = mSystemFacade.getActiveNetworkInfo(mInfo.mUid);
                if (info != null && info.getType() == state.mNetworkType && info.isConnected()) {
                    // Underlying network is still intact, use normal backoff
                    finalStatus = STATUS_WAITING_TO_RETRY;
                } else {
                    // Network changed, retry on any next available
                    finalStatus = STATUS_WAITING_FOR_NETWORK;
                }
            }
        }

        // fall through to finally block
    } catch (Throwable ex) {
        errorMsg = ex.getMessage();
        String msg = "Exception for id " + mInfo.mId + ": " + errorMsg;
        Log.w(Constants.TAG, msg, ex);
        finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;
        // falls through to the code that reports an error
    } finally {
        if (finalStatus == STATUS_SUCCESS) {
            TrafficStatsCompat.incrementOperationCount(1);
        }

        TrafficStatsCompat.clearThreadStatsTag();
        //            TrafficStatsCompat.clearThreadStatsUid();

        cleanupDestination(state, finalStatus);
        notifyDownloadCompleted(state, finalStatus, errorMsg, numFailed);

        Log.i(Constants.TAG, "Download " + mInfo.mId + " finished with status "
                + Downloads.Impl.statusToString(finalStatus));

        //            netPolicy.unregisterListener(mPolicyListener);

        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
    }
    mStorageManager.incrementNumDownloadsSoFar();
}

From source file:eu.faircode.adblocker.ServiceSinkhole.java

synchronized private static PowerManager.WakeLock getLock(Context context) {
    if (wlInstance == null) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        wlInstance = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                context.getString(R.string.app_name) + " wakelock");
        wlInstance.setReferenceCounted(true);
    }// w w w . j  a  v a2s.  com
    return wlInstance;
}