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.foolhorse.downloaddemo.man.DownloadThread.java

/**
 * Executes the download in a separate thread
 *//*from  w w  w  .java  2 s . c om*/
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    State state = new State(mInfo);
    AndroidHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = Downloads.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.mUri);
        }

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

        boolean finished = false;
        while (!finished) {
            Log.i(Constants.TAG, "Initiating request for download " + mInfo.mId);
            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.mUri);
        }
        finalizeDestinationFile(state);
        finalStatus = Downloads.STATUS_SUCCESS;
    } catch (StopRequest error) {
        // remove the cause before printing, in case it contains PII
        Log.w(Constants.TAG, "Aborting request for download " + mInfo.mId + ": " + error.getMessage());
        finalStatus = error.mFinalStatus;
        // fall through to finally block
    } catch (Throwable ex) { // sometimes the socket code throws unchecked
        // exceptions
        Log.w(Constants.TAG, "Exception for id " + mInfo.mId + ": " + ex);
        finalStatus = Downloads.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.mGotData,
                state.mFilename, state.mNewUri, state.mMimeType);
        mInfo.mHasActiveThread = false;
    }
}

From source file:com.android.providers.downloads.DownloadThread.java

/**
 * Executes the download in a separate thread
 *//*from  w w w .j a  v a 2s.  c  om*/
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    State state = new State(mInfo);
    AndroidHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = Downloads.Impl.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.mUri);
        }

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

        boolean finished = false;
        while (!finished) {
            Log.i(Constants.TAG, "Initiating request for download " + mInfo.mId);
            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.mUri);
        }
        finalizeDestinationFile(state);
        finalStatus = Downloads.Impl.STATUS_SUCCESS;
    } catch (StopRequest error) {
        // remove the cause before printing, in case it contains PII
        Log.w(Constants.TAG, "Aborting request for download " + mInfo.mId + ": " + error.getMessage());
        finalStatus = error.mFinalStatus;
        // fall through to finally block
    } catch (Throwable ex) { //sometimes the socket code throws unchecked exceptions
        Log.w(Constants.TAG, "Exception for id " + mInfo.mId + ": " + ex);
        finalStatus = Downloads.Impl.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);
        // We have written new information to the database, the data in the update thread
        // is no longer valid. This needs to be synchronized to prevent the information
        // to change while the Update Thread in Download Service is using it.
        synchronized (mSystemFacade) {
            notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mGotData,
                    state.mFilename, state.mNewUri, state.mMimeType);
            mInfo.mHasActiveThread = false;
            mSystemFacade.setUpdateThreadDataIsOutdated(true);
        }
    }
}

From source file:com.mine.psf.PsfPlaybackService.java

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

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    mWakeLock.setReferenceCounted(false);
    Log.d(LOGTAG, "onCreate, Acquire Wake Lock");

    PsfAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    PsfControlResponder = new ComponentName(getPackageName(), RemoteControlReceiver.class.getName());
    PsfAudioManager.registerMediaButtonEventReceiver(PsfControlResponder);

    mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    reloadQueue();/* www  . j a  va2 s  .  c om*/

    // If the service was idle, but got killed before it stopped itself, the
    // system will relaunch it. Make sure it gets stopped again in that case.
    Message msg = mDelayedStopHandler.obtainMessage();
    mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);

    // Register sd card mount/unmount listener
    registerExternalStorageListener();

    // Register noisy listener, it should
    // 1) Playing with headset, unplug headset, sound should be paused;
    // 2) Playing with speaker, plug headset, sound should keep playing.
    registerNoisyListener();
}

From source file:com.example.slidingmenuexample.ui.NXTRemoteControl.java

/** Called when the activity is first created. */
@SuppressWarnings("deprecation")
@Override/*  w ww  .jav  a 2s. co  m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    readPreferences(prefs, null);
    prefs.registerOnSharedPreferenceChangeListener(this);

    if (savedInstanceState != null) {
        mNewLaunch = false;
        mDeviceAddress = savedInstanceState.getString("device_address");
        if (mDeviceAddress != null) {
            mSavedState = NXTTalker.STATE_CONNECTED;
        }

        if (savedInstanceState.containsKey("power")) {
            mPower = savedInstanceState.getInt("power");
        }
        if (savedInstanceState.containsKey("controls_mode")) {
            mControlsMode = savedInstanceState.getInt("controls_mode");
        }
    }

    mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,
            "NXT Remote Control");

    if (!NO_BT) {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
    }

    setupUI();

    mNXTTalker = new NXTTalker(mHandler);

    pagelist = getSlidingMenu();
    pagelist.setShadowDrawable(R.drawable.shadow);
    pagelist.setBehindOffset(600);
    pagelist.setShadowWidth(15);
    pagelist.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setIcon(R.drawable.ic_launcher);

    if (savedInstanceState != null)
        mContent = getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
    if (mContent == null)
        mContent = new NXTRemoteControlView();

    setContentView(R.layout.content_frame);
    getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mContent).commit();

    setBehindContentView(R.layout.menu_frame);
    getSupportFragmentManager().beginTransaction().replace(R.id.menu_frame, new MenuListPages()).commit();

    setSlidingActionBarEnabled(true);
}

From source file:com.example.download.DownloadThread.java

/**
 * Executes the download in a separate thread
 *//*w w  w  . j  ava2 s  .  c  o  m*/
public void run() {

    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    State state = new State(mInfo);
    AndroidHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = DownloadManager.Impl.STATUS_UNKNOWN_ERROR;

    try {
        PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, com.example.util.Utils.sLogTag);
        wakeLock.acquire();

        Utils.D("initiating download for " + mInfo.mUri);

        client = HttpClientFactory.get().getHttpClient();

        boolean finished = false;
        while (!finished) {

            Utils.D("Initiating request for download " + mInfo.mId + " url " + mInfo.mUri);

            HttpGet request = new HttpGet(state.mRequestUri);
            try {
                executeDownload(state, client, request);
                finished = true;
            } catch (RetryDownload exc) {
                // fall through
            } finally {
                request.abort();
                request = null;
            }
        }

        Utils.D("download completed for " + mInfo.mUri);

        if (!checkFile(state)) {
            throw new Throwable("File MD5 code is not the same as server");
        }

        finalizeDestinationFile(state);
        finalStatus = DownloadManager.Impl.STATUS_SUCCESS;
    } catch (StopRequest error) {
        // remove the cause before printing, in case it contains PII
        Utils.W("Aborting request for download " + mInfo.mId + " url: " + mInfo.mUri + " : "
                + error.getMessage());
        finalStatus = error.mFinalStatus;
        // fall through to finally block
    } catch (Throwable ex) { //sometimes the socket code throws unchecked exceptions
        Utils.W("Exception for id " + mInfo.mId + " url: " + mInfo.mUri + ": " + ex);
        // falls through to the code that reports an error
    } finally {
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        if (client != null) {
            client = null;
        }
        cleanupDestination(state, finalStatus);
        notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mRedirectCount,
                state.mGotData, state.mFilename, state.mNewUri, state.mMimeType);
        mInfo.mHasActiveThread = false;
    }
}

From source file:it.baywaylabs.jumpersumo.robot.ServerPolling.java

/**
 * Method auto invoked execute the task.
 *///from  w w w.j  av a 2  s.  c o  m
@Override
protected void onPreExecute() {
    super.onPreExecute();
    // take CPU lock to prevent CPU from going off if the user
    // presses the power button during download
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
    mWakeLock.acquire();
    if (mProgressDialog != null)
        mProgressDialog.show();
}

From source file:com.sdk.download.providers.downloads.DownloadThread.java

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

    State state = new State(mInfo);
    AndroidHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = Downloads.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.mUri);
        }

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

        boolean finished = false;
        while (!finished) {
            Log.i(Constants.TAG, "Initiating request for download " + mInfo.mId);
            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.mUri);
        }
        finalizeDestinationFile(state);
        finalStatus = Downloads.STATUS_SUCCESS;
    } catch (StopRequest error) {
        // remove the cause before printing, in case it contains PII
        Log.w(Constants.TAG, "Aborting request for download " + mInfo.mId + ": " + error.getMessage());
        finalStatus = error.mFinalStatus;
        // fall through to finally block
    } catch (Throwable ex) { // sometimes the socket code throws unchecked
        // exceptions
        Log.w(Constants.TAG, "Exception for id " + mInfo.mId + ": " + ex);
        finalStatus = Downloads.STATUS_UNKNOWN_ERROR;
        // falls through to the code that reports an error
    } finally {
        if (client != null) {
            client.close();
            client = null;
        }
        cleanupDestination(state, finalStatus);
        notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mGotData,
                state.mFilename, state.mNewUri, state.mMimeType);

        DownloadHandler.getInstance().dequeueDownload(mInfo.mId);

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

From source file:com.android.talkback.eventprocessor.ProcessorVolumeStream.java

@SuppressWarnings("deprecation")
public ProcessorVolumeStream(FeedbackController feedbackController, CursorController cursorController,
        DimScreenController dimScreenController, TalkBackService service) {
    if (feedbackController == null)
        throw new IllegalStateException("CachedFeedbackController is null");
    if (cursorController == null)
        throw new IllegalStateException("CursorController is null");
    if (dimScreenController == null)
        throw new IllegalStateException("DimScreenController is null");

    mAudioManager = (AudioManager) service.getSystemService(Context.AUDIO_SERVICE);
    mCursorController = cursorController;
    mFeedbackController = feedbackController;

    final PowerManager pm = (PowerManager) service.getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, WL_TAG);

    mPrefs = SharedPreferencesUtils.getSharedPreferences(service);
    mService = service;// w w  w . j av a 2s .c o  m
    mDimScreenController = dimScreenController;
    mPatternDetector = new VolumeButtonPatternDetector();
    mPatternDetector.setOnPatternMatchListener(this);
}

From source file:com.mappn.gfan.common.download.DownloadThread.java

/**
 * Executes the download in a separate thread
 *//*from  w  w w  .  j ava 2  s .co m*/
public void run() {

    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    State state = new State(mInfo);
    AndroidHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = DownloadManager.Impl.STATUS_UNKNOWN_ERROR;

    try {
        PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, com.mappn.gfan.common.util.Utils.sLogTag);
        wakeLock.acquire();

        Utils.D("initiating download for " + mInfo.mUri);

        client = HttpClientFactory.get().getHttpClient();

        boolean finished = false;
        while (!finished) {

            Utils.D("Initiating request for download " + mInfo.mId + " url " + mInfo.mUri);

            HttpGet request = new HttpGet(state.mRequestUri);
            try {
                executeDownload(state, client, request);
                finished = true;
            } catch (RetryDownload exc) {
                // fall through
            } finally {
                request.abort();
                request = null;
            }
        }

        Utils.D("download completed for " + mInfo.mUri);

        if (!checkFile(state)) {
            throw new Throwable("File MD5 code is not the same as server");
        }

        finalizeDestinationFile(state);
        finalStatus = DownloadManager.Impl.STATUS_SUCCESS;
    } catch (StopRequest error) {
        // remove the cause before printing, in case it contains PII
        Utils.W("Aborting request for download " + mInfo.mId + " url: " + mInfo.mUri + " : "
                + error.getMessage());
        finalStatus = error.mFinalStatus;
        // fall through to finally block
    } catch (Throwable ex) { //sometimes the socket code throws unchecked exceptions
        Utils.W("Exception for id " + mInfo.mId + " url: " + mInfo.mUri + ": " + ex);
        // falls through to the code that reports an error
    } finally {
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        if (client != null) {
            client = null;
        }
        cleanupDestination(state, finalStatus);
        notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mRedirectCount,
                state.mGotData, state.mFilename, state.mNewUri, state.mMimeType);
        mInfo.mHasActiveThread = false;
    }
}