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.goftagram.telegram.messenger.NotificationsController.java

public NotificationsController() {
    notificationManager = NotificationManagerCompat.from(ApplicationLoader.applicationContext);
    SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications",
            Context.MODE_PRIVATE);
    inChatSoundEnabled = preferences.getBoolean("EnableInChatSound", true);

    try {//from  ww  w. j a v  a  2  s.  c om
        audioManager = (AudioManager) ApplicationLoader.applicationContext
                .getSystemService(Context.AUDIO_SERVICE);
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
    try {
        alarmManager = (AlarmManager) ApplicationLoader.applicationContext
                .getSystemService(Context.ALARM_SERVICE);
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }

    try {
        PowerManager pm = (PowerManager) ApplicationLoader.applicationContext
                .getSystemService(Context.POWER_SERVICE);
        notificationDelayWakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "lock");
        notificationDelayWakelock.setReferenceCounted(false);
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }

    notificationDelayRunnable = new Runnable() {
        @Override
        public void run() {
            FileLog.e("tmessages", "delay reached");
            if (!delayedPushMessages.isEmpty()) {
                showOrUpdateNotification(true);
                delayedPushMessages.clear();
            }
            try {
                if (notificationDelayWakelock.isHeld()) {
                    notificationDelayWakelock.release();
                }
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
        }
    };
}

From source file:com.spoiledmilk.ibikecph.map.MapFragmentBase.java

@Override
public void onResume() {
    super.onResume();
    LOG.d("MapFragmentBase onResume");
    this.locationOverlay.enableMyLocation(this.locationOverlay.getMyLocationProvider());
    SMLocationManager locManager = SMLocationManager.getInstance();
    locManager.init(getActivity(), this);
    if (locManager.hasValidLocation()) {
        refreshMapTileSource(locManager.getLastValidLocation());
    } else {// w  w  w. j  a va 2  s. c o m
        mapView.setTileSource(TileSourceFactory.getTileSource(TileSourceFactory.IBIKECPH.name()));
    }
    if (!SMLocationManager.getInstance().isGPSEnabled()) {
        launchGPSDialog();
    }
    ScaledTilesOverlay scaledTilesOverlay = new ScaledTilesOverlay(mapView.getTileProvider(), getActivity());
    mapView.getOverlayManager().setScaledTilesOverlay(scaledTilesOverlay);
    PowerManager powerManager = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
    boolean isScreenOn = powerManager.isScreenOn();
    if (isReturnFromLock && isScreenOn) {
        isReturnFromLock = false;
        if (mapView.tracking) {
            Location loc = SMLocationManager.getInstance().hasValidLocation()
                    ? SMLocationManager.getInstance().getLastValidLocation()
                    : SMLocationManager.getInstance().getLastKnownLocation();
            if (loc != null) {
                onLocationChanged(loc);
            }
        } else {
            mapView.scrollTo(lastScrollX, lastScrollY);
        }
    }

}

From source file:org.simlar.SimlarService.java

@Override
public void onCreate() {
    Log.i(LOGTAG, "started on device: " + Build.DEVICE);

    FileHelper.init(this);
    mVibratorThread = new VibratorThread(this.getApplicationContext());
    mRingtoneThread = new RingtoneThread(this.getApplicationContext());

    mWakeLock = ((PowerManager) this.getSystemService(Context.POWER_SERVICE))
            .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "SimlarWakeLock");
    mWifiLock = ((WifiManager) this.getSystemService(Context.WIFI_SERVICE))
            .createWifiLock(WifiManager.WIFI_MODE_FULL, "SimlarWifiLock");

    startForeground(NOTIFICATION_ID, createNotification(SimlarStatus.OFFLINE));

    mLinphoneThread = new LinphoneThread(this, this);

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(mNetworkChangeReceiver, intentFilter);

    startKeepAwake();/*from  w  ww  .  j  a  v a 2  s .c  o  m*/

    mHandler.post(new Runnable() {
        @Override
        public void run() {
            initializeCredentials();
        }
    });
}

From source file:com.intel.RtcPingDownloadTester.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    /** First, call the superclass onCreate method */
    super.onCreate(savedInstanceState);

    Log.v(TAG, "onCreate: " + savedInstanceState);

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "RtcPingDownloadTester");
    nWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "RtcPingDownloadTester2");
    setContentView(R.layout.main);//from w  w w.j a  v a 2  s  . co m

    b_Start = (Button) this.findViewById(R.id.ok);
    b_Start.setOnClickListener(new OnClickListener() {
        /* Start button pressed handler.*/
        public void onClick(View v) {
            Log.v(TAG, "onClick : START");

            /* a bit of sanity checking..*/
            if (nRepeatTimerEntry < 0)
                nRepeatTimerEntry = 0;
            else if (nRepeatTimerEntry > 600)
                nRepeatTimerEntry = 600;

            /* Entry point for alarm task */
            if ((nRepeatTimerEntry != 0) && (is_running == false)) {
                is_running = true;
                string_curr_state = "RUNNING";
                label_curr_state.setText(string_curr_state);
                registerReceiver(alarmReceiver, myFilter);
                new setAlarmTask().execute(nRepeatTimerEntry * 1000);
            }
        }
    });

    b_Stop = (Button) this.findViewById(R.id.stop);
    b_Stop.setOnClickListener(new OnClickListener() {
        /* Stop button pressed handler*/
        public void onClick(View v) {
            Log.v(TAG, "onClick : STOP");
            if (is_running) {
                unregisterReceiver(alarmReceiver);
                is_running = false;
                string_curr_state = "STOPED";
                label_curr_state.setText(string_curr_state);
                clearAlarm();
            }
        }
    });

    label_curr_state = (TextView) this.findViewById(R.id.label_curr_state);
    label_curr_state.setText(string_curr_state);

    label_console_box = (TextView) this.findViewById(R.id.label_console_box);
    label_console_box.setText(string_console_text);

    textBox_TimerEntry = (EditText) this.findViewById(R.id.textBox_1);
    textBox_TimerEntry.setText(String.valueOf(nRepeatTimerEntry), TextView.BufferType.EDITABLE);
    textBox_TimerEntry.addTextChangedListener(textBox_TimerEntry_EditorWatcher);

    textBox_HostIp = (EditText) this.findViewById(R.id.textBox_2);
    textBox_HostIp.setText(host_ip_addr, TextView.BufferType.EDITABLE);
    textBox_HostIp.addTextChangedListener(textBox_HostIp_EditorWatcher);

    textBox_fileUrl = (EditText) this.findViewById(R.id.textBox_3);
    textBox_fileUrl.setText(fileUrl, TextView.BufferType.EDITABLE);
    textBox_fileUrl.addTextChangedListener(textBox_fileUrl_EditorWatcher);

    textBox_wklk = (EditText) this.findViewById(R.id.textBox_4);
    textBox_wklk.setText(String.valueOf(wklk), TextView.BufferType.EDITABLE);
    textBox_wklk.addTextChangedListener(textBox_wklk_EditorWatcher);

    checkBox_1 = (CheckBox) this.findViewById(R.id.checkBox_1);
    checkBox_1.setChecked(ping_enabled);
    checkBox_1.setOnClickListener(new OnClickListener() {
        /* Ping checkbox handler */
        public void onClick(View v) {
            if (((CheckBox) v).isChecked())
                ping_enabled = true;
            else
                ping_enabled = false;
        }
    });

    checkBox_2 = (CheckBox) this.findViewById(R.id.checkBox_2);
    checkBox_2.setChecked(download_enabled);
    checkBox_2.setOnClickListener(new OnClickListener() {
        /* Download checkbox handler */
        public void onClick(View v) {
            if (((CheckBox) v).isChecked())
                download_enabled = true;
            else
                download_enabled = false;
        }
    });

    checkBox_3 = (CheckBox) this.findViewById(R.id.checkBox_3);
    checkBox_3.setChecked(wklk_enabled);
    checkBox_3.setOnClickListener(new OnClickListener() {
        /* Download checkbox handler */
        public void onClick(View v) {
            if (((CheckBox) v).isChecked())
                wklk_enabled = true;
            else
                wklk_enabled = false;
        }
    });

}

From source file:com.etime.TimeAlarmService.java

/**
 * Acquires the wake lock to keep the phone awake while the auto clocks out the user.
 * @return the wake lock.//from   w  ww  . jav a2  s. c  o  m
 */
synchronized static PowerManager.WakeLock getLock() {
    if (lockStatic == null && lockContext != null) {
        PowerManager mgr = (PowerManager) lockContext.getSystemService(Context.POWER_SERVICE);

        lockStatic = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, NAME);
        lockStatic.setReferenceCounted(true);
    }

    return (lockStatic);
}

From source file:com.automated.taxinow.GCMIntentService.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *//*ww w . j  av  a2s  . c  o m*/
private void generateNotification(Context context, String message) {
    // System.out.println("this is message " + message);
    // System.out.println("NOTIFICATION RECEIVED!!!!!!!!!!!!!!" + message);
    int icon = R.drawable.ic_launcher;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);
    String title = context.getString(R.string.app_name);
    Intent notificationIntent = new Intent(context, MainDrawerActivity.class);
    notificationIntent.putExtra("fromNotification", "notification");
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    System.out.println("notification====>" + message);
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    // notification.defaults |= Notification.DEFAULT_LIGHTS;
    notification.flags |= Notification.FLAG_SHOW_LIGHTS;
    notification.ledARGB = 0x00000000;
    notification.ledOnMS = 0;
    notification.ledOffMS = 0;
    notificationManager.notify(0, notification);
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = pm.newWakeLock(
            PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE,
            "WakeLock");
    wakeLock.acquire();
    wakeLock.release();
}

From source file:com.b44t.messenger.NotificationsController.java

public NotificationsController() {
    mContext = ApplicationLoader.applicationContext;
    notificationManager = NotificationManagerCompat.from(ApplicationLoader.applicationContext);
    SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications",
            Context.MODE_PRIVATE);
    inChatSoundEnabled = preferences.getBoolean("EnableInChatSound", true);

    try {//from  w  ww.ja v a 2s. c  om
        audioManager = (AudioManager) ApplicationLoader.applicationContext
                .getSystemService(Context.AUDIO_SERVICE);
    } catch (Exception e) {
        FileLog.e("messenger", e);
    }
    try {
        alarmManager = (AlarmManager) ApplicationLoader.applicationContext
                .getSystemService(Context.ALARM_SERVICE);
    } catch (Exception e) {
        FileLog.e("messenger", e);
    }

    try {
        PowerManager pm = (PowerManager) ApplicationLoader.applicationContext
                .getSystemService(Context.POWER_SERVICE);
        notificationDelayWakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "lock");
        notificationDelayWakelock.setReferenceCounted(false);
    } catch (Exception e) {
        FileLog.e("messenger", e);
    }

    notificationDelayRunnable = new Runnable() {
        @Override
        public void run() {
            FileLog.e("messenger", "delay reached");
            if (!delayedPushMessages.isEmpty()) {
                showOrUpdateNotification(true);
                delayedPushMessages.clear();
            }
            try {
                if (notificationDelayWakelock.isHeld()) {
                    notificationDelayWakelock.release();
                }
            } catch (Exception e) {
                FileLog.e("messenger", e);
            }
        }
    };
}

From source file:com.mowares.massagerexpressclient.GCMIntentService.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *///from   ww  w.j a  v a 2  s.  c o  m

private void generateNotification(Context context, String message) {
    // System.out.println("this is message " + message);
    // System.out.println("NOTIFICATION RECEIVED!!!!!!!!!!!!!!" + message);
    int icon = R.drawable.ic_launcher;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);
    String title = context.getString(R.string.app_name);
    Intent notificationIntent = new Intent(context, MainDrawerActivity.class);
    notificationIntent.putExtra("fromNotification", "notification");
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    //notification.setLatestEventInfo(context, title, message, intent);

    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    System.out.println("notification====>" + message);
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    // notification.defaults |= Notification.DEFAULT_LIGHTS;
    notification.flags |= Notification.FLAG_SHOW_LIGHTS;
    notification.ledARGB = 0x00000000;
    notification.ledOnMS = 0;
    notification.ledOffMS = 0;
    notificationManager.notify(0, notification);
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = pm.newWakeLock(
            PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE,
            "WakeLock");
    wakeLock.acquire();
    wakeLock.release();
}

From source file:com.ti.sensortag.gui.services.ServicesActivity.java

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

    pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakelockk = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock");
    setContentView(R.layout.services_browser);

    //for checking signal strength..
    MyListener = new MyPhoneStateListener();
    Tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    Tel.listen(MyListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
    //ends../*from w  ww .  j  a  v a2  s .co m*/

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    test_1 = getIntent().getStringExtra("TEST");
    Toast.makeText(getBaseContext(), "ARV in services SA :" + test_1, Toast.LENGTH_SHORT).show();

    /* sendbutton = (Button) findViewById(R.id.button1);
    sendbutton.setOnClickListener(new OnClickListener() {
              
      @Override
      public void onClick(View v) {
         // TODO Auto-generated method stub
         String sensorid = test_1;
         String sensortype = "temperature";
         BufferedReader br = null;
                  
         try {
            
    String sCurrentLine;
            
    File ext = Environment.getExternalStorageDirectory();
    File myFile = new File(ext, "mysdfile_25.txt");
            
    br = new BufferedReader(new FileReader(myFile));
            
    while ((sCurrentLine = br.readLine()) != null) {
       String[] numberSplit = sCurrentLine.split(":") ; 
       String time = numberSplit[ (numberSplit.length-2) ] ;
       String val = numberSplit[ (numberSplit.length-1) ] ;
       //System.out.println(sCurrentLine);
       HttpResponse httpresponse;
       //int responsecode;
       StatusLine responsecode;
       String strresp;
               
       HttpClient httpclient = new DefaultHttpClient();
       HttpPost httppost = new HttpPost("https://rnicu-cloud.appspot.com/sensor/update");
               
       try{
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
           nameValuePairs.add(new BasicNameValuePair("sensorid", sensorid));
           nameValuePairs.add(new BasicNameValuePair("sensortype", sensortype));
           nameValuePairs.add(new BasicNameValuePair("time", time));
           nameValuePairs.add(new BasicNameValuePair("val", val));
         //  try {
          httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    //      try {
             httpresponse = httpclient.execute(httppost);
             //responsecode = httpresponse.getStatusLine().getStatusCode();
             responsecode = httpresponse.getStatusLine();
             strresp = responsecode.toString();
             Log.d("ARV Response msg from post", httpresponse.toString());
             Log.d("ARV status of post", strresp);
             HttpEntity httpentity = httpresponse.getEntity();
             Log.d("ARV entity string", EntityUtils.toString(httpentity));
          //   Log.d("ARV oly entity", httpentity.toString());
          //   Log.d("ARV Entity response", httpentity.getContent().toString());
             //httpclient.execute(httppost);
             Toast.makeText(getApplicationContext(), "Posted data and returned value:"+ strresp, Toast.LENGTH_LONG).show();
    //      } catch (ClientProtocolException e) {
             // TODO Auto-generated catch block
    //         e.printStackTrace();
    //      } catch (IOException e) {
             // TODO Auto-generated catch block
    //         e.printStackTrace();
    //      }
    //   } 
       }catch (ClientProtocolException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
       }catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
       }
    }
            
         } catch (IOException e) {
    e.printStackTrace();
         } finally {
    try {
       if (br != null)br.close();
    } catch (IOException ex) {
       ex.printStackTrace();
    }
         }
                 
                 
      //   Toast.makeText(getApplicationContext(), "Entered on click", Toast.LENGTH_SHORT).show();
                 
                 
         /*catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
         }   
      }
    });*/

    getActionBar().setDisplayHomeAsUpEnabled(true);
}

From source file:com.fairphone.fplauncher3.Folder.java

/**
 * Used to inflate the Workspace from XML.
 *
 * @param context The application's context.
 * @param attrs The attribtues set containing the Workspace's customization values.
 *///from   ww  w.  ja v  a2s. c  o  m
public Folder(Context context, AttributeSet attrs) {
    super(context, attrs);

    mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);

    LauncherAppState app = LauncherAppState.getInstance();
    DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
    setAlwaysDrawnWithCacheEnabled(false);
    mInflater = LayoutInflater.from(context);
    mIconCache = app.getIconCache();

    Resources res = getResources();
    mMaxCountX = (int) grid.numColumns;
    // Allow scrolling folders when DISABLE_ALL_APPS is true.
    if (LauncherAppState.isDisableAllApps()) {
        mMaxCountY = mMaxNumItems = Integer.MAX_VALUE;
    } else {
        mMaxCountY = (int) grid.numRows;
        mMaxNumItems = mMaxCountX * mMaxCountY;
    }

    mInputMethodManager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);

    mExpandDuration = res.getInteger(R.integer.config_folderExpandDuration);
    mMaterialExpandDuration = res.getInteger(R.integer.config_materialFolderExpandDuration);
    mMaterialExpandStagger = res.getInteger(R.integer.config_materialFolderExpandStagger);

    if (sDefaultFolderName == null) {
        sDefaultFolderName = res.getString(R.string.folder_name);
    }
    if (sHintText == null) {
        sHintText = res.getString(R.string.folder_hint_text);
    }
    mLauncher = (Launcher) context;
    // We need this view to be focusable in touch mode so that when text editing of the folder
    // name is complete, we have something to focus on, thus hiding the cursor and giving
    // reliable behvior when clicking the text field (since it will always gain focus on click).
    setFocusableInTouchMode(true);
}