类android.os.PowerManager源码实例Demo

下面列出了怎么用android.os.PowerManager的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: flickr-uploader   文件: AlarmBroadcastReceiver.java
@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();
		}
	}
}
 
源代码2 项目: mollyim-android   文件: WakeLockUtil.java
/**
 * @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;
  }
}
 
源代码3 项目: Rey-MusicPlayer   文件: FadeMediaPlayer.java
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();
    }
}
 
源代码4 项目: cordova-rtmp-rtsp-stream   文件: RTSPActivity.java
@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();
}
 
源代码5 项目: turbo-editor   文件: Device.java
/**
 * 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();
}
 
源代码6 项目: LivePlayback   文件: IjkMediaPlayer.java
@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();
    }
}
 
@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();
}
 
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();
        }
 
源代码9 项目: Trigger   文件: TriggerLoop.java
@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();
}
 
源代码10 项目: Silence   文件: ApplicationMigrationService.java
@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();
  }
}
 
源代码11 项目: bcm-android   文件: LockManager.java
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);
}
 
源代码12 项目: android_9.0.0_r45   文件: NetworkStatsService.java
@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());
}
 
源代码13 项目: a   文件: SystemUtil.java
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) {
        }
    }
}
 
源代码14 项目: coursera-android   文件: MediaPlaybackService.java
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;
    }
}
 
源代码15 项目: DataLogger   文件: DataLoggerService.java
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));
    }
}
 
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);
}
 
/**
 * 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;
    }
}
 
源代码18 项目: xDrip   文件: BaseWatchFace.java
@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);
}
 
源代码19 项目: android_9.0.0_r45   文件: AnyMotionDetector.java
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);
    }
}
 
源代码20 项目: divide   文件: GCMBaseIntentService.java
/**
 * 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);
}
 
源代码21 项目: NightWatch   文件: BaseWatchFace.java
@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);
}
 
源代码22 项目: Telegram   文件: AndroidUtilities.java
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;
}
 
源代码23 项目: titan-hotfix   文件: JobIntentService.java
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);
}
 
源代码24 项目: android-kiosk-mode   文件: OnScreenOffReceiver.java
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();
}
 
源代码25 项目: xDrip-plus   文件: BluetoothGlucoseMeter.java
@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);
    }
}
 
/**
 * 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");
}
 
源代码27 项目: PhoneProfilesPlus   文件: DataWrapper.java
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) {}
                }
            }
        }
    });
}
 
源代码28 项目: NightWatch   文件: Rest.java
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();
}
 
源代码29 项目: sctalk   文件: IMHeartBeatManager.java
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();
    }
}
 
源代码30 项目: weMessage   文件: FirebaseNotificationService.java
@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);
}
 
 类所在包
 同包方法