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.wl.android.downloadwithprogressbutton.downloads.DownloadThread.java

/**
 * Executes the download in a separate thread
 *//*ww  w  .j ava 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);

            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:it.technocontrolsystem.hypercontrol.gcm.HCGcmListenerService.java

/**
 * Create and show a simple notification containing the received GCM message.
 *//*w  ww . j  a v  a  2 s .  c o  m*/
private void sendNotification(Bundle data) {
    String messagetype = data.getString("messagetype");

    switch (messagetype) {

    // crea una notifica che quando cliccata apre il site in allarme
    case "alarm":

        String siteUUID = data.getString("sitenum");
        Site site = DB.getSiteByUUID(siteUUID);

        if (site != null) {

            Intent intent = new Intent();
            intent.setClass(this, SiteActivity.class);
            intent.putExtra("siteid", site.getId());
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                    PendingIntent.FLAG_ONE_SHOT);

            String title = "Allarme";
            title += " " + site.getName();

            //                String msg = "";
            //                try {
            //                    int plantnum = Integer.parseInt(data.getString("plantnum"));
            //                    Plant plant = DB.getPlantBySiteAndNumber(siteid, plantnum);
            //                    msg += plant.getName();
            //
            //                    int areanum = Integer.parseInt(data.getString("areanum"));
            //                    Area area = DB.getAreaByIdPlantAndAreaNumber(plant.getId(), areanum);
            //                    msg += " " + area.getName();
            //
            //                } catch (Exception e) {
            //                }

            String msg = data.getString("message");
            Uri defaultSoundUri = Lib.resourceToUri(R.raw.siren);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_launcher).setContentTitle(title).setContentText(msg)
                    .setAutoCancel(true).setSound(defaultSoundUri).setContentIntent(pendingIntent);

            Notification mNotification = notificationBuilder.build();
            mNotification.flags |= Notification.FLAG_INSISTENT;

            NotificationManager notificationManager = (NotificationManager) getSystemService(
                    Context.NOTIFICATION_SERVICE);

            notificationManager.notify(0, mNotification);

        } else {
            Log.e(TAG, "site uuid " + siteUUID + " not found");
        }

        break;

    // crea una notifica informativa
    case "info":

        // qui creare la notifica
        // ...

        break;

    }

    // dopo la notifica sveglia il device
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = pm.newWakeLock(
            (PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), getClass().getSimpleName());
    wakeLock.acquire();

}

From source file:com.lan.nicehair.common.download.DownloadThread.java

/**
 * Executes the download in a separate thread
 */// w w  w .j  a v a  2  s.  com
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, TAG);
        wakeLock.acquire();

        AppLog.d(TAG, "initiating download for " + mInfo.mUri);

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

        boolean finished = false;
        while (!finished) {

            AppLog.d(TAG, "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;
            }
        }

        AppLog.d(TAG, "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
        AppLog.e(TAG, "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
        AppLog.e(TAG, "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:csic.ceab.movelab.beepath.FixGet.java

/**
 * Creates a new FixGet service instance.<br>
 * Begins location recording process. Creates a location manager and two
 * location listeners. Begins requesting updates from both the GPS and
 * network services, with one location listener receiving updates from one
 * provider.//from ww w . j a v  a  2s  .  c om
 * <p>
 * If either provider is unavailable, no updates will ever be returned to
 * the corresponding location listener.
 */

@Override
public void onCreate() {

    Context context = getApplicationContext();

    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    wifiLock = ((WifiManager) context.getSystemService(Context.WIFI_SERVICE)).createWifiLock(
            WifiManager.WIFI_MODE_SCAN_ONLY,
            context.getResources().getString(R.string.internal_message_id) + "WifiLock");

    wakeLock = ((PowerManager) context.getSystemService(Context.POWER_SERVICE)).newWakeLock(
            PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
            context.getResources().getString(R.string.internal_message_id) + "ScreenDimWakeLock");

    minDist = Util.getMinDist(context);

}

From source file:com.oo58.game.texaspoker.AppActivity.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //         this.getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED, FLAG_HOMEKEY_DISPATCHED);//
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    mContext = AppActivity.this;

    try {/*from   w  w w.  j  a va2  s.com*/
        ApplicationInfo appInfo = this.getPackageManager().getApplicationInfo(getPackageName(),
                PackageManager.GET_META_DATA);
        String msg = appInfo.metaData.getString("data_Name");

        //         int channelid = Integer.parseInt(msg) ;
        //         
        //         System.out.println(channelid);

    } catch (NameNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    mAct = this;
    allContext = this.getApplicationContext();
    mTencent = Tencent.createInstance("1104823392", getApplicationContext());
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "MyLock");
    mWakeLock.acquire();

    MobclickAgent.setDebugMode(false);
    MobclickAgent.updateOnlineConfig(this);
    AnalyticsConfig.enableEncrypt(true);

    checkUpdate();

    PackageManager pm2 = getPackageManager();
    homeInfo = pm2.resolveActivity(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME), 0);

    mNetChecker.initAndRegListener(mContext);

    mWXPay.init(this);

    MobClickCppHelper.init(this);

    //      // logcatdebug
    //       XGPushConfig.enableDebug(this, true);
    //      // registerPush(getApplicationContext(), XGIOperateCallback)callback
    //      // registerPush(getApplicationContext(),account)
    //      // 
    //      // ApplicationContext
    //      Context context = getApplicationContext();
    //      XGPushManager.registerPush(context);    
    //       
    //      // 2.362
    //      Intent service = new Intent(context, XGPushService.class);
    //      context.startService(service);

    // API
    // registerPush(context,account)registerPush(context,account, XGIOperateCallback)accountAPPqqopenid
    // registerPush(context,"*")account="*"
    // unregisterPush(context)
    // setTag(context, tagName)
    // deleteTag(context, tagName)

    updateListViewReceiver = new MsgReceiver();
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("com.oo58.game.texaspoker.activity.UPDATE_LISTVIEW");
    registerReceiver(updateListViewReceiver, intentFilter);

    XGPushManager.registerPush(getApplicationContext(), new XGIOperateCallback() {
        @Override
        public void onSuccess(Object data, int flag) {
            //                  Log.w(Constants.LogTag,
            //                        "+++ register push sucess. token:" + data);

        }

        @Override
        public void onFail(Object data, int errCode, String msg) {
            //                  Log.w(Constants.LogTag,
            //                        "+++ register push fail. token:" + data
            //                              + ", errCode:" + errCode + ",msg:"
            //                              + msg);

        }
    });

    //javajosnC++demo
    /*      JSONObject jsonObj = new JSONObject();  
            try {
             jsonObj.put("Int_att",25);
               jsonObj.put("String_att","str");//string  
               jsonObj.put("Double_att",12.25);//double  
               jsonObj.put("Boolean_att",true);//boolean  
          } catch (JSONException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
          }//int  
            
            PushJson(jsonObj.toString()) ;*/

}

From source file:cn.keyshare.download.core.DownloadThread.java

/**
  * Executes the download in a separate thread
  *///  w w w.  j a  v a 2  s. c o 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:cc.softwarefactory.lokki.android.androidServices.LocationService.java

@Override
public void onCreate() {

    Log.d(TAG, "onCreate");
    super.onCreate();

    if (PreferenceUtils.getString(this, PreferenceUtils.KEY_AUTH_TOKEN).isEmpty()) {
        Log.d(TAG, "User disabled reporting in App. Service not started.");
        stopSelf();/*from   www.j av  a  2s. c o m*/
    } else if (Utils.checkGooglePlayServices(this)) {
        Log.d(TAG, "Starting Service..");
        setLocationClient();
        setNotificationAndForeground();
        PowerManager mgr = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
        wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "GPS Child Location Wake Lock");
        wakeLock.acquire();
        serviceRunning = true;
    } else {
        Log.e(TAG, "Google Play Services Are NOT installed.");
        stopSelf();
    }
}

From source file:cm.aptoide.pt.Aptoide.java

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    keepScreenOn = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,
            "Full Power");
    DownloadQueueServiceIntent = new Intent(getApplicationContext(), DownloadQueueService.class);
    startService(DownloadQueueServiceIntent);

    //@dsilveira  #534 +10lines Check if Aptoide is already running to avoid wasting time and showing the splash
    ActivityManager activityManager = (ActivityManager) getApplicationContext()
            .getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> running = activityManager.getRunningTasks(Integer.MAX_VALUE);
    for (RunningTaskInfo runningTask : running) {
        if (runningTask.baseActivity.getClassName().equals("cm.aptoide.pt.RemoteInTab")) { //RemoteInTab is the real Aptoide Activity
            Message msg = new Message();
            msg.what = LOAD_TABS;/*ww w  .  j  ava  2s  .c  om*/
            startHandler.sendMessage(msg);
            return;
        }
    }

    Log.d("Aptoide", "******* \n Downloads will be made to: "
            + Environment.getExternalStorageDirectory().getPath() + "\n ********");

    sPref = getSharedPreferences("aptoide_prefs", MODE_PRIVATE);
    prefEdit = sPref.edit();

    db = new DbHandler(this);

    PackageManager mPm = getPackageManager();
    try {
        pkginfo = mPm.getPackageInfo("cm.aptoide.pt", 0);
    } catch (NameNotFoundException e) {
    }

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    try {
        if (pkginfo.versionCode < Integer.parseInt(getXmlElement("versionCode"))) {
            Log.d("Aptoide-VersionCode", "Using version " + pkginfo.versionCode + ", suggest update!");
            requestUpdateSelf();
        } else {
            proceed();
        }
    } catch (Exception e) {
        e.printStackTrace();
        proceed();
    }

}

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 ww . java  2s.  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);

}