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.bluros.music.helpers.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, "Music headset button");
        mWakeLock.setReferenceCounted(false);
    }//from  w  w  w  . j a  v a2 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:com.thebigbang.ftpclient.FTPOperation.java

/**
 * will force keep the device turned on for all the operation duration.
 * @param params// ww  w.j a v  a  2s  .c  o  m
 * @return 
 */
@SuppressLint("Wakelock")
@SuppressWarnings("deprecation")
@Override
protected Boolean doInBackground(FTPBundle... params) {
    Thread.currentThread().setName("FTPOperationWorker");
    for (final FTPBundle bundle : params) {

        FTPClient ftp = new FTPClient();
        PowerManager pw = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
        WakeLock w = pw.newWakeLock(PowerManager.FULL_WAKE_LOCK, "FTP Client");
        try {
            // setup ftp connection:
            InetAddress addr = InetAddress.getByName(bundle.FTPServerHost);
            //set here the timeout.
            TimeoutThread timeout = new TimeoutThread(_timeOut, new FTPTimeout() {
                @Override
                public void Occurred(TimeoutException e) {
                    bundle.Exception = e;
                    bundle.OperationStatus = FTPOperationStatus.Failed;
                    publishProgress(bundle);
                }
            });
            timeout.start();
            ftp.connect(addr, bundle.FTPServerPort);
            int reply = ftp.getReplyCode();
            timeout.Stop();
            if (!FTPReply.isPositiveCompletion(reply)) {
                throw new IOException("connection refuse");
            }
            ftp.login(bundle.FTPCredentialUsername, bundle.FTPCredentialPassword);
            if (bundle.OperationType == FTPOperationType.Connect) {
                bundle.OperationStatus = FTPOperationStatus.Succed;
                publishProgress(bundle);
                continue;
            }
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.enterLocalPassiveMode();

            w.acquire();
            // then switch between enum of operation types.
            if (bundle.OperationType == FTPOperationType.RetrieveFilesFoldersList) {
                ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory);
                bundle.FilesOnCurrentPath = ftp.listFiles();
                bundle.FoldersOnCurrentPath = ftp.listDirectories();
                bundle.OperationStatus = FTPOperationStatus.Succed;
            } else if (bundle.OperationType == FTPOperationType.RetrieveFolderList) {
                ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory);
                bundle.FoldersOnCurrentPath = ftp.listDirectories();
                bundle.OperationStatus = FTPOperationStatus.Succed;
            } else if (bundle.OperationType == FTPOperationType.RetrieveFileList) {
                ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory);
                bundle.FilesOnCurrentPath = ftp.listFiles();
                bundle.OperationStatus = FTPOperationStatus.Succed;
            } else if (bundle.OperationType == FTPOperationType.GetData) {
                String finalFPFi = bundle.LocalFilePathName;
                // The remote filename to be downloaded.
                if (bundle.LocalWorkingDirectory != null && bundle.LocalWorkingDirectory != "") {
                    File f = new File(bundle.LocalWorkingDirectory);
                    f.mkdirs();

                    finalFPFi = bundle.LocalWorkingDirectory + finalFPFi;
                }
                FileOutputStream fos = new FileOutputStream(finalFPFi);

                // Download file from FTP server
                String finalFileN = bundle.RemoteFilePathName;
                if (bundle.RemoteWorkingDirectory != null && bundle.RemoteWorkingDirectory != "") {
                    finalFileN = bundle.RemoteWorkingDirectory + finalFileN;
                }
                boolean b = ftp.retrieveFile(finalFileN, fos);
                if (b)
                    bundle.OperationStatus = FTPOperationStatus.Succed;
                else
                    bundle.OperationStatus = FTPOperationStatus.Failed;
                fos.close();

            } else if (bundle.OperationType == FTPOperationType.SendData) {
                InputStream istr = new FileInputStream(bundle.LocalFilePathName);
                ftp.changeWorkingDirectory(bundle.RemoteWorkingDirectory);
                Boolean b = ftp.storeFile(bundle.RemoteFilePathName, istr);
                istr.close();
                if (b)
                    bundle.OperationStatus = FTPOperationStatus.Succed;
                else
                    bundle.OperationStatus = FTPOperationStatus.Failed;
            } else if (bundle.OperationType == FTPOperationType.DeleteData) {
                throw new IOException("DeleteData is Not yet implemented");
            }

            ftp.disconnect();
            // then finish/return.
            //publishProgress(bundle);
        } catch (IOException e) {
            e.printStackTrace();
            bundle.Exception = e;
            bundle.OperationStatus = FTPOperationStatus.Failed;
        }
        try {
            w.release();
        } catch (RuntimeException ex) {
            ex.printStackTrace();
        }
        publishProgress(bundle);
    }
    return true;
}

From source file:rp.soi.dmsd.notextingwhilewalking.DetectedActivitiesIntentService.java

/**
 * Handles incoming intents.//from   w  w  w.  jav a 2  s. c o  m
 * @param intent The Intent is provided (inside a PendingIntent) when requestActivityUpdates()
 *               is called.
 */
@Override
protected void onHandleIntent(Intent intent) {
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mOrientation = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
    mSensorManager.registerListener(this, mOrientation, SensorManager.SENSOR_DELAY_NORMAL);
    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

    ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
    Intent localIntent = new Intent(rp.soi.dmsd.notextingwhilewalking.Constants.BROADCAST_ACTION);

    // Get the list of the probable activities associated with the current state of the
    // device. Each activity is associated with a confidence level, which is an int between
    // 0 and 100.
    ArrayList<DetectedActivity> detectedActivities = (ArrayList) result.getProbableActivities();

    // Log each activity.
    Log.i(TAG, "activities detected");
    for (DetectedActivity da : detectedActivities) {
        Log.i(TAG, rp.soi.dmsd.notextingwhilewalking.Constants.getActivityString(getApplicationContext(),
                da.getType()) + " " + da.getConfidence() + "%");
        // trigger a notification if the walking activity has a confidence of > 50%

        //float[] xyz = mSensorManager.getOrientation();

        if (da.getType() == DetectedActivity.WALKING && da.getConfidence() > 15) {

            // For API 20 and higher
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Log.i(TAG, "Android version is HIGHER than 20 ");
                if (powerManager.isInteractive()) {
                    Log.i(TAG, "Screen is ON");
                    if (isPhoneFacingUp) {
                        Log.i(TAG, "Phone is facing UP.");
                        createNotification(true);
                    } else {
                        Log.i(TAG, "Phone is facing DOWN.");
                    }
                } else {
                    Log.i(TAG, "Screen is OFF");
                }
            } else {
                Log.i(TAG, "Android version is LOWER than 20 ");
                if (powerManager.isScreenOn()) {
                    Log.i(TAG, "Screen is ON");
                    if (isPhoneFacingUp) {
                        Log.i(TAG, "Phone is facing UP.");
                        createNotification(true);
                    } else {
                        Log.i(TAG, "Phone is facing DOWN.");
                    }
                } else {
                    Log.i(TAG, "Screen is OFF");
                }
            }
        }

    }

    // Broadcast the list of detected activities.
    localIntent.putExtra(Constants.ACTIVITY_EXTRA, detectedActivities);
    LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
}

From source file:com.konsula.app.gcm.MyGcmListenerService.java

/**
 * Called when message is received./* w  ww. j a v  a  2  s .c o  m*/
 *
 * @param from SenderID of the sender.
 * @param data Data bundle containing message data as key/value pairs.
 *             For Set of keys use data.keySet().
 */
// [START receive_message]
@Override
public void onMessageReceived(String from, Bundle data) {
    String message = data.getString("message");
    togo = data.getString("type");
    bundle = data;
    //        Settings.System.putString(this.getContentResolver(), Settings.System.NEXT_ALARM_FORMATTED, message);

    Log.d(TAG, String.valueOf(data));
    Log.d(TAG, "Message: " + message);

    if (from.startsWith("/topics/")) {
        // message received from some topic.
    } else {
        // normal downstream message.
    }

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
    wl.acquire(3000);
    wl.release();

    //kalo misalnya app kebuka, message diterima disini.

    // [START_EXCLUDE]
    /**
     * Production applications would usually process the message here.
     * Eg: - Syncing with server.
     *     - Store message in local database.
     *     - Update UI.
     */

    /**
     * In some cases it may be useful to show a notification indicating to the user
     * that a message was received.
     */
    handleGCM(bundle);
    sendNotification(message);
    // [END_EXCLUDE]
}

From source file:com.techmighty.baseplayer.helpers.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, "BasePlayer headset button");
        mWakeLock.setReferenceCounted(false);
    }//from   w  w  w.  j ava 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:org.awokenwell.proximity.ProximitySensorListener.java

/**
 * Sets the context of the Command. This can then be used to do things like
 * get file paths associated with the Activity.
 *
 * @param cordova The context of the main Activity.
 * @param webView The CordovaWebView Cordova is running in.
 *//*from  www  .  ja va2 s . c o  m*/
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
    super.initialize(cordova, webView);
    this.sensorManager = (SensorManager) cordova.getActivity().getSystemService(Context.SENSOR_SERVICE);
    this.powerManager = (PowerManager) cordova.getActivity().getSystemService(Context.POWER_SERVICE);
    this.wakeLock = null;

}

From source file:com.technologx.blaze.player.helpers.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, "Blaze headset button");
        mWakeLock.setReferenceCounted(false);
    }/*from w  w w  .j ava  2s  . c  om*/
    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:nu.yona.app.api.service.ActivityMonitorService.java

@Override
public void onCreate() {
    super.onCreate();
    restartReceiver();/*ww  w .  j  a  va 2s.co m*/
    powerManager = ((PowerManager) YonaApplication.getAppContext().getSystemService(Context.POWER_SERVICE));
}

From source file:com.jelly.music.player.AsyncTasks.AsyncGetGooglePlayMusicMetadataTask.java

@Override
protected void onPreExecute() {
    super.onPreExecute();

    //Hide the actionbar.
    mApp.setIsBuildingLibrary(true);// w  ww.  ja  va2 s .c  o m

    //Acquire a wakelock to prevent the CPU from sleeping while the process is running.
    pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
            "com.jelly.music.player.AsyncTasks.AsyncGetGooglePlayMusicMetadata");
    wakeLock.acquire();

    //Set the initial setting of the progressbar as indeterminate.
    currentTask = mContext.getResources().getString(R.string.contacting_google_play_music);

}