Example usage for android.os PowerManager PARTIAL_WAKE_LOCK

List of usage examples for android.os PowerManager PARTIAL_WAKE_LOCK

Introduction

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

Prototype

int PARTIAL_WAKE_LOCK

To view the source code for android.os PowerManager PARTIAL_WAKE_LOCK.

Click Source Link

Document

Wake lock level: Ensures that the CPU is running; the screen and keyboard backlight will be allowed to go off.

Usage

From source file:com.dragedy.playermusic.service.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, "Phonograph headset button");
        mWakeLock.setReferenceCounted(false);
    }//from   w w  w.  java  2 s.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:it.baywaylabs.jumpersumo.twitter.TwitterListener.java

/**
 * Method auto invoked pre execute the task.<br />
 * This method read the last mention id from Shared Preferences.
 *///ww w  .  j  a va  2  s.  co  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();

    sharedPref = context.getSharedPreferences(Constants.MY_PREFERENCES, Context.MODE_PRIVATE);
    editor = sharedPref.edit();

    idLastTwit = sharedPref.getLong(Constants.LAST_ID_MENTIONED, 0);

}

From source file:ru.kudzmi.rajitaku.radioService.RadioService.java

private void initMediaPlayer() {
    mPlayer = new MediaPlayer();
    mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mPlayer.setOnPreparedListener(this);
    mPlayer.setOnErrorListener(this);
    mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
}

From source file:net.patchingzone.ru4real.nuevo.TorchActivityPlugin.java

private void startWakeLock() {
    if (wakeLock == null) {
        Log.d(TAG, "wakeLock is null, getting a new WakeLock");
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        Log.d(TAG, "PowerManager acquired");
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKE_LOCK_TAG);
        Log.d(TAG, "WakeLock set");
    }//w w  w. ja  v  a 2s.c o m
    wakeLock.acquire();
    Log.d(TAG, "WakeLock acquired");
}

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

/**
 * Executes the download in a separate thread
 */// w  ww  . j a v a2 s .  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.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:esolz.connexstudent.apprtc.ConnectActivity.java

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

    //=============Power locker

    threadmanager = new Handler();

    callRejectionThred = new Runnable() {
        @Override/*from  ww w . j  av  a2 s .  c o  m*/
        public void run() {

            //======Missed Call and no answer

            SimpleDateFormat frmatr = new SimpleDateFormat("dd MMM,yyyy-HH:mm");

            cDB.insertInLogTable(getIntent().getStringExtra("PHONE"),
                    cDB.getUserNameFromPhone(getIntent().getStringExtra("PHONE")),
                    cDB.getUserImage(getIntent().getStringExtra("PHONE")), "missed",
                    frmatr.format(new Date(Calendar.getInstance().getTimeInMillis())));

            fireMissedCall(cDB.getUserNameFromPhone(getIntent().getStringExtra("PHONE")));
            //==================================

            Intent i = new Intent(getApplicationContext(), RingToneService.class);
            i.setAction(RingToneService.ACTION_KILL);
            startService(i);
            finish();
        }
    };

    powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "RingToneServiceLockerActivity");
    wakeLock.acquire();

    cDB = new ConnexDB(getApplicationContext());
    // Get setting keys.
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    keyprefVideoCallEnabled = getString(R.string.pref_videocall_key);
    keyprefResolution = getString(R.string.pref_resolution_key);
    keyprefFps = getString(R.string.pref_fps_key);
    keyprefCaptureQualitySlider = getString(R.string.pref_capturequalityslider_key);
    keyprefVideoBitrateType = getString(R.string.pref_startvideobitrate_key);
    keyprefVideoBitrateValue = getString(R.string.pref_startvideobitratevalue_key);
    keyprefVideoCodec = getString(R.string.pref_videocodec_key);
    keyprefHwCodecAcceleration = getString(R.string.pref_hwcodec_key);
    keyprefCaptureToTexture = getString(R.string.pref_capturetotexture_key);
    keyprefAudioBitrateType = getString(R.string.pref_startaudiobitrate_key);
    keyprefAudioBitrateValue = getString(R.string.pref_startaudiobitratevalue_key);
    keyprefAudioCodec = getString(R.string.pref_audiocodec_key);
    keyprefNoAudioProcessingPipeline = getString(R.string.pref_noaudioprocessing_key);
    keyprefAecDump = getString(R.string.pref_aecdump_key);
    keyprefOpenSLES = getString(R.string.pref_opensles_key);
    keyprefDisplayHud = getString(R.string.pref_displayhud_key);
    keyprefTracing = getString(R.string.pref_tracing_key);
    keyprefRoomServerUrl = getString(R.string.pref_room_server_url_key);
    keyprefRoom = getString(R.string.pref_room_key);
    keyprefRoomList = getString(R.string.pref_room_list_key);

    setContentView(R.layout.activity_connect);

    getWindow().setFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON,
            WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED,
            WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    //=============permission management
    findViewById(R.id.notifoicatio).setVisibility(View.GONE);

    permissionChk();

    findViewById(R.id.rcv_call).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            //======Missed Call and no answer

            threadmanager.removeCallbacks(callRejectionThred);

            SimpleDateFormat frmatr = new SimpleDateFormat("dd MMM,yyyy-HH:mm");

            cDB.insertInLogTable(getIntent().getStringExtra("PHONE"),
                    cDB.getUserNameFromPhone(getIntent().getStringExtra("PHONE")),
                    cDB.getUserImage(getIntent().getStringExtra("PHONE")), "received",
                    frmatr.format(new Date(Calendar.getInstance().getTimeInMillis())));

            //==================================

            Intent i = new Intent(getApplicationContext(), RingToneService.class);
            i.setAction(RingToneService.ACTION_KILL_WITH_NOTHING);
            startService(i);

            ROOM_NAME = getIntent().getStringExtra("ROOM_NAME");

            pushHelperDhoperUrlAcceptence();

        }
    });

    findViewById(R.id.end_call).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            if (getIntent().getAction().equals(ACTION_APP)) {
                try {
                    if (mPlayer.isPlaying()) {
                        mPlayer.stop();
                        mPlayer.release();
                    }
                    finish();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                dialoerRejection(ConnexConstante.DOMAIN_URL + "push_send?roomId=000000&sender_id="
                        + ConnexApplication.getInstance().getUserID() + "&receiver_id=" + RECEIVER_ID
                        + "&mod=callEnded&pem_mod=prod");

            } else {

                //======Missed Call and Rejected by You

                //======Missed Call and no answer

                threadmanager.removeCallbacks(callRejectionThred);

                SimpleDateFormat frmatr = new SimpleDateFormat("dd MMM,yyyy-HH:mm");

                cDB.insertInLogTable(getIntent().getStringExtra("PHONE"),
                        cDB.getUserNameFromPhone(getIntent().getStringExtra("PHONE")),
                        cDB.getUserImage(getIntent().getStringExtra("PHONE")), "missed",
                        frmatr.format(new Date(Calendar.getInstance().getTimeInMillis())));

                fireMissedCall(cDB.getUserNameFromPhone(getIntent().getStringExtra("PHONE")));
                //==================================

                //==================================

                Intent i = new Intent(getApplicationContext(), RingToneService.class);
                i.setAction(RingToneService.ACTION_KILL);
                startService(i);
            }

            finish();
        }
    });

    if (mPlayer == null) {
        mPlayer = MediaPlayer.create(ConnectActivity.this, R.raw.dialing);
    }

}

From source file:org.pixmob.freemobile.netstat.SyncService.java

@Override
protected void onHandleIntent(Intent intent) {
    // Check if statistics upload is enabled.
    if (!prefs.getBoolean(Constants.SP_KEY_UPLOAD_STATS, false)) {
        Log.d(TAG, "Synchronization is disabled: skip sync");
        return;/*from  w w w  .  j a v a 2  s .  com*/
    }

    // Check if an Internet connection is available.
    final NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo == null || !netInfo.isAvailable() || !netInfo.isConnected()) {
        Log.d(TAG, "Network connectivity is not available: skip sync");
        return;
    }

    final PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    SQLiteDatabase db = null;
    try {
        wl.acquire();
        db = dbHelper.getWritableDatabase();
        run(intent, db);

        // Sync was successful: reset sync error count.
        internalPrefsEditor.remove(INTERNAL_SP_KEY_SYNC_ERRORS).commit();
    } catch (Exception e) {
        Log.e(TAG, "Failed to upload statistics", e);

        // Increment sync errors.
        final int syncErrors = internalPrefs.getInt(INTERNAL_SP_KEY_SYNC_ERRORS, 0);
        internalPrefsEditor.putInt(INTERNAL_SP_KEY_SYNC_ERRORS, syncErrors + 1).commit();
    } finally {
        if (db != null) {
            db.close();
        }
        wl.release();

        // Reschedule this service according to the sync error count.
        schedule(this, true);
    }

    Log.i(TAG, "Statistics upload done");
}

From source file:at.andreasrohner.spartantimelapserec.BackgroundService.java

@SuppressWarnings("deprecation")
@Override//w w  w.j  a  v a2 s  .  co m
public void onCreate() {
    created = true;

    settings = new RecSettings();
    settings.load(getApplicationContext(),
            PreferenceManager.getDefaultSharedPreferences(getApplicationContext()));

    createNotification(NOTIFICATION_ID);

    if (settings.isSchedRecEnabled() && settings.getSchedRecTime() > System.currentTimeMillis() + 10000) {
        AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(getApplicationContext(), ScheduleReceiver.class);
        PendingIntent alarmIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);

        alarmMgr.set(AlarmManager.RTC_WAKEUP, settings.getSchedRecTime(), alarmIntent);

        stopSelf();
        return;
    }

    // Create new SurfaceView, set its size to 1x1, move
    // it to the top left corner and set this service as a callback
    WindowManager winMgr = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    surfaceView = new SurfaceView(this);
    // deprecated setting, but required on Android versions prior to 3.0
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
        surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    surfaceView.getHolder().addCallback(this);

    LayoutParams layoutParams = new WindowManager.LayoutParams(1, 1,
            WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY, WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
            PixelFormat.TRANSLUCENT);
    layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
    winMgr.addView(surfaceView, layoutParams);

    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    wakeLock.setReferenceCounted(false);
    wakeLock.acquire();
}

From source file:com.snda.mymarket.providers.downloads.DownloadTask.java

/**
 * Executes the download in a separate thread
 *///from  w ww.  j  a v a2  s  .  co m
public void run() {
    if (mInfo.mStatus != Downloads.STATUS_RUNNING) {
        mInfo.mStatus = Downloads.STATUS_RUNNING;
        ContentValues values = new ContentValues();
        values.put(Downloads.COLUMN_STATUS, mInfo.mStatus);
        mContext.getContentResolver().update(mInfo.getAllDownloadsUri(), values, null, null);
    } else {
        if (Constants.LOGV) {
            Log.v(Constants.TAG, "download status is: " + mInfo.mStatus);
        }
    }

    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    State state = new State(mInfo);
    HttpStack 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);
        }

        if (Build.VERSION.SDK_INT >= 9) {
            client = new HurlStack();
        } else {
            // Prior to Gingerbread, HttpUrlConnection was unreliable.
            // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            client = new HttpClientStack(AndroidHttpClient.newInstance(userAgent()));
        }

        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 {
        mNotifer.notifyDownloadSpeed(mInfo.mId, 0);

        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        if (client != null) {
            try {
                client.close();
                client = null;
            } catch (IOException e) {
                e.printStackTrace();
                finalStatus = Downloads.STATUS_UNKNOWN_ERROR;
            }
        }
        cleanupDestination(state, finalStatus);
        notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mGotData,
                state.mFilename, state.mNewUri, state.mMimeType);
        mInfo.cancelTask();
    }
}

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  w  w .ja v a2s  .c o m*/
        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();
}