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:net.oddsoftware.android.feedscribe.data.Downloader.java

private Downloader(Context ctx) {
    mContext = ctx;//from  www  .  j a v  a  2 s  .c  om

    mThreadPool = Executors.newFixedThreadPool(4);

    mFeedManager = FeedManager.getInstance(mContext);

    mDownloadCount = 0;

    mWakeLock = ((PowerManager) ctx.getSystemService(Context.POWER_SERVICE))
            .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "FeedScribe.Downloader");
    mWakeLock.setReferenceCounted(false);

    mAwakeChecker = new Thread() {
        @Override
        public void run() {
            try {
                while (true) {
                    Thread.sleep(mAwakeInterval);
                    checkAwake();
                }
            } catch (InterruptedException exc) {
                return;
            }
        }
    };

    mAwakeChecker.start();
}

From source file:it.baywaylabs.jumpersumo.utility.FTPDownloadImage.java

/**
 * Method auto invoked pre execute the task.<br />
 *///from   ww  w .j  a  v a  2s.  c  o 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();
}

From source file:com.mendhak.gpslogger.common.Systems.java

/**
 * Returns true if the device is in Doze/Idle mode. Should be called before checking the network connection because
 * the ConnectionManager may report the device is connected when it isn't during Idle mode.
 * https://github.com/yigit/android-priority-jobqueue/blob/master/jobqueue/src/main/java/com/path/android/jobqueue/network/NetworkUtilImpl.java#L60
 *//*w ww  .ja  v  a 2  s  .com*/
@TargetApi(23)
public static boolean isDozing(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        return powerManager.isDeviceIdleMode()
                && !powerManager.isIgnoringBatteryOptimizations(context.getPackageName());
    } else {
        return false;
    }
}

From source file:com.dattasmoon.pebble.plugin.FireReceiver.java

@Override
public void onReceive(final Context context, final Intent intent) {
    if (com.twofortyfouram.locale.Intent.ACTION_FIRE_SETTING.equals(intent.getAction())) {
        // fetch this for later, we may need it in case we change things
        // around and we need to know what version of the code they were
        // running when they saved the action
        int bundleVersionCode = intent.getIntExtra(Constants.BUNDLE_EXTRA_INT_VERSION_CODE, 1);

        Type type = Type.values()[intent.getIntExtra(Constants.BUNDLE_EXTRA_INT_TYPE,
                Type.NOTIFICATION.ordinal())];
        PowerManager pm;/*from   www.j a v a2 s  .c  o  m*/
        switch (type) {
        case NOTIFICATION:
            SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);

            // handle screen DND
            boolean notifScreenOn = sharedPref.getBoolean(Constants.PREFERENCE_NOTIF_SCREEN_ON, true);
            pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            if (Constants.IS_LOGGABLE) {
                Log.d(Constants.LOG_TAG, "FireReceiver.onReceive: notifScreenOn=" + notifScreenOn + "  screen="
                        + pm.isScreenOn());
            }
            if (!notifScreenOn && pm.isScreenOn()) {
                break;
            }

            //handle quiet hours DND
            boolean quiet_hours = sharedPref.getBoolean(Constants.PREFERENCE_QUIET_HOURS, false);
            //we only need to pull this if quiet hours are enabled. Save the cycles for the cpu! (haha)
            if (quiet_hours) {
                String[] pieces = sharedPref.getString(Constants.PREFERENCE_QUIET_HOURS_BEFORE, "00:00")
                        .split(":");
                Date quiet_hours_before = new Date(0, 0, 0, Integer.parseInt(pieces[0]),
                        Integer.parseInt(pieces[1]));
                pieces = sharedPref.getString(Constants.PREFERENCE_QUIET_HOURS_AFTER, "23:59").split(":");
                Date quiet_hours_after = new Date(0, 0, 0, Integer.parseInt(pieces[0]),
                        Integer.parseInt(pieces[1]));
                Calendar c = Calendar.getInstance();
                Date now = new Date(0, 0, 0, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE));
                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG, "Checking quiet hours. Now: " + now.toString() + " vs "
                            + quiet_hours_before.toString() + " and " + quiet_hours_after.toString());
                }
                if (now.before(quiet_hours_before) || now.after(quiet_hours_after)) {
                    if (Constants.IS_LOGGABLE) {
                        Log.i(Constants.LOG_TAG, "Time is before or after the quiet hours time. Returning.");
                    }
                    break;
                }
            }

            String title = intent.getStringExtra(Constants.BUNDLE_EXTRA_STRING_TITLE);
            String body = intent.getStringExtra(Constants.BUNDLE_EXTRA_STRING_BODY);

            sendAlertToPebble(context, bundleVersionCode, title, body);
            break;
        case SETTINGS:
            Mode mode = Mode.values()[intent.getIntExtra(Constants.BUNDLE_EXTRA_INT_MODE, Mode.OFF.ordinal())];
            String packageList = intent.getStringExtra(Constants.BUNDLE_EXTRA_STRING_PACKAGE_LIST);

            setNotificationSettings(context, bundleVersionCode, mode, packageList);
            break;
        }
    }
}

From source file:net.olejon.spotcommander.AddComputerActivity.java

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

    // Power manager
    final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

    //noinspection deprecation
    mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "wakeLock");

    // Allow landscape?
    if (!mTools.allowLandscape())
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    // Layout// www. j a v a  2 s .  co m
    setContentView(R.layout.activity_add_computer);

    // Toolbar
    final Toolbar toolbar = (Toolbar) findViewById(R.id.add_computer_toolbar);
    toolbar.setTitleTextColor(ContextCompat.getColor(mContext, R.color.white));

    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    mAddComputerNameInputLayout = (TextInputLayout) findViewById(R.id.add_computer_text_input_name_layout);
    mAddComputerUriInputLayout = (TextInputLayout) findViewById(R.id.add_computer_text_input_uri_layout);
    mAddComputerNameInputLayout.setHintAnimationEnabled(true);
    mAddComputerUriInputLayout.setHintAnimationEnabled(true);

    // Progress bar
    mProgressBar = (ProgressBar) findViewById(R.id.add_computer_progressbar);

    // Information
    final TextView textView = (TextView) findViewById(R.id.add_computer_information);
    textView.setMovementMethod(LinkMovementMethod.getInstance());

    // Scan dialog
    new MaterialDialog.Builder(mContext).title(R.string.add_computer_scan_dialog_title)
            .content(getString(R.string.add_computer_scan_dialog_message))
            .positiveText(R.string.add_computer_scan_dialog_positive_button)
            .negativeText(R.string.add_computer_scan_dialog_negative_button)
            .onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog materialDialog,
                        @NonNull DialogAction dialogAction) {
                    scanNetwork();
                }
            }).contentColorRes(R.color.black).negativeColorRes(R.color.black).show();
}

From source file:net.pmarks.chromadoze.NoiseService.java

@Override
public void onCreate() {
    // Set up a message handler in the main thread.
    mPercentHandler = new PercentHandler();
    AudioParams params = new AudioParams();
    mSampleShuffler = new SampleShuffler(params);
    mSampleGenerator = new SampleGenerator(this, params, mSampleShuffler);
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ChromaDoze Wake Lock");
    mWakeLock.acquire();//from   w  w  w  .j  av a  2s.c o m

    startForeground(NOTIFY_ID, makeNotify());

    // Note: This leaks memory if I use "this" instead of "getApplicationContext()".
    mAudioFocusHelper = new AudioFocusHelper(getApplicationContext(), mSampleShuffler.getVolumeListener());
}

From source file:singh.amandeep.musicplayer.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, "Eleven headset button");
        mWakeLock.setReferenceCounted(false);
    }//  ww  w . j  av  a  2  s. c  o m
    // Make sure we don't indefinitely hold the wake lock under any circumstances
    mWakeLock.acquire(10000);

    mHandler.sendMessageDelayed(msg, delay);
}

From source file:ws.logv.trainmonitor.GCMIntentService.java

@Override
protected void onMessage(final Context context, Intent intent) {

    if (intent.hasExtra("command")) {
        String command = intent.getStringExtra("command");

        if ("sync".equals(command)) {
            String type = intent.getStringExtra("type");

            if ("subscription".equals(type)) {
                Workflow.getEventBus(context).post(new PullSubscriptionsEvent());
            }//  w  w  w . j a v a2  s  .c  o m
        }

    } else {
        String train = intent.getStringExtra("train");
        if (wl == null) {
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Refresh trains");
        }

        wl.acquire(2000);
        EventBus bus = Workflow.getEventBus(context);
        bus.register(this, FetchTrainDetailsResult.class);
        bus.post(new FetchTrainDetailsCommand(train));
    }
}

From source file:de.schildbach.wallet.offline.AcceptBluetoothService.java

@Override
public void onCreate() {
    serviceCreatedAt = System.currentTimeMillis();
    log.debug(".onCreate()");

    super.onCreate();
    this.application = (WalletApplication) getApplication();
    final BluetoothAdapter bluetoothAdapter = checkNotNull(BluetoothAdapter.getDefaultAdapter());
    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);

    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
    wakeLock.acquire();//from ww  w . ja  v  a  2 s  .  c  om

    registerReceiver(bluetoothStateChangeReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));

    try {
        classicThread = new AcceptBluetoothThread.ClassicBluetoothThread(bluetoothAdapter) {
            @Override
            public boolean handleTx(final Transaction tx) {
                return AcceptBluetoothService.this.handleTx(tx);
            }
        };
        paymentProtocolThread = new AcceptBluetoothThread.PaymentProtocolThread(bluetoothAdapter) {
            @Override
            public boolean handleTx(final Transaction tx) {
                return AcceptBluetoothService.this.handleTx(tx);
            }
        };
    } catch (final IOException x) {
        new Toast(this).longToast(R.string.error_bluetooth, x.getMessage());
        log.warn("problem with listening, stopping service", x);
        CrashReporter.saveBackgroundTrace(x, application.packageInfo());
        stopSelf();
    }

    wallet = new WalletLiveData(application);
    wallet.observe(this, new Observer<Wallet>() {
        @Override
        public void onChanged(final Wallet wallet) {
            classicThread.start();
            paymentProtocolThread.start();
        }
    });
}

From source file:org.ligi.android.dubwise_mk.BaseActivity.java

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

    DUBwisePrefs.init(this);

    if (DUBwisePrefs.keepLightNow()) {
        if (mWakeLock == null) {
            final PowerManager pm = (PowerManager) (getSystemService(Context.POWER_SERVICE));
            mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "DUBwise");
        }//from  www .  java  2  s .  c  o m
        mWakeLock.acquire();
    }

    // do only once
    if (!did_init) {
        //BluetoothMaster.init(activity);
        VoicePrefs.init(this);
        StatusVoice.getInstance().init(this);
        BlackBoxPrefs.init(this);

        // start the default connection
        StartupConnectionService.start(this);

        if (BlackBoxPrefs.isBlackBoxEnabled()) {
            DUBwiseBackgroundHandler.getInstance().addAndStartTask(BlackBox.getInstance());
        }

        did_init = true;
    }

    if (VoicePrefs.isVoiceEnabled() && !DUBwiseBackgroundHandler.getInstance().getBackgroundTasks()
            .contains(StatusVoice.getInstance())) {
        DUBwiseBackgroundHandler.getInstance().addAndStartTask(StatusVoice.getInstance());
    }

    setContentView(R.layout.base_layout);
    contentView = (ViewGroup) findViewById(R.id.content_frame);

    drawerList = (ListView) findViewById(R.id.left_drawer);

    drawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            IconicMenuItem item = ((IconicMenuItem) (drawerList.getAdapter().getItem(position)));

            if (item.intent != null) {
                startActivity(item.intent);
            }

        }
    });
    refresh_list();

    //mTitle = mDrawerTitle = getTitle();
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.drawer_open,
            R.string.drawer_close) {

        /** Called when a drawer has settled in a completely closed state. */
        public void onDrawerClosed(View view) {
            //getActionBar().setTitle(mTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        /** Called when a drawer has settled in a completely open state. */
        public void onDrawerOpened(View drawerView) {
            //getActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };

    drawerLayout.setDrawerListener(drawerToggle);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    // a little hack because I strongly disagree with the style guide here
    // ;-)
    // not having the Actionbar overfow menu also with devices with hardware
    // key really helps discoverability
    // http://stackoverflow.com/questions/9286822/how-to-force-use-of-overflow-menu-on-devices-with-menu-button
    try {
        ViewConfiguration config = ViewConfiguration.get(this);
        Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
        if (menuKeyField != null) {
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        }
    } catch (Exception ex) {
        // Ignore - but at least we tried ;-)
    }

}