Example usage for android.os PowerManager newWakeLock

List of usage examples for android.os PowerManager newWakeLock

Introduction

In this page you can find the example usage for android.os PowerManager newWakeLock.

Prototype

public WakeLock newWakeLock(int levelAndFlags, String tag) 

Source Link

Document

Creates a new wake lock with the specified level and flags.

Usage

From source file:com.z3r0byte.magistify.Services.BackgroundService.java

@SuppressLint("InvalidWakeLockTag")
@Override/*from   ww  w . jav  a2s .  c om*/
public void onReceive(final Context context, Intent intent) {
    PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    wakeLock.acquire(15 * 1000);

    //Bundle extras = intent.getExtras();

    mGson = new Gson();
    calendarDB = new CalendarDB(context);
    scheduleChangeDB = new ScheduleChangeDB(context);
    gradesdb = new NewGradesDB(context);
    homeworkDB = new HomeworkDB(context);

    this.context = context;
    configUtil = new ConfigUtil(context);
    final User user = mGson.fromJson(configUtil.getString("User"), User.class);
    final School school = mGson.fromJson(configUtil.getString("School"), School.class);

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                manageSession(user, school);
                if (configUtil.getBoolean("silent_enabled") || configUtil.getBoolean("appointment_enabled")
                        || configUtil.getBoolean("new_homework_notification")) {
                    getAppointments();
                }

                if (configUtil.getBoolean("appointment_enabled")) {
                    appointmentNotification();
                }

                if (configUtil.getBoolean("silent_enabled")) {
                    autoSilent();
                }

                if (configUtil.getBoolean("new_grade_enabled")) {
                    newGradeNotification();
                }

                if (configUtil.getBoolean("notificationOnNewChanges")) {
                    newScheduleChangeNotification();
                }

                if (configUtil.getBoolean("notificationOnChangedLesson")) {
                    nextAppointmentChangedNotification();
                }

                if (configUtil.getBoolean("unfinished_homework_notification")) {
                    unFinishedHomeworkNotification();
                }

                if (configUtil.getBoolean("new_homework_notification")) {
                    newHomeworkNotification();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                Log.d(TAG, "onReceive: Cleaning up and releasing wakelock!");
                if (wakeLock.isHeld())
                    wakeLock.release();
                calendarDB.close();
                scheduleChangeDB.close();
                gradesdb.close();
            }
        }
    }).start();
}

From source file:com.iamplus.musicplayer.MusicService.java

@Override
public void onCreate() {
    Log.i(TAG, "debug: Creating service");

    // Create the Wifi lock (this does not acquire the lock, this just creates it)
    //      mWifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
    //            .createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    mWakeLock.setReferenceCounted(false);

    //mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

    // create the Audio Focus Helper, if the Audio Focus feature is available (SDK 8 or above)
    if (android.os.Build.VERSION.SDK_INT >= 8)
        mAudioFocusHelper = new AudioFocusHelper(getApplicationContext(), this);
    else/*from   ww  w . j a v a  2s  .  c  om*/
        mAudioFocus = AudioFocus.Focused; // no focus feature, so we always "have" audio focus

    //mDummyAlbumArt = BitmapFactory.decodeResource(getResources(), R.drawable.albumart_mp_unknown);

    mMediaButtonReceiverComponent = new ComponentName(this, MusicIntentReceiver.class);

    e_play_mode emode = MusicRetriever.getPlayModePref(this, e_play_mode.e_play_mode_normal);
    MusicRetriever.getInstance().setPlayMode(emode);
}

From source file:com.example.socketio.lib.IOConnection.java

/**
 * Sends a plain message to the {@link IOTransport}.
 * /*  w  w  w. j  a  v  a  2s. c  o m*/
 * @param text
 *            the Text to be send.
 */
private synchronized void sendPlain(String text) {
    if (wakelock == null) {
        // Log.e(TAG, "wakelock==null");
        PowerManager pm = (PowerManager) mContext.getSystemService(Service.POWER_SERVICE);
        wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, wakeLockTag);
    }
    wakelock.acquire();
    if (getState() == STATE_READY)
        try {
            logger.info("> " + text);
            transport.send(text);
        } catch (Exception e) {
            logger.info("IOEx: saving");
            outputBuffer.add(text);
        }
    else {
        outputBuffer.add(text);
    }
    if (wakelock != null && wakelock.isHeld()) {
        wakelock.release();
    }
}

From source file:com.kncwallet.wallet.service.BlockchainServiceImpl.java

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

    super.onCreate();

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

    final String lockName = getPackageName() + " blockchain sync";

    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, lockName);

    application = (WalletApplication) getApplication();
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    final Wallet wallet = application.getWallet();

    bestChainHeightEver = prefs.getInt(Constants.PREFS_KEY_BEST_CHAIN_HEIGHT_EVER, 0);

    peerConnectivityListener = new PeerConnectivityListener();

    sendBroadcastPeerState(0);/*from www  . ja  v a  2 s .c  om*/

    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
    registerReceiver(connectivityReceiver, intentFilter);

    blockChainFile = new File(getDir("blockstore", Context.MODE_PRIVATE), Constants.BLOCKCHAIN_FILENAME);
    final boolean blockChainFileExists = blockChainFile.exists();

    if (!blockChainFileExists) {
        log.info("blockchain does not exist, resetting wallet");

        wallet.clearTransactions(0);
        wallet.setLastBlockSeenHeight(-1); // magic value
        wallet.setLastBlockSeenHash(null);
    }

    try {
        blockStore = new SPVBlockStore(Constants.NETWORK_PARAMETERS, blockChainFile);
        blockStore.getChainHead(); // detect corruptions as early as possible

        final long earliestKeyCreationTime = wallet.getEarliestKeyCreationTime();

        if (!blockChainFileExists && earliestKeyCreationTime > 0) {
            try {
                final InputStream checkpointsInputStream = getAssets().open(Constants.CHECKPOINTS_FILENAME);
                CheckpointManager.checkpoint(Constants.NETWORK_PARAMETERS, checkpointsInputStream, blockStore,
                        earliestKeyCreationTime);
            } catch (final IOException x) {
                log.error("problem reading checkpoints, continuing without", x);
            }
        }
    } catch (final BlockStoreException x) {
        blockChainFile.delete();

        final String msg = "blockstore cannot be created";
        log.error(msg, x);
        throw new Error(msg, x);
    }

    log.info("using " + blockStore.getClass().getName());

    try {
        blockChain = new BlockChain(Constants.NETWORK_PARAMETERS, wallet, blockStore);
    } catch (final BlockStoreException x) {
        throw new Error("blockchain cannot be created", x);
    }

    application.getWallet().addEventListener(walletEventListener);

    registerReceiver(tickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));

    maybeRotateKeys();
}

From source file:org.zeroxlab.zeroxbenchmark.Benchmark.java

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        orientation = getResources().getConfiguration().orientation;
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TAG);
        mWakeLock.acquire();/*from  w  w w .ja v a 2 s  . co  m*/

        setContentView(R.layout.main);
        mCases = new LinkedList<Case>();
        Case arith = new CaseArithmetic();
        Case javascript = new CaseJavascript();
        Case scimark2 = new CaseScimark2();
        Case canvas = new CaseCanvas();
        Case glcube = new CaseGLCube();
        Case circle = new CaseDrawCircle();
        Case nehe08 = new CaseNeheLesson08();
        Case nehe16 = new CaseNeheLesson16();
        Case teapot = new CaseTeapot();
        Case gc = new CaseGC();
        Case libMicro = new NativeCaseMicro();
        Case libUbench = new NativeCaseUbench();

        Case dc2 = new CaseDrawCircle2();
        Case dr = new CaseDrawRect();
        Case da = new CaseDrawArc();
        Case di = new CaseDrawImage();
        Case dt = new CaseDrawText();

        mCategory.put(D2, new HashSet<Case>());
        mCategory.put(D3, new HashSet<Case>());
        mCategory.put(MATH, new HashSet<Case>());
        mCategory.put(VM, new HashSet<Case>());
        mCategory.put(NATIVE, new HashSet<Case>());
        mCategory.put(MISC, new HashSet<Case>());

        // mflops
        mCases.add(arith);
        mCases.add(scimark2);
        mCases.add(javascript);
        mCategory.get(MATH).add(arith);
        mCategory.get(MATH).add(scimark2);
        mCategory.get(MISC).add(javascript);

        // 2d
        mCases.add(canvas);
        mCases.add(circle);
        mCases.add(dc2);
        mCases.add(dr);
        mCases.add(da);
        mCases.add(di);
        mCases.add(dt);

        mCategory.get(D2).add(canvas);
        mCategory.get(D2).add(circle);
        mCategory.get(D2).add(dc2);
        mCategory.get(D2).add(dr);
        mCategory.get(D2).add(da);
        mCategory.get(D2).add(di);
        mCategory.get(D2).add(dt);

        // 3d
        mCases.add(glcube);
        mCases.add(nehe08);
        mCases.add(nehe16);
        mCases.add(teapot);

        mCategory.get(D3).add(glcube);
        mCategory.get(D3).add(nehe08);
        mCategory.get(D3).add(nehe16);
        mCategory.get(D3).add(teapot);

        // vm
        mCases.add(gc);
        mCategory.get(VM).add(gc);

        // native
        mCases.add(libMicro);
        mCases.add(libUbench);

        mCategory.get(NATIVE).add(libMicro);
        mCategory.get(NATIVE).add(libUbench);

        initViews();

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            mAutoRun = bundle.getBoolean("autorun");
            mCheckMath = bundle.getBoolean("math");
            mCheck2D = bundle.getBoolean("2d");
            mCheck3D = bundle.getBoolean("3d");
            mCheckVM = bundle.getBoolean("vm");
            mCheckNative = bundle.getBoolean("native");
            mAutoUpload = bundle.getBoolean("autoupload");
        }

        if (mCheckMath && !mathCheckBox.isChecked()) {
            mathCheckBox.performClick();
        }

        if (mCheck2D && !d2CheckBox.isChecked()) {
            d2CheckBox.performClick();
        }

        if (mCheck3D && !d3CheckBox.isChecked()) {
            d3CheckBox.performClick();
        }

        if (mCheckVM && !vmCheckBox.isChecked()) {
            vmCheckBox.performClick();
        }

        if (mCheckNative && !nativeCheckBox.isChecked()) {
            nativeCheckBox.performClick();
        }

        if (mCheckMisc && !miscCheckBox.isChecked()) {
            miscCheckBox.performClick();
        }
        /*
        if (intent.getBooleanExtra("AUTO", false)) {
        ImageView head = (ImageView)findViewById(R.id.banner_img);
        head.setImageResource(R.drawable.icon_auto);
        mTouchable = false;
        initAuto();
        }
        */
        if (mAutoRun) {
            onClick(mRun);
        }
    }

From source file:com.hamradiocoin.wallet.service.BlockchainServiceImpl.java

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

    super.onCreate();

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

    final String lockName = getPackageName() + " blockchain sync";

    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, lockName);

    application = (WalletApplication) getApplication();
    config = application.getConfiguration();
    final Wallet wallet = application.getWallet();

    bestChainHeightEver = config.getBestChainHeightEver();

    peerConnectivityListener = new PeerConnectivityListener();

    sendBroadcastPeerState(0);//from ww w .  j  a v a2s.  c o m

    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
    intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
    registerReceiver(connectivityReceiver, intentFilter);

    blockChainFile = new File(getDir("blockstore", Context.MODE_PRIVATE), Constants.Files.BLOCKCHAIN_FILENAME);
    final boolean blockChainFileExists = blockChainFile.exists();

    if (!blockChainFileExists) {
        log.info("blockchain does not exist, resetting wallet");

        wallet.clearTransactions(0);
        wallet.setLastBlockSeenHeight(-1); // magic value
        wallet.setLastBlockSeenHash(null);
    }

    try {
        blockStore = new SPVBlockStore(Constants.NETWORK_PARAMETERS, blockChainFile);
        blockStore.getChainHead(); // detect corruptions as early as possible

        final long earliestKeyCreationTime = wallet.getEarliestKeyCreationTime();

        if (!blockChainFileExists && earliestKeyCreationTime > 0) {
            try {
                final InputStream checkpointsInputStream = getAssets()
                        .open(Constants.Files.CHECKPOINTS_FILENAME);
                CheckpointManager.checkpoint(Constants.NETWORK_PARAMETERS, checkpointsInputStream, blockStore,
                        earliestKeyCreationTime);
            } catch (final IOException x) {
                log.error("problem reading checkpoints, continuing without", x);
            }
        }
    } catch (final BlockStoreException x) {
        blockChainFile.delete();

        final String msg = "blockstore cannot be created";
        log.error(msg, x);
        throw new Error(msg, x);
    }

    log.info("using " + blockStore.getClass().getName());

    try {
        blockChain = new BlockChain(Constants.NETWORK_PARAMETERS, wallet, blockStore);
    } catch (final BlockStoreException x) {
        throw new Error("blockchain cannot be created", x);
    }

    application.getWallet().addEventListener(walletEventListener, Threading.SAME_THREAD);

    registerReceiver(tickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));

    maybeRotateKeys();
}

From source file:com.example.download.DownloadThread.java

/**
 * Executes the download in a separate thread
 *///from   ww  w .  j  a  v a2  s.  c om
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, com.example.util.Utils.sLogTag);
        wakeLock.acquire();

        Utils.D("initiating download for " + mInfo.mUri);

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

        boolean finished = false;
        while (!finished) {

            Utils.D("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;
            }
        }

        Utils.D("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
        Utils.W("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
        Utils.W("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:com.mappn.gfan.common.download.DownloadThread.java

/**
 * Executes the download in a separate thread
 *///from ww w. j av a  2s  .co m
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, com.mappn.gfan.common.util.Utils.sLogTag);
        wakeLock.acquire();

        Utils.D("initiating download for " + mInfo.mUri);

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

        boolean finished = false;
        while (!finished) {

            Utils.D("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;
            }
        }

        Utils.D("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
        Utils.W("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
        Utils.W("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:com.bonsai.btcreceive.WalletService.java

@Override
public void onCreate() {
    mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    mLBM = LocalBroadcastManager.getInstance(this);

    mLogger.info("WalletService created");

    mContext = getApplicationContext();//from w  w  w  .  j av  a 2s.  c o  m
    mRes = mContext.getResources();

    final String lockName = getPackageName() + " blockchain sync";
    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, lockName);

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    String fiatRateSource = sharedPref.getString(SettingsActivity.KEY_FIAT_RATE_SOURCE, "");
    setFiatRateSource(fiatRateSource);

    // Register for future preference changes.
    sharedPref.registerOnSharedPreferenceChangeListener(this);
}

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

/**
 * Executes the download in a separate thread
 *///from   w  ww  .j  av  a  2s .c om
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;
    }
}