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.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//from   w w w . jav  a  2  s  . co m
 * @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// w w w .j  a  v a2  s  .  c  o m
 */
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:se.hockersten.timed.vibration.main.CompetitionTab.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    PowerManager pm = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "CompetitionTab.onCreateView()");
    if (savedInstanceState != null) {
        competing = savedInstanceState.getBoolean(COMPETING);
        visible = savedInstanceState.getBoolean(VISIBLE);
        lastPress = (Calendar) savedInstanceState.getSerializable(LAST_PRESS);
    }//from ww  w . j ava  2  s . c o  m

    root = inflater.inflate(R.layout.main_competition, container, false);
    return root;
}

From source file:com.almarsoft.GroundhogReader.lib.MessagePosterLib.java

public MessagePosterLib(String currentGroup, String groups, String body, String subject, String references,
        String prevMsgId, Context context) {

    mCurrentGroup = currentGroup;//w  w  w .j av  a  2s  .  com
    mContext = context;
    mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
    mGroups = groups.trim();
    mBody = body;
    mSubject = subject.trim();
    mPostCharset = mPrefs.getString("postCharset", "ISO8859_15");
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,
            "GroundhogSending");

    // Reply to non-first post in a thread
    if (references != null && references.length() > 0)
        mReferences = references.trim();
    else
        mReferences = null;

    // Reply to a thread
    if (prevMsgId != null && prevMsgId.length() > 0)
        mPrevMsgId = prevMsgId.trim();
    else
        mPrevMsgId = null; // Message starting new thread

    // Reply to the first post in thread
    if (mReferences == null && mPrevMsgId != null) {
        mReferences = mPrevMsgId;
    }

}

From source file:edu.cens.loci.sensors.AccelerometerHandler.java

private PowerManager cpu() {
    return (PowerManager) mCxt.getSystemService(Context.POWER_SERVICE);
}

From source file:com.easemob.helpdeskdemo.ui.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        String packageName = getPackageName();
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (!pm.isIgnoringBatteryOptimizations(packageName)) {
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + packageName));
            startActivity(intent);/*from   w w w.ja va2 s.c o  m*/
        }
    }

    setContentView(R.layout.em_activity_main);
    if (savedInstanceState != null) {
        currentTabIndex = savedInstanceState.getInt("selectedIndex", 0);
    }
    if (shopFragment != null) {
        shopFragment = getSupportFragmentManager().findFragmentByTag(shopFragment.getClass().getName());
        settingFragment = getSupportFragmentManager().findFragmentByTag(settingFragment.getClass().getName());
        ticketListFragment = getSupportFragmentManager()
                .findFragmentByTag(ticketListFragment.getClass().getName());
        fragments = new Fragment[] { shopFragment, ticketListFragment, settingFragment };
        getSupportFragmentManager().beginTransaction().hide(shopFragment).hide(settingFragment)
                .hide(ticketListFragment).show(fragments[currentTabIndex]).commit();

    } else {
        shopFragment = new ShopFragment();
        settingFragment = new SettingFragment();
        ticketListFragment = new TicketListFragment();
        fragments = new Fragment[] { shopFragment, ticketListFragment, settingFragment };
        // shopFragment?
        FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
        trx.add(R.id.fragment_container, shopFragment, shopFragment.getClass().getName())
                .add(R.id.fragment_container, ticketListFragment, ticketListFragment.getClass().getName())
                .add(R.id.fragment_container, settingFragment, settingFragment.getClass().getName())
                .hide(settingFragment).hide(ticketListFragment).hide(shopFragment)
                .show(fragments[currentTabIndex]);
        trx.commit();
    }
    mBottomNav = $(R.id.bottom_navigation);
    mBottomNav.setBottomNavigationSelectedListener(this);
    //??listener
    connectionListener = new MyConnectionListener();
    ChatClient.getInstance().addConnectionListener(connectionListener);
    //6.0????target api?23demo??????
    requestPermissions();
}

From source file:org.elliotglaysher.lifecounter.LifeCounter.java

/** Called when the activity is first created. */
@Override/*from  w  w  w. ja v a 2  s .  co m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    setupLayouts();

    if (savedInstanceState != null) {
        restoreModelsFromBundle(savedInstanceState);
    }

    // Prevent the screen from totally going to sleep...
    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");

    newGame();
}

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();/* w w  w .j a  va2s  . c o  m*/

    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.haarman.pebblenotifier.pebble.PebbleNotifier.java

private boolean shouldNotify(@NotNull final App app) {
    if (app.isMuted()) {
        return false;
    }/*from  w  ww  . ja  v a 2s  .  c  o m*/

    PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
    if (powerManager.isScreenOn() && !mPreferences.shouldSendWhenScreenOn()) {
        return false;
    }

    if (app.getLastNotified().plusMillis(IGNORE_INTERVAL_MILLIS).isAfterNow()) {
        return !mPreferences.shouldIgnoreMultipleNotifications();
    }

    return true;
}

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();/*w w w .  ja v a  2 s  .c  om*/

    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();
}