Java Code Examples for android.os.PowerManager#newWakeLock()

The following examples show how to use android.os.PowerManager#newWakeLock() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RedPacketService.java    From styT with Apache License 2.0 6 votes vote down vote up
/**
 * 解锁屏幕
 */
private void wakeUpScreen() {

    //获取电源管理器对象
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    //后面的参数|表示同时传入两个值,最后的是调试用的Tag
    wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK, "bright");

    //点亮屏幕
    wakeLock.acquire();

    //得到键盘锁管理器
    KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
    keyguardLock = km.newKeyguardLock("unlock");

    //解锁
    keyguardLock.disableKeyguard();
}
 
Example 2
Source File: WakefulBroadcastReceiver.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Do a {@link android.content.Context#startService(android.content.Intent)
 * Context.startService}, but holding a wake lock while the service starts.
 * This will modify the Intent to hold an extra identifying the wake lock;
 * when the service receives it in {@link android.app.Service#onStartCommand
 * Service.onStartCommand}, it should the Intent it receives there back to
 * {@link #completeWakefulIntent(android.content.Intent)} in order to release
 * the wake lock.
 *
 * @param context The Context in which it operate.
 * @param intent The Intent with which to start the service, as per
 * {@link android.content.Context#startService(android.content.Intent)
 * Context.startService}.
 */
public static ComponentName startWakefulService(Context context, Intent intent) {
    synchronized (mActiveWakeLocks) {
        int id = mNextId;
        mNextId++;
        if (mNextId <= 0) {
            mNextId = 1;
        }

        intent.putExtra(EXTRA_WAKE_LOCK_ID, id);
        ComponentName comp = context.startService(intent);
        if (comp == null) {
            return null;
        }

        PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                "wake:" + comp.flattenToShortString());
        wl.setReferenceCounted(false);
        wl.acquire(60*1000);
        mActiveWakeLocks.put(id, wl);
        return comp;
    }
}
 
Example 3
Source File: ScreenLockUtil.java    From AndroidModulePattern with Apache License 2.0 6 votes vote down vote up
/**
 * 保持屏幕常亮
 *
 * @param activity you know
 */
public static void keepScreenOn(Activity activity) {
    WakeLock wakeLock = mWakeLockArray.get(activity);
    if (wakeLock == null) {
        PowerManager powerManager = (PowerManager) activity.getSystemService(Context.POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK,
                activity.getClass().getName());
    }

    if (!wakeLock.isHeld()) {
        wakeLock.acquire();
    }

    mWakeLockArray.put(activity, wakeLock);

    cancelLockScreen(activity);

    Log.i(TAG, "开启屏幕常亮");
}
 
Example 4
Source File: CreateEDSLocationTaskFragmentBase.java    From edslite with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void doWork(TaskState state) throws Exception
{
    state.setResult(0);
    Location location = _locationsManager
            .getLocation(
                    (Uri) getArguments().getParcelable(ARG_LOCATION));

    if(!checkParams(state, location))
        return;
    PowerManager pm = (PowerManager) _context
            .getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
            toString());
    wl.acquire();
    try
    {
        createEDSLocation(state, location);
    }
    finally
    {
        wl.release();
    }
}
 
Example 5
Source File: SonicAudioPlayer.java    From AntennaPod-AudioPlayer with Apache License 2.0 6 votes vote down vote up
@Override
public void setWakeMode(Context context, int mode) {
    boolean wasHeld = false;
    if (mWakeLock != null) {
        if (mWakeLock.isHeld()) {
            wasHeld = true;
            mWakeLock.release();
        }
        mWakeLock = null;
    }

    if (mode > 0) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(mode, this.getClass().getName());
        mWakeLock.setReferenceCounted(false);
        if (wasHeld) {
            mWakeLock.acquire();
        }
    }
}
 
Example 6
Source File: BotService.java    From Telephoto with Apache License 2.0 5 votes vote down vote up
private void preventSleepMode() {
    try {
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                "MyWakelockTag");
        wakeLock.acquire();
    } catch (Throwable ex) {
        L.e(ex);
    }
}
 
Example 7
Source File: InputActivity.java    From wearmouse with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_card_flip);
    setAmbientEnabled();

    PowerManager powerManager = getSystemService(PowerManager.class);
    wakeLock =
            powerManager.newWakeLock(
                    SCREEN_DIM_WAKE_LOCK | ACQUIRE_CAUSES_WAKEUP, "WearMouse:PokeScreen");

    keyboardController = new KeyboardInputController(this::finish);
    keyboardController.onCreate(this);

    currentMode = InputMode.MOUSE;
    Intent intent = getIntent();
    if (intent != null) {
        int mode = intent.getIntExtra(EXTRA_INPUT_MODE, -1);
        if (mode > 0) {
            currentMode = mode;
        }
    }

    getFragmentManager()
            .beginTransaction()
            .add(R.id.fragment_container, getFragment(currentMode))
            .commit();

    registerReceiver(screenReceiver, new IntentFilter(ACTION_SCREEN_OFF));
}
 
Example 8
Source File: DownloadTask.java    From Bluefruit_LE_Connect_Android_V2 with MIT License 5 votes vote down vote up
@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 powerManager = (PowerManager) mWeakContext.get().getSystemService(Context.POWER_SERVICE);
    if (powerManager != null) {
        mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
        mWakeLock.acquire();
    }
}
 
Example 9
Source File: StaticWakeLock.java    From SpecialAlarmClock with Apache License 2.0 5 votes vote down vote up
public static void lockOn(Context context) {
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    //Object flags;
    if (wl == null)
        wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "MATH_ALARM");
    wl.acquire();
}
 
Example 10
Source File: WakeLock.java    From cathode with Apache License 2.0 5 votes vote down vote up
private static PowerManager.WakeLock getLock(Context context, String tag) {
  synchronized (WAKELOCKS) {
    PowerManager.WakeLock wakeLock = WAKELOCKS.get(tag);
    if (wakeLock == null || !wakeLock.isHeld()) {
      PowerManager mgr = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
      wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, tag);
      WAKELOCKS.put(tag, wakeLock);
    }
    return wakeLock;
  }
}
 
Example 11
Source File: StandupTimer.java    From UltimateAndroid with Apache License 2.0 5 votes vote down vote up
private void acquireWakeLock() {
    if (wakeLock == null) {
        Logger.d("Acquiring wake lock");
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, this.getClass().getCanonicalName());
        wakeLock.acquire();
    }
}
 
Example 12
Source File: WakeLocker.java    From AndroidDemo with Apache License 2.0 5 votes vote down vote up
public static void acquire(Context ctx) {
	if (wakeLock != null)
		wakeLock.release();

	PowerManager pm = (PowerManager) ctx
			.getSystemService(Context.POWER_SERVICE);
	// wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
	// PowerManager.ACQUIRE_CAUSES_WAKEUP |
	// PowerManager.ON_AFTER_RELEASE, "TAG");
	wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TAG");
	wakeLock.acquire();
}
 
Example 13
Source File: SelfAwareConditions.java    From Saiy-PS with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Constructor
 * <p/>
 * When a remote application first binds to {@link SelfAware} it may make a number of initial
 * requests to check the state of the application (such as speaking or listening). We set the
 * {@link #count} to zero here and allow it to make {@link #THROTTLE_IGNORE} requests before we
 * start applying any potential throttling limit on requests.
 *
 * @param mContext         the application context
 * @param telephonyManager the {@link TelephonyManager}
 */
public SelfAwareConditions(@NonNull final Context mContext, @NonNull final TelephonyManager telephonyManager) {
    super(mContext, telephonyManager);
    this.mContext = mContext;
    count = 0;

    final PowerManager manager = (PowerManager) this.mContext.getSystemService(Context.POWER_SERVICE);
    wakeLock = manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);

    //noinspection deprecation
    wakeLockDisplay = manager.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
            WAKELOCK_DISPLAY_TAG);

    saiySoundPool = new SaiySoundPool().setUp(this.mContext, SaiySoundPool.VOICE_RECOGNITION);
}
 
Example 14
Source File: JobIntentService.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
CompatWorkEnqueuer(Context context, ComponentName cn) {
    super(context, cn);
    mContext = context.getApplicationContext();
    // Make wake locks.  We need two, because the launch wake lock wants to have
    // a timeout, and the system does not do the right thing if you mix timeout and
    // non timeout (or even changing the timeout duration) in one wake lock.
    PowerManager pm = ((PowerManager) context.getSystemService(Context.POWER_SERVICE));
    mLaunchWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
            cn.getClassName() + ":launch");
    mLaunchWakeLock.setReferenceCounted(false);
    mRunWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
            cn.getClassName() + ":run");
    mRunWakeLock.setReferenceCounted(false);
}
 
Example 15
Source File: MyScreenLocker.java    From SimplePomodoro-android with MIT License 4 votes vote down vote up
public void unlock(){
	PowerManager pm = (PowerManager)mActivity.getSystemService(Context.POWER_SERVICE);
	WakeLock mWakelock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |PowerManager.SCREEN_DIM_WAKE_LOCK, "SimpleTimer");
	mWakelock.acquire();
	mWakelock.release();
}
 
Example 16
Source File: SettingsDownloader.java    From SettingsDeployer with MIT License 4 votes vote down vote up
@Override
protected Boolean doInBackground(String... strParams)
{
    Boolean result = Boolean.FALSE;

    // get a wakelock to hold for the duration of the background work. downloading
    // may be slow. extraction usually isn't too slow but also takes a bit of time. limit the wakelock's time!
    PowerManager powerManager = (PowerManager)m_ctx.getSystemService(Context.POWER_SERVICE);
    WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "SettingsDownloaderWakeLock");
    wakeLock.acquire(FOUR_MINUTES);

    // download the file
    String filename = downloadFile(strParams[0]);
    if (filename != null)
    {
        File fSettingsZip = new File(filename);
        if (fSettingsZip.exists() && !isCancelled())
        {
            try
            {
                m_logWriter.write("Successfully downloaded to: "+filename+"\n");

                // extract to wanted directory
                String destDir = strParams[1];
                boolean bSuccess = extractSettingsZip(fSettingsZip, destDir);
                result = (bSuccess ? Boolean.TRUE : Boolean.FALSE);

                // delete settings zip
                if (fSettingsZip.exists()) {
                    fSettingsZip.delete();
                }
            }
            catch(Exception e)
            {
                Log.e("SettingsDownloader", "Error: "+e.toString());
            }
        }
    }

    // if our max time hasn't passed but work is done or an error occurred we bail out and release
    if (wakeLock.isHeld())
    {
        wakeLock.release();
    }

    return result;
}
 
Example 17
Source File: DownloadThread.java    From UnityOBBDownloader with Apache License 2.0 4 votes vote down vote up
/**
 * Executes the download in a separate thread
 */
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    State state = new State(mInfo, mService);
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = DownloaderService.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.mFileName);
            Log.v(Constants.TAG, "  at " + mInfo.mUri);
        }

        boolean finished = false;
        while (!finished) {
            if (Constants.LOGV) {
                Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName);
                Log.v(Constants.TAG, "  at " + mInfo.mUri);
            }
            // Set or unset proxy, which may have changed since last GET
            // request.
            // setDefaultProxy() supports null as proxy parameter.
            URL url = new URL(state.mRequestUri);
            HttpURLConnection request = (HttpURLConnection)url.openConnection();
            request.setRequestProperty("User-Agent", userAgent());
            try {
                executeDownload(state, request);
                finished = true;
            } catch (RetryDownload exc) {
                // fall through
            } finally {
                request.disconnect();
                request = null;
            }
        }

        if (Constants.LOGV) {
            Log.v(Constants.TAG, "download completed for " + mInfo.mFileName);
            Log.v(Constants.TAG, "  at " + mInfo.mUri);
        }
        finalizeDestinationFile(state);
        finalStatus = DownloaderService.STATUS_SUCCESS;
    } catch (StopRequest error) {
        // remove the cause before printing, in case it contains PII
        Log.w(Constants.TAG,
                "Aborting request for download " + mInfo.mFileName + ": " + error.getMessage());
        error.printStackTrace();
        finalStatus = error.mFinalStatus;
        // fall through to finally block
    } catch (Throwable ex) { // sometimes the socket code throws unchecked
                             // exceptions
        Log.w(Constants.TAG, "Exception for " + mInfo.mFileName + ": " + ex);
        finalStatus = DownloaderService.STATUS_UNKNOWN_ERROR;
        // falls through to the code that reports an error
    } finally {
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        cleanupDestination(state, finalStatus);
        notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter,
                state.mRedirectCount, state.mGotData, state.mFilename);
    }
}
 
Example 18
Source File: AndroidWakeLock.java    From actor-platform with GNU Affero General Public License v3.0 4 votes vote down vote up
public AndroidWakeLock() {
    PowerManager powerManager = (PowerManager) AndroidContext.getContext().getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
            "ActorWakelock");
    wakeLock.acquire();
}
 
Example 19
Source File: MainActivity.java    From QuickerAndroid with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 设置背光亮一段时间
 */
void setupScreenLight() {
    PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "MyWakeLock");
    wakeLock.acquire(60 * 60 * 1000);
}
 
Example 20
Source File: DownloadThread.java    From travelguide with Apache License 2.0 4 votes vote down vote up
/**
 * Executes the download in a separate thread
 */
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    State state = new State(mInfo, mService);
    AndroidHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = DownloaderService.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.mFileName);
            Log.v(Constants.TAG, "  at " + mInfo.mUri);
        }

        client = AndroidHttpClient.newInstance(userAgent(), mContext);

        boolean finished = false;
        while (!finished) {
            if (Constants.LOGV) {
                Log.v(Constants.TAG, "initiating download for " + mInfo.mFileName);
                Log.v(Constants.TAG, "  at " + mInfo.mUri);
            }
            // Set or unset proxy, which may have changed since last GET
            // request.
            // setDefaultProxy() supports null as proxy parameter.
            ConnRouteParams.setDefaultProxy(client.getParams(),
                    getPreferredHttpHost(mContext, state.mRequestUri));
            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.mFileName);
            Log.v(Constants.TAG, "  at " + mInfo.mUri);
        }
        finalizeDestinationFile(state);
        finalStatus = DownloaderService.STATUS_SUCCESS;
    } catch (StopRequest error) {
        // remove the cause before printing, in case it contains PII
        Log.w(Constants.TAG,
                "Aborting request for download " + mInfo.mFileName + ": " + error.getMessage());
        error.printStackTrace();
        finalStatus = error.mFinalStatus;
        // fall through to finally block
    } catch (Throwable ex) { // sometimes the socket code throws unchecked
                             // exceptions
        Log.w(Constants.TAG, "Exception for " + mInfo.mFileName + ": " + ex);
        finalStatus = DownloaderService.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.mRedirectCount, state.mGotData, state.mFilename);
    }
}