Example usage for android.os PowerManager newWakeLock

List of usage examples for android.os PowerManager newWakeLock

Introduction

In this page you can find the example usage for android.os PowerManager newWakeLock.

Prototype

public WakeLock newWakeLock(int levelAndFlags, String tag) 

Source Link

Document

Creates a new wake lock with the specified level and flags.

Usage

From source file:com.simplelife.seeds.android.utils.downloadprocess.DownloadThread.java

/**
 * Executes the download in a separate thread
 *//*from w w w  . j  a v  a  2s .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);

            Log.i(Constants.TAG, "mRequestUri: " + state.mRequestUri);
            Log.i(Constants.TAG, "mRequestRef: " + state.mRequestRef);
            HttpPost request = new HttpPost(SeedsDefinitions.SEEDS_SERVER_DOWNLOADPHP);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("ref", state.mRequestRef));
            request.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

            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:org.navitproject.navit.Navit.java

/** Called when the activity is first created. */
@Override/*from w  w  w.ja va2  s .  co  m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    else
        this.getActionBar().hide();

    dialogs = new NavitDialogs(this);

    NavitResources = getResources();

    // only take arguments here, onResume gets called all the time (e.g. when screenblanks, etc.)
    Navit.startup_intent = this.getIntent();
    // hack! Remember time stamps, and only allow 4 secs. later in onResume to set target!
    Navit.startup_intent_timestamp = System.currentTimeMillis();
    Log.e("Navit", "**1**A " + startup_intent.getAction());
    Log.e("Navit", "**1**D " + startup_intent.getDataString());

    // init translated text
    NavitTextTranslations.init();

    // NOTIFICATION
    // Setup the status bar notification      
    // This notification is removed in the exit() function
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // Grab a handle to the NotificationManager
    Notification NavitNotification = new Notification(R.drawable.ic_notify,
            getString(R.string.notification_ticker), System.currentTimeMillis()); // Create a new notification, with the text string to show when the notification first appears
    PendingIntent appIntent = PendingIntent.getActivity(getApplicationContext(), 0, getIntent(), 0);
    //      FIXME : needs a fix for sdk 23
    //      NavitNotification.setLatestEventInfo(getApplicationContext(), "Navit", getString(R.string.notification_event_default), appIntent);   // Set the text in the notification
    //      NavitNotification.flags|=Notification.FLAG_ONGOING_EVENT;   // Ensure that the notification appears in Ongoing
    //      nm.notify(R.string.app_name, NavitNotification);   // Set the notification

    // Status and navigation bar sizes
    // These are platform defaults and do not change with rotation, but we have to figure out which ones apply
    // (is the navigation bar visible? on the side or at the bottom?)
    Resources resources = getResources();
    int shid = resources.getIdentifier("status_bar_height", "dimen", "android");
    int adhid = resources.getIdentifier("action_bar_default_height", "dimen", "android");
    int nhid = resources.getIdentifier("navigation_bar_height", "dimen", "android");
    int nhlid = resources.getIdentifier("navigation_bar_height_landscape", "dimen", "android");
    int nwid = resources.getIdentifier("navigation_bar_width", "dimen", "android");
    status_bar_height = (shid > 0) ? resources.getDimensionPixelSize(shid) : 0;
    action_bar_default_height = (adhid > 0) ? resources.getDimensionPixelSize(adhid) : 0;
    navigation_bar_height = (nhid > 0) ? resources.getDimensionPixelSize(nhid) : 0;
    navigation_bar_height_landscape = (nhlid > 0) ? resources.getDimensionPixelSize(nhlid) : 0;
    navigation_bar_width = (nwid > 0) ? resources.getDimensionPixelSize(nwid) : 0;
    Log.d(TAG, String.format(
            "status_bar_height=%d, action_bar_default_height=%d, navigation_bar_height=%d, navigation_bar_height_landscape=%d, navigation_bar_width=%d",
            status_bar_height, action_bar_default_height, navigation_bar_height,
            navigation_bar_height_landscape, navigation_bar_width));
    if ((ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
            || (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
        Log.d(TAG, "ask for permission(s)");
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_FINE_LOCATION }, MY_PERMISSIONS_REQUEST_ALL);
    }
    // get the local language -------------
    Locale locale = java.util.Locale.getDefault();
    String lang = locale.getLanguage();
    String langu = lang;
    String langc = lang;
    Log.e("Navit", "lang=" + lang);
    int pos = langu.indexOf('_');
    if (pos != -1) {
        langc = langu.substring(0, pos);
        NavitLanguage = langc + langu.substring(pos).toUpperCase(locale);
        Log.e("Navit", "substring lang " + NavitLanguage.substring(pos).toUpperCase(locale));
        // set lang. for translation
        NavitTextTranslations.main_language = langc;
        NavitTextTranslations.sub_language = NavitLanguage.substring(pos).toUpperCase(locale);
    } else {
        String country = locale.getCountry();
        Log.e("Navit", "Country1 " + country);
        Log.e("Navit", "Country2 " + country.toUpperCase(locale));
        NavitLanguage = langc + "_" + country.toUpperCase(locale);
        // set lang. for translation
        NavitTextTranslations.main_language = langc;
        NavitTextTranslations.sub_language = country.toUpperCase(locale);
    }
    Log.e("Navit", "Language " + lang);

    SharedPreferences prefs = getSharedPreferences(NAVIT_PREFS, MODE_PRIVATE);
    map_filename_path = prefs.getString("filenamePath",
            Environment.getExternalStorageDirectory().getPath() + "/navit/");

    // make sure the new path for the navitmap.bin file(s) exist!!
    File navit_maps_dir = new File(map_filename_path);
    navit_maps_dir.mkdirs();

    // make sure the share dir exists
    File navit_data_share_dir = new File(NAVIT_DATA_SHARE_DIR);
    navit_data_share_dir.mkdirs();

    Display display_ = getWindowManager().getDefaultDisplay();
    int width_ = display_.getWidth();
    int height_ = display_.getHeight();
    metrics = new DisplayMetrics();
    display_.getMetrics(Navit.metrics);
    int densityDpi = (int) ((Navit.metrics.density * 160) - .5f);
    Log.e("Navit", "Navit -> pixels x=" + width_ + " pixels y=" + height_);
    Log.e("Navit", "Navit -> dpi=" + densityDpi);
    Log.e("Navit", "Navit -> density=" + Navit.metrics.density);
    Log.e("Navit", "Navit -> scaledDensity=" + Navit.metrics.scaledDensity);

    ActivityResults = new NavitActivityResult[16];
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "NavitDoNotDimScreen");

    if (!extractRes(langc, NAVIT_DATA_DIR + "/locale/" + langc + "/LC_MESSAGES/navit.mo")) {
        Log.e("Navit", "Failed to extract language resource " + langc);
    }

    if (densityDpi <= 120) {
        my_display_density = "ldpi";
    } else if (densityDpi <= 160) {
        my_display_density = "mdpi";
    } else if (densityDpi < 240) {
        my_display_density = "hdpi";
    } else if (densityDpi < 320) {
        my_display_density = "xhdpi";
    } else if (densityDpi < 480) {
        my_display_density = "xxhdpi";
    } else if (densityDpi < 640) {
        my_display_density = "xxxhdpi";
    } else {
        Log.e("Navit", "found device of very high density (" + densityDpi + ")");
        Log.e("Navit", "using xxxhdpi values");
        my_display_density = "xxxhdpi";
    }

    if (!extractRes("navit" + my_display_density, NAVIT_DATA_DIR + "/share/navit.xml")) {
        Log.e("Navit", "Failed to extract navit.xml for " + my_display_density);
    }

    // --> dont use android.os.Build.VERSION.SDK_INT, needs API >= 4
    Log.e("Navit", "android.os.Build.VERSION.SDK_INT=" + Integer.valueOf(android.os.Build.VERSION.SDK));
    NavitMain(this, NavitLanguage, Integer.valueOf(android.os.Build.VERSION.SDK), my_display_density,
            NAVIT_DATA_DIR + "/bin/navit", map_filename_path);

    showInfos();

    Navit.mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
}

From source file:com.googlecode.eyesfree.brailleback.DisplayManager.java

/**
 * Creates an instance of this class and starts the internal thread to
 * connect to the braille display service.  {@code context} is used to
 * connect to the display service.  {@code translator} is used for braille
 * translation.  The various listeners will be called as appropriate and
 * on the same thread that was used to create this object.  The current
 * thread must have a prepared looper.// w  w w  .  j a v a  2s .  c  om
 */
public DisplayManager(TranslatorManager translatorManager, Context context,
        OnPanOverflowListener panOverflowListener,
        Display.OnConnectionStateChangeListener connectionStateChangeListener,
        OnMappedInputEventListener mappedInputEventListener) {
    mTranslatorManager = translatorManager;
    mTranslatorManager.addOnTablesChangedListener(this);
    mContext = context;
    mPanOverflowListener = panOverflowListener;
    mConnectionStateChangeListener = connectionStateChangeListener;
    mMappedInputEventListener = mappedInputEventListener;
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,
            "BrailleBack");
    mHandlerThread = new HandlerThread("DisplayManager") {
        @Override
        public void onLooperPrepared() {
            mDisplay = new OverlayDisplay(mContext, new DisplayClient(mContext));
            mDisplay.setOnConnectionStateChangeListener(DisplayManager.this);
            mDisplay.setOnInputEventListener(DisplayManager.this);
        }
    };
    mHandlerThread.start();
    mDisplayHandler = new DisplayHandler(mHandlerThread.getLooper());
    mCallbackHandler = new CallbackHandler();
}

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 w ww .ja v  a2  s. co 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:cn.keyshare.download.core.DownloadThread.java

/**
  * Executes the download in a separate thread
  *//*  w  w  w  .  ja va2 s . co m*/
 @SuppressLint("Wakelock")
 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 + ": " + "  final status is " + error.mFinalStatus
                         + " fileName is " + mInfo.mFileName + " download title is " + mInfo.mTitle
                         + 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:org.cowboycoders.cyclismo.turbo.TurboService.java

@Override
public void onCreate() {
    super.onCreate();
    trackRecordingServiceConnection = new TrackRecordingServiceConnection(this, bindChangedCallback);
    // trackRecordingServiceConnection.startAndBind();
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    this.gpsAccuracy = getApplicationContext().getResources().getInteger(R.integer.SIMULATED_LOCATION_ACCURACY);
    this.wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TurboService.WAKE_LOCK);
}

From source file:net.sourceforge.kalimbaradio.androidapp.service.DownloadServiceImpl.java

@Override
public void onCreate() {
    Util.setUncaughtExceptionHandler(this);
    super.onCreate();

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

    mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
        @Override//from  w  ww  .  ja  v a 2s  .c om
        public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
            handleError(new Exception("MediaPlayer error: " + what + " (" + more + ")"));
            return false;
        }
    });

    if (equalizerAvailable) {
        equalizerController = new EqualizerController(this, mediaPlayer);
        if (!equalizerController.isAvailable()) {
            equalizerController = null;
        } else {
            equalizerController.loadSettings();
        }
    }
    if (visualizerAvailable) {
        visualizerController = new VisualizerController(this, mediaPlayer);
        if (!visualizerController.isAvailable()) {
            visualizerController = null;
        }
    }

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

    instance = this;
    lifecycleSupport.onCreate();
}

From source file:org.qeo.android.service.QeoService.java

private void enableNetworkSettings() {
    LOG.fine("Enable network change monitoring");
    mOnNetworkConnectivityChanged = new BroadcastReceiver() {
        @SuppressLint("Wakelock")
        @Override/*  w  w  w  .j  a v a 2 s.  c  o  m*/
        public void onReceive(Context context, Intent intent) {

            /*
             * Check if there is still a connected active network interface. If not, take a wakelock to make sure
             * DDS has the time to let all of it's timers time out properly. This is especially needed when the
             * network goes down due to the device going in sleep mode.
             */
            ConnectivityManager connMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInf = connMgr.getActiveNetworkInfo();
            if (((activeNetworkInf != null) && (!activeNetworkInf.isConnected()))
                    || (activeNetworkInf == null)) {
                PowerManager powerMgr = (PowerManager) getSystemService(POWER_SERVICE);
                PowerManager.WakeLock wakeLock = powerMgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

                LOG.info("Take wakelock for 40 seconds");
                wakeLock.acquire(40 * 1000);
            }

            configureNetworkSettings(activeNetworkInf);
        }

    };
    registerReceiver(mOnNetworkConnectivityChanged, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();
    configureNetworkSettings(activeNetworkInfo);
}

From source file:com.mobilyzer.util.PhoneUtils.java

/** Wakes up the CPU of the phone if it is sleeping. */
public synchronized void acquireWakeLock() {
    if (wakeLock == null) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "tag");
    }// w  ww.ja va  2 s.c  om
    Logger.d("PowerLock acquired");
    wakeLock.acquire();
}

From source file:the.joevlc.AudioService.java

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

    // Get libVLC instance
    try {/*www. j  a  v  a2 s.  c  o  m*/
        mLibVLC = LibVLC.getInstance();
    } catch (LibVlcException e) {
        e.printStackTrace();
    }

    Thread.setDefaultUncaughtExceptionHandler(new VlcCrashHandler());

    mCallback = new HashMap<IAudioServiceCallback, Integer>();
    mMediaList = new ArrayList<Media>();
    mPrevious = new Stack<Media>();
    mEventManager = EventManager.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(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("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);
}