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.haha01haha01.harail.DatabaseDownloader.java

@Override
protected void onHandleIntent(Intent workIntent) {
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, NAME);

    NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Notification.Builder builder = new Notification.Builder(this);
    builder.setContentTitle("HaRail GTFS Database").setContentText("Downloading file")
            .setSmallIcon(android.R.drawable.ic_popup_sync).setProgress(0, 0, true);
    notifyManager.notify(1, builder.build());

    wakeLock.acquire();/*  w ww .j av a  2s.  c om*/
    try {
        String filename = "harail_irw_gtfs_" + Utils.getCurrentDateString() + ".zip";
        File zip_file = new File(
                new File(Environment.getExternalStorageDirectory(), Environment.DIRECTORY_DOWNLOADS), filename);
        if (downloadFile(irw_gtfs_server, irw_gtfs_port, "anonymous", "", irw_gtfs_filename, zip_file)) {
            sendFinished(extractDb(zip_file, notifyManager, builder));
        } else {
            sendFinished(false);
        }
        wakeLock.release();
    } catch (IOException e) {
        sendFinished(false);
        builder.setContentText("Download failed").setSmallIcon(android.R.drawable.ic_dialog_alert)
                .setProgress(0, 0, false);
        notifyManager.notify(1, builder.build());
        wakeLock.release();
    }
}

From source file:com.jay.pea.mhealthapp2.utilityClasses.AlarmReceiver.java

/**
 * OnRecieve method that recieves calls form the AlertManager class and then applies some logic to fire notifications to the user.
 *
 * @param context// www.jav a2s. c om
 * @param intent
 */
@Override
public void onReceive(Context context, Intent intent) {
    Log.d(TAG, "onRecieve");
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MedMinder");
    //Acquire the lock
    wl.acquire();

    dose = null;
    dose = (Dose) intent.getSerializableExtra(AlertManager.ALARMSTRING);
    Log.d(TAG,
            " This dose is " + dose.getMedication().getMedName() + "  " + dose.getDoseTime().toString(dtfTime));

    if (dose == null) {
        Log.d(TAG, "Alert object Extra is null");
    }

    //get the parent med
    Medication med = dose.getMedication();
    int alertCount = 0;
    for (DateTime doseDueDT : med.getDoseMap1().keySet()) {
        DateTime doseTakenDT = med.getDoseMap1().get(doseDueDT);
        if (doseDueDT.isBefore(new DateTime().now())
                && doseDueDT.isAfter(new DateTime().withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0))
                && doseTakenDT.equals(new DateTime(0))) {
            alertCount++;
        }
    }

    if (alertCount == 0) {
        return;
    }

    SharedPreferences sharedPref = context.getSharedPreferences("AlertCounter", 0);
    int alertCountPref = sharedPref.getInt(med.getMedName(), 0);
    SharedPreferences.Editor editor = sharedPref.edit();

    DateTime now = new DateTime().now();
    int notifID = dose.getMedication().getDbID();
    Random rand = new Random();
    //int notifID = rand.nextInt();
    Log.d(TAG, dose.getMedication().getDbID() + "   " + dose.getDoseTime().getMillisOfDay());

    if (dose.getTakenTime().toString(dtfDate).equals(new DateTime(0).toString(dtfDate))) {
        //            if ((dose.getDoseTime().getMillis() + alertMissedWindowArray[dose.getMedication().getFreq() - 1] * 2) > new DateTime().getMillis());
        String alertString = "You have " + alertCount + " missed doses for " + med.getMedName();
        if (alertCount == 1) {
            alertString = "You have a missed dose for " + med.getMedName();
        }

        //check if the dose is due +/- 15mins and advise that a dose is due.
        long diffMillis = dose.getDoseTime().getMillis() - new DateTime().now().getMillis();
        Log.d(TAG, diffMillis + "   dose time = " + dose.getDoseTime().getMillis() + " now= "
                + new DateTime().now().getMillis());
        boolean doseDue = Math.abs(diffMillis) < 1800000;
        if (doseDue) {
            alertString = dose.getMedication().getDose() + " of " + dose.getMedication().getMedName()
                    + " is due now.";
        }

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                .setSmallIcon(R.mipmap.medminder_icon).setContentTitle("MedMinder").setContentText(alertString);

        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mBuilder.setSound(alarmSound);
        // Creates an explicit intent for an Activity in your app
        Intent resultIntent = new Intent(context, MainActivity.class);

        // The stack builder object will contain an artificial back stack for the started Activity.
        // This ensures that navigating backward from the Activity leads out of your application to the Home screen.
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(MainActivity.class);
        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        // mId allows you to update the notification later on.
        mNotificationManager.notify(notifID, mBuilder.build());
        Log.d(TAG, " Notification sent " + notifID);
        //
        //
        //            editor.putInt(med.getMedName(), alertCount);
        //            editor.commit();

        //Release the lock
        wl.release();
    }
}

From source file:fr.inria.ucn.Helpers.java

/**
 * Acquire the wakelock to keep the CPU running.
 * @param c/*from www  .  ja va2 s .c om*/
 */
public static synchronized void acquireLock(Context c) {
    PowerManager mgr = (PowerManager) c.getSystemService(Context.POWER_SERVICE);
    if (lock == null) {
        lock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.CPU_WAKE_LOCK);
        lock.setReferenceCounted(true);
    }
    Log.d(Constants.LOGTAG, "acquire lock");
    lock.acquire();
}

From source file:com.google.android.apps.muzei.sync.TaskQueueService.java

@Override
public int onStartCommand(final Intent intent, int flags, final int startId) {
    if (intent.getAction() == null) {
        stopSelf();/*from w  w w. jav a2  s . co m*/
        return START_NOT_STICKY;
    }

    String action = intent.getAction();
    if (ACTION_DOWNLOAD_CURRENT_ARTWORK.equals(action)) {
        // Handle internal download artwork request
        new DownloadArtworkTask(this) {
            PowerManager.WakeLock lock;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // This is normally not started by a WakefulBroadcastReceiver so request a
                // new wakelock.
                PowerManager pwm = (PowerManager) getSystemService(POWER_SERVICE);
                lock = pwm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
                lock.acquire(DOWNLOAD_ARTWORK_WAKELOCK_TIMEOUT_MILLIS);
            }

            @Override
            protected void onPostExecute(Boolean success) {
                super.onPostExecute(success);
                if (success) {
                    cancelArtworkDownloadRetries();
                } else {
                    scheduleRetryArtworkDownload();
                }
                if (lock.isHeld()) {
                    lock.release();
                }
                WakefulBroadcastReceiver.completeWakefulIntent(intent);
                stopSelf(startId);
            }
        }.execute();

    }
    return START_REDELIVER_INTENT;
}

From source file:com.connectsdk.smarthomesampler.SceneService.java

@Override
public void onCreate() {
    super.onCreate();
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Wake Lock");
    wakeLock.acquire();//from ww w.j  ava 2  s.c om

    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(getString(R.string.app_name))
            .setContentText(getString(R.string.smarthome_service_is_working)).setContentIntent(pendingIntent)
            .build();

    startForeground(NOTIFICATION_ID, notification);
}

From source file:com.reallynourl.nourl.fmpfoldermusicplayer.backend.MediaService.java

private void setupMediaPlayer(ExtendedFile file) {
    mIsPreparedToPlay = false;/*from w w w .ja v  a  2  s.  com*/
    mCurrentFile = file;
    if (mMediaPlayer == null) {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnErrorListener(this);
        mMediaPlayer.setOnInfoListener(this);
    } else {
        if (mMediaPlayer.isPlaying())
            mMediaPlayer.stop();
        mMediaPlayer.reset();
    }
    try {
        mMediaPlayer.setDataSource(getApplicationContext(), Uri.fromFile(file));
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), "Failed to load the file.", Toast.LENGTH_LONG).show();
        return;
    }
    mMediaPlayer.prepareAsync();
}

From source file:osu.crowd_ml.BackgroundDataSend.java

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

    // TODO(david soller) : fix these comments
    // Step 1. Extract necessary information
    UID = MultiprocessPreferences.getDefaultSharedPreferences(this).getString("uid", "");

    // Step 3. Initialize necessary data.
    dataSender = new DataSender(UID);

    // Step 4. Create a listener to handle wifi connectivity.
    network = isDataConnected();//from   ww  w .j a  v a2  s  .c o m
    receiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            network = isDataConnected();
            handleWifiChange();
        }
    };
    registerReceiver(receiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));

    // Step 5. Acquire a lock on the CPU for computation during sleep.
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
    wakeLock.acquire();

    // Step 6. Begin this service as a foreground service.
    Intent notificationIntent = new Intent(this, Login.class);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(this)
            .setSmallIcon(android.R.drawable.stat_notify_sync).setContentTitle("Background Service Running")
            .setContentText("Processing data").setContentIntent(pendingIntent).build();

    /*
     * NOTE: A foreground service is used to decouple the service from the application. When a
     * user exits from the application view (the Login activity), using a foreground service
     * prevents this service from restarting. The number supplied below is arbitrary but must be
     * > 0.
     * */
    startForeground(1337, notification);
}

From source file:uk.co.workingedge.phonegap.plugin.PowerManagement.java

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {

    Log.d(LOG_TAG, "Plugin execute called - " + this.toString());
    Log.d(LOG_TAG, "Action is " + action);

    try {//  w ww .  j  a v a2 s . c  om
        if (action.equals("acquire")) {
            String type = args.optString(0);
            if (type.equals("dim")) {
                Log.d(LOG_TAG, "Type: dim wakelock");
                this.acquire(PowerManager.SCREEN_DIM_WAKE_LOCK);
            } else if (type.equals("bright")) {
                Log.d(LOG_TAG, "Type: bright wakelock");
                this.acquire(PowerManager.SCREEN_BRIGHT_WAKE_LOCK);
            } else if (type.equals("partial")) {
                Log.d(LOG_TAG, "Type: partial wakelock");
                this.acquire(PowerManager.PARTIAL_WAKE_LOCK);
            } else {
                Log.d(LOG_TAG, "Type: full wakelock");
                this.acquire(PowerManager.FULL_WAKE_LOCK);
            }
        } else if (action.equals("release")) {
            this.release();
        }
    } catch (Exception e) {
        return false;
    }

    callbackContext.success();
    return true;
}

From source file:my.home.lehome.service.SendMsgIntentService.java

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

    if (mWakeLock == null) {
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        mWakeLock.acquire();//from w  w  w .j  a  v  a 2  s. c o  m
        Log.d(TAG, "acquire wakelock");
    }

    mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}

From source file:com.andreadec.musicplayer.IndexFolderService.java

@Override
protected void onHandleIntent(Intent intent) {
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "IndexFolderService");
    wakeLock.acquire();//  ww  w.j a  va 2s.  co m

    try {
        SongsDatabase songsDatabase = new SongsDatabase();
        db = songsDatabase.getWritableDatabase();

        File folder = new File(intent.getStringExtra("folder"));
        clearSongsDatabase();
        index(folder);

        db.close();
    } catch (Exception e) {
    } // Just to be sure the wake lock is always released, also if something wrong happens.

    wakeLock.release();
}