Java Code Examples for android.os.PowerManager

The following examples show how to use android.os.PowerManager. These examples are extracted from open source projects. 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
@Override
public void onReceive(Context context, Intent intent) {
	PowerManager.WakeLock wl = null;
	try {
		PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
		wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
		wl.acquire();
		if (Utils.canAutoUploadBool()) {
			UploadService.checkNewFiles();
		} else {
			initAlarm();
		}
	} catch (Throwable e) {
		LOG.error(ToolString.stack2string(e));
	} finally {
		if (wl != null) {
			wl.release();
		}
	}
}
 
Example 2
Source Project: mollyim-android   Source File: WakeLockUtil.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param tag will be prefixed with "signal:" if it does not already start with it.
 */
public static WakeLock acquire(@NonNull Context context, int lockType, long timeout, @NonNull String tag) {
  tag = prefixTag(tag);
  try {
    PowerManager powerManager = ServiceUtil.getPowerManager(context);
    WakeLock     wakeLock     = powerManager.newWakeLock(lockType, tag);

    wakeLock.acquire(timeout);
    Log.d(TAG, "Acquired wakelock with tag: " + tag);

    return wakeLock;
  } catch (Exception e) {
    Log.w(TAG, "Failed to acquire wakelock with tag: " + tag, e);
    return null;
  }
}
 
Example 3
Source Project: Rey-MusicPlayer   Source File: FadeMediaPlayer.java    License: Apache License 2.0 6 votes vote down vote up
public FadeMediaPlayer(MusicService musicService) {
    mMusicService = musicService;

    mMediaPlayer1 = new MediaPlayer();
    mMediaPlayer2 = new MediaPlayer();
    mHandler = new Handler();

    mMediaPlayer1.setWakeMode(mMusicService, PowerManager.PARTIAL_WAKE_LOCK);
    mMediaPlayer1.setAudioStreamType(AudioManager.STREAM_MUSIC);

    mMediaPlayer2.setWakeMode(mMusicService, PowerManager.PARTIAL_WAKE_LOCK);
    mMediaPlayer2.setAudioStreamType(AudioManager.STREAM_MUSIC);

    try {
        startSong();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 4
Source Project: cordova-rtmp-rtsp-stream   Source File: RTSPActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    if (pm != null) {
        mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK |
                PowerManager.ON_AFTER_RELEASE, TAG);
        mWakeLock.acquire(10);
    }

    Intent intent = getIntent();
    _username = intent.getStringExtra("username");
    _password = intent.getStringExtra("password");
    _url = intent.getStringExtra("url");

    Toast.makeText(this, "U: " + _username + " P: " + _password + " U: " + _url, Toast.LENGTH_SHORT).show();
    
    _UIListener();
}
 
Example 5
Source Project: turbo-editor   Source File: Device.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Reboots the device into the recovery.<br /><br />
 * 
 * This method first tries using the {@link PowerManager}, if that fails it fallbacks on using the reboot command from toolbox.<br /><br />
 * 
 * Note that using the {@link PowerManager} requires your app to optain the 'REBOOT' permission. If you don't want this, just parse NULL as {@link Context} 
 * and the method will use the fallback. This however is more likely to fail, as many toolbox versions does not support the reboot command. 
 * And since only the kernel can write to the CBC, we need a native caller to invoke this. So there is no fallback for missing toolbox support when it comes 
 * to rebooting into the recovery. 
 * 
 * @param context
 *     A {@link Context} or NULL to skip using the {@link PowerManager}
 */
public Boolean rebootRecovery(Context context) {
	if (context != null) {
		try {
			PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
			pm.reboot(null);
			
			/*
			 * This will never be reached if the reboot is successful
			 */
			return false;	
		
		} catch (Throwable e) {}
	}
	
	Result result = mShell.execute("toolbox reboot recovery");
	
	return result != null && result.wasSuccessful();
}
 
Example 6
Source Project: LivePlayback   Source File: IjkMediaPlayer.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressLint("Wakelock")
@Override
public void setWakeMode(Context context, int mode) {
    boolean washeld = false;
    if (mWakeLock != null) {
        if (mWakeLock.isHeld()) {
            washeld = true;
            mWakeLock.release();
        }
        mWakeLock = null;
    }

    PowerManager pm = (PowerManager) context
            .getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(mode | PowerManager.ON_AFTER_RELEASE,
            IjkMediaPlayer.class.getName());
    mWakeLock.setReferenceCounted(false);
    if (washeld) {
        mWakeLock.acquire();
    }
}
 
Example 7
@Override
public void onReceive(Context context, Intent intent) {
    String action = new HostMonitorConfig(context).getBroadcastAction();

    if (intent == null || action == null || !intent.getAction().equals(action)) {
        return;
    }

    PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                                                              getClass().getSimpleName());

    wakeLock.acquire();

    HostStatus hostStatus = intent.getParcelableExtra(HostMonitor.PARAM_STATUS);
    onHostStatusChanged(hostStatus);

    wakeLock.release();
}
 
Example 8
Source Project: 600SeriesAndroidUploader   Source File: PushoverUploadService.java    License: MIT License 6 votes vote down vote up
public void run() {

            PowerManager.WakeLock wl = getWakeLock(mContext, TAG, 60000);

            storeRealm = Realm.getInstance(UploaderApplication.getStoreConfiguration());
            dataStore = storeRealm.where(DataStore.class).findFirst();

            if (UploaderApplication.isOnline() && dataStore.isPushoverEnable()) {
                statPushover = (StatPushover) Stats.getInstance().readRecord(StatPushover.class);
                statPushover.incRun();

                pushoverApi = new PushoverApi(PUSHOVER_URL);
                if (isValid()) process();
                else statPushover.incValidError();
            }

            storeRealm.close();

            releaseWakeLock(wl);
            stopSelf();
        }
 
Example 9
Source Project: Trigger   Source File: TriggerLoop.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    jobSet = new ConcurrentHashMap<>();
    receivers = new ConcurrentHashMap<>();
    jobHappens = new ConcurrentHashMap<>();
    binder = new TriggerBinder();
    executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE, new TriggerWorkerFactory());
    mainHandler = new Handler(Looper.getMainLooper());
    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    shortDeadlineHandler = new Handler();
    deadlineCheck = new DeadlineCheck();
    sDeviceStatus = DeviceStatus.get(this);
    registerReceiver(deadlineCheck, new IntentFilter(DEADLINE_BROADCAST));
    PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
    int granted = checkCallingOrSelfPermission("android.permission.WAKE_LOCK");
    if (granted == PackageManager.PERMISSION_GRANTED) {
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    } else {
        wakeLock = null;
    }
    handlerThread = new HandlerThread("Trigger-HandlerThread");
    handlerThread.start();
    checker = new CheckHandler(handlerThread.getLooper());
    mayRecoverJobsFromFile();
}
 
Example 10
@Override
public void run() {
  notification              = initializeBackgroundNotification();
  PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
  WakeLock     wakeLock     = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Migration");

  try {
    wakeLock.acquire();

    setState(new ImportState(ImportState.STATE_MIGRATING_BEGIN, null));

    SmsMigrator.migrateDatabase(ApplicationMigrationService.this,
                                masterSecret,
                                ApplicationMigrationService.this);

    setState(new ImportState(ImportState.STATE_MIGRATING_COMPLETE, null));

    setDatabaseImported(ApplicationMigrationService.this);
    stopForeground(true);
    notifyImportComplete();
    stopSelf();
  } finally {
    wakeLock.release();
  }
}
 
Example 11
Source Project: bcm-android   Source File: LockManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
public LockManager(Context context) {
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    fullLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "BCM:Full");
    partialLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "BCM:Partial");
    proximityLock = new ProximityLock(pm);

    WifiManager wm = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "RedPhone Wifi");

    fullLock.setReferenceCounted(false);
    partialLock.setReferenceCounted(false);
    wifiLock.setReferenceCounted(false);

    accelerometerListener = new AccelerometerListener(context, new AccelerometerListener.OrientationListener() {
        @Override
        public void orientationChanged(int newOrientation) {
            orientation = newOrientation;
            Log.d(TAG, "Orentation Update: " + newOrientation);
            updateInCallLockState();
        }
    });

    wifiLockEnforced = isWifiPowerActiveModeEnabled(context);
}
 
Example 12
Source Project: android_9.0.0_r45   Source File: NetworkStatsService.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
NetworkStatsService(Context context, INetworkManagementService networkManager,
        AlarmManager alarmManager, PowerManager.WakeLock wakeLock, Clock clock,
        TelephonyManager teleManager, NetworkStatsSettings settings,
        NetworkStatsObservers statsObservers, File systemDir, File baseDir) {
    mContext = checkNotNull(context, "missing Context");
    mNetworkManager = checkNotNull(networkManager, "missing INetworkManagementService");
    mAlarmManager = checkNotNull(alarmManager, "missing AlarmManager");
    mClock = checkNotNull(clock, "missing Clock");
    mSettings = checkNotNull(settings, "missing NetworkStatsSettings");
    mTeleManager = checkNotNull(teleManager, "missing TelephonyManager");
    mWakeLock = checkNotNull(wakeLock, "missing WakeLock");
    mStatsObservers = checkNotNull(statsObservers, "missing NetworkStatsObservers");
    mSystemDir = checkNotNull(systemDir, "missing systemDir");
    mBaseDir = checkNotNull(baseDir, "missing baseDir");
    mUseBpfTrafficStats = new File("/sys/fs/bpf/traffic_uid_stats_map").exists();

    LocalServices.addService(NetworkStatsManagerInternal.class,
            new NetworkStatsManagerInternalImpl());
}
 
Example 13
Source Project: a   Source File: SystemUtil.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static void ignoreBatteryOptimization(Activity activity) {
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) return;

    PowerManager powerManager = (PowerManager) activity.getSystemService(POWER_SERVICE);
    boolean hasIgnored = powerManager.isIgnoringBatteryOptimizations(activity.getPackageName());
    //  判断当前APP是否有加入电池优化的白名单,如果没有,弹出加入电池优化的白名单的设置对话框。
    if (!hasIgnored) {
        try {
            @SuppressLint("BatteryLife")
            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + activity.getPackageName()));
            activity.startActivity(intent);
        } catch (Throwable ignored) {
        }
    }
}
 
Example 14
Source Project: coursera-android   Source File: MediaPlaybackService.java    License: MIT License 6 votes vote down vote up
public void setNextDataSource(String path) {
    mCurrentMediaPlayer.setNextMediaPlayer(null);
    if (mNextMediaPlayer != null) {
        mNextMediaPlayer.release();
        mNextMediaPlayer = null;
    }
    if (path == null) {
        return;
    }
    mNextMediaPlayer = new CompatMediaPlayer();
    mNextMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
    mNextMediaPlayer.setAudioSessionId(getAudioSessionId());
    if (setDataSourceImpl(mNextMediaPlayer, path)) {
        mCurrentMediaPlayer.setNextMediaPlayer(mNextMediaPlayer);
    } else {
        // failed to open next, we'll transition the old fashioned way,
        // which will skip over the faulty file
        mNextMediaPlayer.release();
        mNextMediaPlayer = null;
    }
}
 
Example 15
Source Project: DataLogger   Source File: DataLoggerService.java    License: MIT License 6 votes vote down vote up
public void onCreate() {
    // Fires when a service is first initialized
    super.onCreate();

    PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

    mMasterAddress = "";

    mNotification = new NotificationCompat.Builder(this)
            .setContentTitle(getResources().getString(R.string.notification_content_title))
            .setTicker(getResources().getString(R.string.notification_ticker))
            .setContentText(getResources().getString(R.string.notification_waiting_content_text))
            .setSmallIcon(R.drawable.ic_not_128)
            .setContentIntent(PendingIntent.getActivity(this, 1, new Intent(this, DisplayActivity.class), PendingIntent.FLAG_UPDATE_CURRENT))
            .setOngoing(true).build();

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    if (mBluetoothAdapter == null) { // Device does not support Bluetooth
        updateBluetoothState(Constants.BLUETOOTH_STATE_NOT_SUPPORTED);
    } else {
        registerReceiver(mBluetoothStateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
    }
}
 
Example 16
public NetworkTimeUpdateService(Context context) {
    mContext = context;
    mTime = NtpTrustedTime.getInstance(context);
    mAlarmManager = mContext.getSystemService(AlarmManager.class);
    mCM = mContext.getSystemService(ConnectivityManager.class);

    Intent pollIntent = new Intent(ACTION_POLL, null);
    mPendingPollIntent = PendingIntent.getBroadcast(mContext, POLL_REQUEST, pollIntent, 0);

    mPollingIntervalMs = mContext.getResources().getInteger(
            com.android.internal.R.integer.config_ntpPollingInterval);
    mPollingIntervalShorterMs = mContext.getResources().getInteger(
            com.android.internal.R.integer.config_ntpPollingIntervalShorter);
    mTryAgainTimesMax = mContext.getResources().getInteger(
            com.android.internal.R.integer.config_ntpRetry);
    mTimeErrorThresholdMs = mContext.getResources().getInteger(
            com.android.internal.R.integer.config_ntpThreshold);

    mWakeLock = context.getSystemService(PowerManager.class).newWakeLock(
            PowerManager.PARTIAL_WAKE_LOCK, TAG);
}
 
Example 17
/**
 * 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 pass back the Intent it receives there 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 18
Source Project: xDrip   Source File: BaseWatchFace.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    //mActivity = this;//TODO
    Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
            .getDefaultDisplay();
    display.getSize(displaySize);
    wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Clock");

    specW = View.MeasureSpec.makeMeasureSpec(displaySize.x,
            View.MeasureSpec.EXACTLY);
    specH = View.MeasureSpec.makeMeasureSpec(displaySize.y,
            View.MeasureSpec.EXACTLY);
    sharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(this);
    sharedPrefs.registerOnSharedPreferenceChangeListener(this);
    smallFontsizeArray = getResources().getStringArray(R.array.toggle_fontsize);
    externalStatusString = getResources().getString(R.string.init_external_status);
}
 
Example 19
Source Project: android_9.0.0_r45   Source File: AnyMotionDetector.java    License: Apache License 2.0 6 votes vote down vote up
public AnyMotionDetector(PowerManager pm, Handler handler, SensorManager sm,
        DeviceIdleCallback callback, float thresholdAngle) {
    if (DEBUG) Slog.d(TAG, "AnyMotionDetector instantiated.");
    synchronized (mLock) {
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        mWakeLock.setReferenceCounted(false);
        mHandler = handler;
        mSensorManager = sm;
        mAccelSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mMeasurementInProgress = false;
        mMeasurementTimeoutIsActive = false;
        mWakelockTimeoutIsActive = false;
        mSensorRestartIsActive = false;
        mState = STATE_INACTIVE;
        mCallback = callback;
        mThresholdAngle = thresholdAngle;
        mRunningStats = new RunningSignalStats();
        mNumSufficientSamples = (int) Math.ceil(
                ((double)ORIENTATION_MEASUREMENT_DURATION_MILLIS / SAMPLING_INTERVAL_MILLIS));
        if (DEBUG) Slog.d(TAG, "mNumSufficientSamples = " + mNumSufficientSamples);
    }
}
 
Example 20
Source Project: divide   Source File: GCMBaseIntentService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Called from the broadcast receiver.
 * <p>
 * Will process the received intent, call handleMessage(), registered(),
 * etc. in background threads, with a wake lock, while keeping the service
 * alive.
 */
static void runIntentInService(Context context, Intent intent,
        String className) {
    synchronized (LOCK) {
        if (sWakeLock == null) {
            // This is called from BroadcastReceiver, there is no init.
            PowerManager pm = (PowerManager)
                    context.getSystemService(Context.POWER_SERVICE);
            sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                    WAKELOCK_KEY);
        }
    }
    Log.v(TAG, "Acquiring wakelock");
    sWakeLock.acquire();
    intent.setClassName(context, className);
    context.startService(intent);
}
 
Example 21
Source Project: NightWatch   Source File: BaseWatchFace.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
            .getDefaultDisplay();
    display.getSize(displaySize);
    wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Clock");

    specW = View.MeasureSpec.makeMeasureSpec(displaySize.x,
            View.MeasureSpec.EXACTLY);
    specH = View.MeasureSpec.makeMeasureSpec(displaySize.y,
            View.MeasureSpec.EXACTLY);
    sharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(this);
    sharedPrefs.registerOnSharedPreferenceChangeListener(this);
}
 
Example 22
Source Project: Telegram   Source File: AndroidUtilities.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static boolean shouldEnableAnimation() {
    if (Build.VERSION.SDK_INT < 26 || Build.VERSION.SDK_INT >= 28) {
        return true;
    }
    PowerManager powerManager = (PowerManager) ApplicationLoader.applicationContext.getSystemService(Context.POWER_SERVICE);
    if (powerManager.isPowerSaveMode()) {
        return false;
    }
    float scale = Settings.Global.getFloat(ApplicationLoader.applicationContext.getContentResolver(), Settings.Global.ANIMATOR_DURATION_SCALE, 1.0f);
    if (scale <= 0.0f) {
        return false;
    }
    return true;
}
 
Example 23
Source Project: titan-hotfix   Source File: JobIntentService.java    License: Apache License 2.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 24
Source Project: android-kiosk-mode   Source File: OnScreenOffReceiver.java    License: Apache License 2.0 5 votes vote down vote up
private void wakeUpDevice(AppContext context) {
    PowerManager.WakeLock wakeLock = context.getWakeLock(); // get WakeLock reference via AppContext
    if (wakeLock.isHeld()) {
        wakeLock.release(); // release old wake lock
    }

    // create a new wake lock...
    wakeLock.acquire();

    // ... and release again
    wakeLock.release();
}
 
Example 25
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
                                    BluetoothGattCharacteristic characteristic) {

    final PowerManager.WakeLock wl = JoH.getWakeLock("bt-meter-characterstic-change", 30000);
    try {
        processCharacteristicChange(gatt, characteristic);
        Bluetooth_CMD.poll_queue();
    } finally {
        JoH.releaseWakeLock(wl);
    }
}
 
Example 26
Source Project: cordova-plugin-screen-locker   Source File: ScreenLocker.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets the context of the Command. This can then be used to do things like
 * get file paths associated with the Activity.
 *
 * @param cordova The context of the main Activity.
 * @param webView The CordovaWebView Cordova is running in.
 */
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
    super.initialize(cordova, webView);

    powerManager = (PowerManager) cordova.getActivity().getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock((PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE), "TAG");

    Log.v(TAG, "Init ScreenLocker");
}
 
Example 27
Source Project: PhoneProfilesPlus   Source File: DataWrapper.java    License: Apache License 2.0 5 votes vote down vote up
private void pauseAllEventsForGlobalStopEvents() {
    final DataWrapper dataWrapper = copyDataWrapper();

    PPApplication.startHandlerThread(/*"DataWrapper.pauseAllEventsForGlobalStopEvents"*/);
    final Handler handler = new Handler(PPApplication.handlerThread.getLooper());
    handler.post(new Runnable() {
        @Override
        public void run() {

            PowerManager powerManager = (PowerManager) dataWrapper.context.getSystemService(Context.POWER_SERVICE);
            PowerManager.WakeLock wakeLock = null;
            try {
                if (powerManager != null) {
                    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":DataWrapper_pauseAllEventsFromMainThread");
                    wakeLock.acquire(10 * 60 * 1000);
                }

                //PPApplication.logE("PPApplication.startHandlerThread", "START run - from=DataWrapper.pauseAllEventsForGlobalStopEvents");

                dataWrapper.pauseAllEvents(true, false);

                //PPApplication.logE("PPApplication.startHandlerThread", "END run - from=DataWrapper.pauseAllEventsForGlobalStopEvents");
            } finally {
                if ((wakeLock != null) && wakeLock.isHeld()) {
                    try {
                        wakeLock.release();
                    } catch (Exception ignored) {}
                }
            }
        }
    });
}
 
Example 28
Source Project: NightWatch   Source File: Rest.java    License: GNU General Public License v3.0 5 votes vote down vote up
Rest(Context context) {
    mContext = context;
    prefs = PreferenceManager.getDefaultSharedPreferences(context);
    mUrl = prefs.getString("dex_collection_method", "https://{yoursite}.azurewebsites.net");
    PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    this.wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "rest wakelock");
    wakeLock.acquire();
}
 
Example 29
Source Project: sctalk   Source File: IMHeartBeatManager.java    License: Apache License 2.0 5 votes vote down vote up
public void sendHeartBeatPacket(){
    logger.d("heartbeat#reqSendHeartbeat");
    PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "teamtalk_heartBeat_wakelock");
    wl.acquire();
    try {
        final long timeOut = 5*1000;
        IMOther.IMHeartBeat imHeartBeat = IMOther.IMHeartBeat.newBuilder()
                .build();
        int sid = IMBaseDefine.ServiceID.SID_OTHER_VALUE;
        int cid = IMBaseDefine.OtherCmdID.CID_OTHER_HEARTBEAT_VALUE;
        IMSocketManager.instance().sendRequest(imHeartBeat,sid,cid,new Packetlistener(timeOut) {
            @Override
            public void onSuccess(Object response) {
                logger.d("heartbeat#心跳成功,链接保活");
            }

            @Override
            public void onFaild() {
                logger.w("heartbeat#心跳包发送失败");
                IMSocketManager.instance().onMsgServerDisconn();
            }

            @Override
            public void onTimeout() {
                logger.w("heartbeat#心跳包发送超时");
                IMSocketManager.instance().onMsgServerDisconn();
            }
        });
        logger.d("heartbeat#send packet to server");
    } finally {
        wl.release();
    }
}
 
Example 30
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

    if(!powerManager.isInteractive()) {
        PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "WeMessageNotificationWakeLock");
        wakeLock.acquire(5 * 1000);
    }

    weMessage.get().getNotificationManager().showFirebaseNotification(this, remoteMessage);
}