android.os.PowerManager

Here are the examples of the java api android.os.PowerManager taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

447 Examples 7

19 Source : IjkMediaPlayer.java
with MIT License
from zzh12138

@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.clreplaced.getName());
    mWakeLock.setReferenceCounted(false);
    if (washeld) {
        mWakeLock.acquire();
    }
}

19 Source : DeviceUtils.java
with Apache License 2.0
from Zweihui

public static boolean isScreenOn(Context context) {
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    return pm.isScreenOn();
}

19 Source : FindMyPhonePlugin.java
with GNU General Public License v2.0
from ZorinOS

@PluginFactory.LoadablePlugin
public clreplaced FindMyPhonePlugin extends Plugin {

    public final static String PACKET_TYPE_FINDMYPHONE_REQUEST = "kdeconnect.findmyphone.request";

    private NotificationManager notificationManager;

    private int notificationId;

    private AudioManager audioManager;

    private MediaPlayer mediaPlayer;

    private int previousVolume = -1;

    private PowerManager powerManager;

    @Override
    public String getDisplayName() {
        switch(DeviceHelper.getDeviceType(context)) {
            case Tv:
                return context.getString(R.string.findmyphone_replacedle_tv);
            case Tablet:
                return context.getString(R.string.findmyphone_replacedle_tablet);
            case Phone:
                return context.getString(R.string.findmyphone_replacedle);
            default:
                return context.getString(R.string.findmyphone_replacedle);
        }
    }

    @Override
    public String getDescription() {
        return context.getString(R.string.findmyphone_description);
    }

    @Override
    public boolean onCreate() {
        notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationId = (int) System.currentTimeMillis();
        audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        Uri ringtone;
        String ringtoneString = prefs.getString(context.getString(R.string.findmyphone_preference_key_ringtone), "");
        if (ringtoneString.isEmpty()) {
            ringtone = Settings.System.DEFAULT_RINGTONE_URI;
        } else {
            ringtone = Uri.parse(ringtoneString);
        }
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(context, ringtone);
            // TODO: Deprecated use setAudioAttributes for API > 21
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
            mediaPlayer.setLooping(true);
            mediaPlayer.prepare();
        } catch (Exception e) {
            Log.e("FindMyPhoneActivity", "Exception", e);
            return false;
        }
        return true;
    }

    @Override
    public void onDestroy() {
        if (mediaPlayer.isPlaying()) {
            stopPlaying();
        }
        audioManager = null;
        mediaPlayer.release();
        mediaPlayer = null;
    }

    @Override
    public boolean onPacketReceived(NetworkPacket np) {
        if (Build.VERSION.SDK_INT < 29 || MyApplication.isInForeground()) {
            Intent intent = new Intent(context, FindMyPhoneActivity.clreplaced);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(FindMyPhoneActivity.EXTRA_DEVICE_ID, device.getDeviceId());
            context.startActivity(intent);
        } else {
            if (powerManager.isInteractive()) {
                startPlaying();
                showBroadcastNotification();
            } else {
                showActivityNotification();
            }
        }
        return true;
    }

    @RequiresApi(16)
    private void showBroadcastNotification() {
        Intent intent = new Intent(context, FindMyPhoneReceiver.clreplaced);
        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        intent.setAction(FindMyPhoneReceiver.ACTION_FOUND_IT);
        intent.putExtra(FindMyPhoneReceiver.EXTRA_DEVICE_ID, device.getDeviceId());
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        createNotification(pendingIntent);
    }

    private void showActivityNotification() {
        Intent intent = new Intent(context, FindMyPhoneActivity.clreplaced);
        intent.putExtra(FindMyPhoneActivity.EXTRA_DEVICE_ID, device.getDeviceId());
        PendingIntent pi = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        createNotification(pi);
    }

    private void createNotification(PendingIntent pendingIntent) {
        NotificationCompat.Builder notification = new NotificationCompat.Builder(context, NotificationHelper.Channels.HIGHPRIORITY);
        notification.setSmallIcon(R.drawable.ic_notification).setOngoing(false).setFullScreenIntent(pendingIntent, true).setPriority(NotificationCompat.PRIORITY_HIGH).setAutoCancel(true).setContentreplacedle(context.getString(R.string.findmyphone_found));
        notification.setGroup("BackgroundService");
        notificationManager.notify(notificationId, notification.build());
    }

    void startPlaying() {
        if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
            // Make sure we are heard even when the phone is silent, restore original volume later
            previousVolume = audioManager.getStreamVolume(AudioManager.STREAM_ALARM);
            audioManager.setStreamVolume(AudioManager.STREAM_ALARM, audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM), 0);
            mediaPlayer.start();
        }
    }

    void hideNotification() {
        notificationManager.cancel(notificationId);
    }

    void stopPlaying() {
        if (audioManager == null) {
            // The Plugin was destroyed (probably the device disconnected)
            return;
        }
        if (previousVolume != -1) {
            audioManager.setStreamVolume(AudioManager.STREAM_ALARM, previousVolume, 0);
        }
        mediaPlayer.stop();
        try {
            mediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    boolean isPlaying() {
        return mediaPlayer.isPlaying();
    }

    @Override
    public String[] getSupportedPacketTypes() {
        return new String[] { PACKET_TYPE_FINDMYPHONE_REQUEST };
    }

    @Override
    public String[] getOutgoingPacketTypes() {
        return new String[0];
    }

    @Override
    public boolean hreplacedettings() {
        return true;
    }

    @Override
    public PluginSettingsFragment getSettingsFragment(Activity activity) {
        return FindMyPhoneSettingsFragment.newInstance(getPluginKey());
    }
}

19 Source : InstrumentationUiAutomatorBridge.java
with MIT License
from ZhongAnTech

@Override
public boolean isScreenOn() {
    PowerManager pm = (PowerManager) mContext.getSystemService(Service.POWER_SERVICE);
    return pm.isScreenOn();
}

19 Source : GrblActivity.java
with GNU General Public License v3.0
from zeevy

private void checkPowerManagement() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        if (pm != null && !pm.isIgnoringBatteryOptimizations(getPackageName())) {
            new AlertDialog.Builder(this).setreplacedle(getString(R.string.text_power_management_warning_replacedle)).setMessage(getString(R.string.text_power_management_warning_description)).setPositiveButton(getString(R.string.text_settings), new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    try {
                        Intent myIntent = new Intent();
                        myIntent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
                        startActivity(myIntent);
                    } catch (RuntimeException ignored) {
                    }
                }
            }).setNegativeButton(getString(R.string.text_cancel), null).setCancelable(false).show();
        }
    }
}

19 Source : Utils.java
with Apache License 2.0
from yiwent

public static void acquireWakeLock(Context context) {
    if (null == mWakeLock) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
        mWakeLock.setReferenceCounted(true);
        if (null != mWakeLock) {
            mWakeLock.acquire();
        }
    }
}

19 Source : LocalService.java
with Apache License 2.0
from yangchong211

@Override
public void onCreate() {
    super.onCreate();
    if (mBinder == null) {
        mBinder = new GuardBinder();
    }
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mIsPause = pm != null && pm.isScreenOn();
    if (mHandler == null) {
        mHandler = new Handler();
    }
}

19 Source : OnePixelActivity.java
with Apache License 2.0
from yangchong211

/**
 * 检测屏幕是否
 */
private void checkScreenOn() {
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    // 如果设备处于交互状态,则返回true。
    boolean isScreenOn;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT_WATCH) {
        // 20以上,建议用isInteractive方法
        isScreenOn = pm != null && pm.isInteractive();
    } else {
        isScreenOn = pm != null && pm.isScreenOn();
    }
    if (isScreenOn) {
        finish();
    }
}

19 Source : AppLogService.java
with Apache License 2.0
from yangchong211

private void init() {
    // 日志文件在内存中的路径(日志文件在安装目录中的路径)
    LOG_PATH_MEMORY_DIR = getFilesDir().getAbsolutePath() + File.separator + "log";
    // LOG_PATH_MEMORY_DIR = FileSaveUtils.getLocalRootSavePathDir("memory") + File.separator + "log";
    // 本服务产生的日志,记录日志服务开启失败信息
    String LOG_SERVICE_LOG_PATH = LOG_PATH_MEMORY_DIR + File.separator + logServiceLogName;
    // 日志文件在sdcard中的路径
    LOG_PATH_SDCARD_DIR = FileSaveUtils.getLocalRootSavePathDir(FileSaveUtils.logger) + File.separator + "log";
    createLogDir();
    try {
        // 先判断文件是否又创建,没有则创建,避免异常崩溃
        if (new File(LOG_SERVICE_LOG_PATH).exists()) {
            FileOutputStream fos = new FileOutputStream(LOG_SERVICE_LOG_PATH, true);
            writer = new OutputStreamWriter(fos, UNICODE);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Log.e(TAG, e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        Log.e(TAG, e.getMessage(), e);
    }
    // 获取PowerManager管理者
    PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
    if (pm != null) {
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    }
    // 当前的日志记录类型
    CURR_LOG_TYPE = getCurrLogType();
    Log.i(TAG, "LogService onCreate");
}

19 Source : OnePixelActivity.java
with Apache License 2.0
from xuexiangjys

private void checkScreenOn() {
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    boolean isScreenOn = pm != null && pm.isScreenOn();
    if (isScreenOn) {
        finish();
    }
}

19 Source : NotificationService.java
with Apache License 2.0
from XJIOP

public clreplaced NotificationService extends NotificationListenerService {

    private static final String TAG = "DBG | NService";

    public static NotificationService notificationService;

    public static int NOTIFICATION_COUNT;

    public static int INDICATOR_COUNT;

    private Handler handler;

    private PowerManager powerManager;

    private PowerManager.WakeLock wakeLock;

    private PowerManager.WakeLock wakeLockTos;

    @Override
    public void onCreate() {
        // Log.d(TAG, "onCreate");
        super.onCreate();
        NOTIFICATION_COUNT = 0;
        INDICATOR_COUNT = 0;
        notificationService = this;
        handler = new Handler();
        Application.getAppContext().registerScreenPowerReceiver();
        powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (powerManager != null) {
            wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getPackageName() + ":indicator");
            wakeLock.setReferenceCounted(false);
            wakeLockTos = powerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, getPackageName() + ":turn_on_screen");
            wakeLockTos.setReferenceCounted(false);
        }
    }

    @Override
    public void onDestroy() {
        // Log.d(TAG, "onDestroy");
        NOTIFICATION_COUNT = 0;
        INDICATOR_COUNT = 0;
        notificationService = null;
        if (wakeLock != null && wakeLock.isHeld())
            wakeLock.release();
        if (wakeLockTos != null && wakeLockTos.isHeld())
            wakeLockTos.release();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        if (!Helper.isAccessibilityPermission())
            Application.getAppContext().unregisterScreenPowerReceiver();
        super.onDestroy();
    }

    @Override
    public void onListenerConnected() {
    // Log.d(TAG, "onListenerConnected");
    }

    @Override
    public void onListenerDisconnected() {
    // Log.d(TAG, "onListenerDisconnected");
    }

    @Override
    public void onNotificationPosted(final StatusBarNotification sbn) {
        // Log.d(TAG, "onNotificationPosted =  " + sbn);
        // Log.d(TAG, " - notification package = " + sbn.getPackageName());
        // Log.d(TAG, " - notification content = " + sbn.getNotification().extras.getString(Notification.EXTRA_TEXT));
        // Log.d(TAG, " - notification is ongoing = " + sbn.isOngoing());
        // Log.d(TAG, " - notification id = " + sbn.getId());
        // Log.d(TAG, " - notification category = " + sbn.getNotification().category);
        // Log.d(TAG, " - notification flags = " + sbn.getNotification().flags);
        // Log.d(TAG, " - notification key = " + sbn.getKey());
        if (newNotification(sbn))
            startIndicator();
    }

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        // Log.d(TAG, "onNotificationRemoved = " + sbn);
        // Log.d(TAG, " - notification package = " + sbn.getPackageName());
        // Log.d(TAG, " - notification content = " + sbn.getNotification().extras.getString(Notification.EXTRA_TEXT));
        // Log.d(TAG, " - notification is ongoing = " + sbn.isOngoing());
        // Log.d(TAG, " - notification id = " + sbn.getId());
        // Log.d(TAG, " - notification category = " + sbn.getNotification().category);
        // Log.d(TAG, " - notification flags = " + sbn.getNotification().flags);
        // Log.d(TAG, " - notification key = " + sbn.getKey());
        if (sbn == null)
            return;
        // prepare next indicator
        if (sbn.getId() == INDICATOR_NOTIFICATION_ID) {
            startIndicator();
            return;
        }
        // ignore ongoing (this notifications cannot be dismissed)
        if (sbn.isOngoing())
            return;
        // ignore duplicate
        if ((sbn.getNotification().flags & Notification.FLAG_GROUP_SUMMARY) != 0) {
            // Log.d(TAG, " - ignore this notification");
            return;
        }
        // category filter
        String cat = sbn.getNotification().category == null ? "undefined" : sbn.getNotification().category;
        if (!ALLOWED_CATEGORY.contains(cat))
            return;
        if (NOTIFICATION_COUNT > 0) {
            NOTIFICATION_COUNT--;
            if (WAKE_LOCK && wakeLock != null && wakeLock.isHeld())
                wakeLock.release();
            if (NOTIFICATION_COUNT == 0) {
                if (handler != null)
                    handler.removeCallbacksAndMessages(null);
            }
        }
    }

    public void startIndicator() {
        // Log.d(TAG, "startIndicator | NOTIFICATION_COUNT: " + NOTIFICATION_COUNT + " | INDICATOR_COUNT: " + INDICATOR_COUNT);
        // Log.d(TAG, " - wakeLock isHeld: " + wakeLock.isHeld());
        if (NOTIFICATION_COUNT == 0)
            return;
        if (isAmount())
            return;
        if (!ANY_TIME) {
            LocalTime now = LocalTime.now();
            boolean isSchedule = now.isAfter(START_TIME) && now.isBefore(END_TIME);
            if (!isSchedule) {
                // Log.d(TAG, " - stopped by schedule");
                return;
            }
        }
        if (!isScreenOff())
            return;
        if (handler != null) {
            INDICATOR_COUNT++;
            if (WAKE_LOCK && wakeLock != null && !wakeLock.isHeld())
                wakeLock.acquire((INTERVAL + 5) * 1000);
            handler.removeCallbacksAndMessages(null);
            handler.postDelayed(new Runnable() {

                public void run() {
                    if (NOTIFICATION_COUNT > 0) {
                        if (TURN_ON_SCREEN) {
                            try {
                                Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                                Ringtone ringtone = RingtoneManager.getRingtone(NotificationService.this, uri);
                                ringtone.play();
                            } catch (Exception ignored) {
                            }
                            if (wakeLockTos != null && !wakeLockTos.isHeld()) {
                                try {
                                    wakeLockTos.acquire();
                                } finally {
                                    wakeLockTos.release();
                                }
                            }
                        } else {
                            sendBroadcast(new Intent(NotificationService.this, NotificationReceiver.clreplaced));
                        }
                    }
                }
            }, INTERVAL * 1000);
        }
    }

    public void stopIndicator() {
        // Log.d(TAG, "stopAlert | NOTIFICATION_COUNT: " + NOTIFICATION_COUNT);
        // Log.d(TAG, " - wakeLock isHeld: " + wakeLock.isHeld());
        NOTIFICATION_COUNT = 0;
        INDICATOR_COUNT = 0;
        if (WAKE_LOCK && wakeLock != null && wakeLock.isHeld())
            wakeLock.release();
        if (handler != null)
            handler.removeCallbacksAndMessages(null);
    }

    private boolean newNotification(StatusBarNotification sbn) {
        if (sbn == null)
            return false;
        // ignore indicator
        if (sbn.getId() == INDICATOR_NOTIFICATION_ID)
            return false;
        // ignore ongoing (this notifications cannot be dismissed)
        if (sbn.isOngoing())
            return false;
        // ignore duplicate
        if ((sbn.getNotification().flags & Notification.FLAG_GROUP_SUMMARY) != 0) {
            // Log.d(TAG, " - ignore this notification");
            return false;
        }
        // category filter
        String cat = sbn.getNotification().category == null ? "undefined" : sbn.getNotification().category;
        if (!ALLOWED_CATEGORY.contains(cat))
            return false;
        NOTIFICATION_COUNT++;
        INDICATOR_COUNT = 0;
        return true;
    }

    public void recountNotifications() {
        NOTIFICATION_COUNT = 0;
        INDICATOR_COUNT = 0;
        if (!RESET_WHEN_SCREEN_TURN_ON) {
            for (StatusBarNotification sbn : getActiveNotifications()) {
                newNotification(sbn);
            }
        }
    }

    private boolean isAmount() {
        return AMOUNT > 0 && INDICATOR_COUNT == AMOUNT;
    }

    private boolean isScreenOff() {
        return !isScreenON && powerManager != null && !powerManager.isInteractive();
    }
}

19 Source : KeyService.java
with Apache License 2.0
from XJIOP

public clreplaced KeyService extends AccessibilityService {

    private final String TAG = "DBG | KeyService";

    private int CLICK_THRESHOLD = 250;

    private long CLICK_DELAY;

    private PowerManager powerManager;

    private PowerManager.WakeLock wakeLock;

    @Override
    public void onCreate() {
        // Log.d(TAG, "onCreate");
        super.onCreate();
        Application.getAppContext().registerScreenPowerReceiver();
        powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (powerManager != null) {
            wakeLock = powerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, getPackageName() + ":double_tap");
            wakeLock.setReferenceCounted(false);
        }
    }

    @Override
    public void onDestroy() {
        if (wakeLock != null && wakeLock.isHeld())
            wakeLock.release();
        if (!Helper.isNotificationPermission())
            Application.getAppContext().unregisterScreenPowerReceiver();
        super.onDestroy();
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
    // Log.d(TAG, "onAccessibilityEvent: " + event);
    }

    @Override
    public void onInterrupt() {
    // Log.d(TAG, "onInterrupt");
    }

    @Override
    protected boolean onKeyEvent(KeyEvent event) {
        // Log.d(TAG, "onKeyEvent: " + event);
        boolean result = false;
        if (event.getKeyCode() == KeyEvent.KEYCODE_F4 && isScreenOff()) {
            if (result = (SINGLE_TAP || doubleClick())) {
                if (wakeLock != null && !wakeLock.isHeld()) {
                    try {
                        wakeLock.acquire();
                    } finally {
                        wakeLock.release();
                    }
                    if (VIBRATION) {
                        Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                        if (vibrator != null) {
                            vibrator.vibrate(VibrationEffect.createOneShot(1, VibrationEffect.DEFAULT_AMPLITUDE));
                        }
                    }
                }
            }
        }
        return result || super.onKeyEvent(event);
    }

    private boolean doubleClick() {
        boolean result = false;
        long thisTime = System.currentTimeMillis();
        if ((thisTime - CLICK_DELAY) < CLICK_THRESHOLD) {
            // Log.d(TAG, "doubleClick");
            CLICK_DELAY = -1;
            result = true;
        } else {
            CLICK_DELAY = thisTime;
        }
        return result;
    }

    private boolean isScreenOff() {
        return !isScreenON && powerManager != null && !powerManager.isInteractive();
    }
}

19 Source : PowerManagerCompat.java
with GNU General Public License v3.0
from XecureIT

public static boolean isDeviceIdleMode(@NonNull PowerManager powerManager) {
    if (Build.VERSION.SDK_INT >= 23) {
        return powerManager.isDeviceIdleMode();
    }
    return false;
}

19 Source : WakeLock.java
with Apache License 2.0
from wzx54321

/**
 * <!-- 亮屏 -->
 * require <uses-permission android:name="android.permission.WAKE_LOCK"/>
 *
 * @date 2014-11-04
 */
public clreplaced WakeLock {

    PowerManager powerManager;

    PowerManager.WakeLock wakeLock;

    public WakeLock(Context context, String tag) {
        // //获取电源的服务 声明电源管理器
        powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.FULL_WAKE_LOCK, tag);
    }

    /**
     * Call requires API level 7
     */
    public boolean isScreenOn() {
        return powerManager.isScreenOn();
    }

    public void turnScreenOn() {
        // 点亮亮屏
        Log.i("Log : ", "PowerManager.WakeLock : wakeLock.isHeld: " + wakeLock.isHeld());
        if (!wakeLock.isHeld()) {
            Log.i("Log : ", "PowerManager.WakeLock : 点亮屏幕");
            wakeLock.acquire();
        }
    }

    public void turnScreenOff() {
        // 释放亮屏
        Log.i("Log : ", "PowerManager.WakeLock : wakeLock.isHeld: " + wakeLock.isHeld());
        if (wakeLock.isHeld()) {
            Log.i("Log : ", "PowerManager.WakeLock : 灭掉屏幕");
            try {
                wakeLock.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void release() {
        if (wakeLock != null && wakeLock.isHeld()) {
            try {
                wakeLock.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public PowerManager.WakeLock getWakeLock() {
        return wakeLock;
    }

    public void setWakeLock(PowerManager.WakeLock wakeLock) {
        this.wakeLock = wakeLock;
    }

    public PowerManager getPowerManager() {
        return powerManager;
    }

    public void setPowerManager(PowerManager powerManager) {
        this.powerManager = powerManager;
    }
}

19 Source : WakeLock.java
with Apache License 2.0
from wzx54321

public void setPowerManager(PowerManager powerManager) {
    this.powerManager = powerManager;
}

19 Source : CallFeatures.java
with Apache License 2.0
from WrBug

private void onCallsManagerCreated(Object callsManager) {
    if (DEBUG)
        log("onCallsManagerCreated()");
    mContext = (Context) XposedHelpers.getObjectField(callsManager, "mContext");
    mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
    mVibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
    mHandler = new Handler();
    PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
}

19 Source : ModVolumeKeySkipTrack.java
with Apache License 2.0
from WrBug

public clreplaced ModVolumeKeySkipTrack {

    private static final String TAG = "GB:ModVolumeKeySkipTrack";

    private static final boolean DEBUG = BuildConfig.DEBUG;

    private static boolean mIsLongPress = false;

    private static boolean allowSkipTrack;

    private static AudioManager mAudioManager;

    private static PowerManager mPowerManager;

    private static boolean mShoudTriggerWakeUp;

    private static void log(String message) {
        XposedBridge.log(TAG + ": " + message);
    }

    static void initAndroid(final XSharedPreferences prefs, final ClreplacedLoader clreplacedLoader) {
        try {
            if (DEBUG)
                log("init");
            updatePreference(prefs);
            Clreplaced<?> clreplacedPhoneWindowManager = findClreplaced("com.android.server.policy.PhoneWindowManager", clreplacedLoader);
            XposedBridge.hookAllConstructors(clreplacedPhoneWindowManager, handleConstructPhoneWindowManager);
            // take advantage of screenTurnedOff method for refreshing state of allowSkipTrack preference
            findAndHookMethod(clreplacedPhoneWindowManager, "screenTurnedOff", new XC_MethodHook() {

                @Override
                protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                    if (DEBUG)
                        log("screenTurnedOff");
                    updatePreference(prefs);
                }
            });
            findAndHookMethod(clreplacedPhoneWindowManager, "interceptKeyBeforeQueueing", KeyEvent.clreplaced, int.clreplaced, handleInterceptKeyBeforeQueueing);
        } catch (Throwable t) {
            XposedBridge.log(t);
        }
    }

    private static XC_MethodHook handleInterceptKeyBeforeQueueing = new XC_MethodHook() {

        @Override
        protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
            if (!allowSkipTrack)
                return;
            final KeyEvent event = (KeyEvent) param.args[0];
            final int keyCode = event.getKeyCode();
            initManagers((Context) XposedHelpers.getObjectField(param.thisObject, "mContext"));
            if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) && (event.getFlags() & KeyEvent.FLAG_FROM_SYSTEM) != 0 && !mPowerManager.isInteractive() && mAudioManager != null && mAudioManager.isMusicActive()) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    mIsLongPress = false;
                    handleVolumeLongPress(param.thisObject, keyCode);
                } else {
                    handleVolumeLongPressAbort(param.thisObject);
                    if (!mIsLongPress) {
                        if (mShoudTriggerWakeUp) {
                            wakeUp();
                        } else {
                            mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, keyCode == KeyEvent.KEYCODE_VOLUME_UP ? AudioManager.ADJUST_RAISE : AudioManager.ADJUST_LOWER, 0);
                        }
                    }
                }
                param.setResult(0);
                return;
            }
        }
    };

    private static XC_MethodHook handleConstructPhoneWindowManager = new XC_MethodHook() {

        @Override
        protected void afterHookedMethod(final MethodHookParam param) throws Throwable {
            /**
             * When a volumeup-key longpress expires, skip songs based on key press
             */
            Runnable mVolumeUpLongPress = new Runnable() {

                @Override
                public void run() {
                    // set the long press flag to true
                    mIsLongPress = true;
                    // Shamelessly copied from Kmobs LockScreen controls, works for Pandora, etc...
                    sendMediaButtonEvent(param.thisObject, KeyEvent.KEYCODE_MEDIA_NEXT);
                }
            };
            /**
             * When a volumedown-key longpress expires, skip songs based on key press
             */
            Runnable mVolumeDownLongPress = new Runnable() {

                @Override
                public void run() {
                    // set the long press flag to true
                    mIsLongPress = true;
                    // Shamelessly copied from Kmobs LockScreen controls, works for Pandora, etc...
                    sendMediaButtonEvent(param.thisObject, KeyEvent.KEYCODE_MEDIA_PREVIOUS);
                }
            };
            setAdditionalInstanceField(param.thisObject, "mVolumeUpLongPress", mVolumeUpLongPress);
            setAdditionalInstanceField(param.thisObject, "mVolumeDownLongPress", mVolumeDownLongPress);
        }
    };

    private static void initManagers(Context ctx) {
        if (mAudioManager == null) {
            mAudioManager = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
        }
        if (mPowerManager == null) {
            mPowerManager = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
        }
    }

    private static void sendMediaButtonEvent(Object phoneWindowManager, int code) {
        long eventtime = SystemClock.uptimeMillis();
        Intent keyIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
        KeyEvent keyEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_DOWN, code, 0);
        keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
        dispatchMediaButtonEvent(keyEvent);
        keyEvent = KeyEvent.changeAction(keyEvent, KeyEvent.ACTION_UP);
        keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
        dispatchMediaButtonEvent(keyEvent);
    }

    private static void dispatchMediaButtonEvent(KeyEvent keyEvent) {
        try {
            mAudioManager.dispatchMediaKeyEvent(keyEvent);
        } catch (Throwable t) {
            XposedBridge.log(t);
        }
    }

    private static void handleVolumeLongPress(Object phoneWindowManager, int keycode) {
        Handler mHandler = (Handler) getObjectField(phoneWindowManager, "mHandler");
        Runnable mVolumeUpLongPress = (Runnable) getAdditionalInstanceField(phoneWindowManager, "mVolumeUpLongPress");
        Runnable mVolumeDownLongPress = (Runnable) getAdditionalInstanceField(phoneWindowManager, "mVolumeDownLongPress");
        mHandler.postDelayed(keycode == KeyEvent.KEYCODE_VOLUME_UP ? mVolumeUpLongPress : mVolumeDownLongPress, ViewConfiguration.getLongPressTimeout());
    }

    private static void handleVolumeLongPressAbort(Object phoneWindowManager) {
        Handler mHandler = (Handler) getObjectField(phoneWindowManager, "mHandler");
        Runnable mVolumeUpLongPress = (Runnable) getAdditionalInstanceField(phoneWindowManager, "mVolumeUpLongPress");
        Runnable mVolumeDownLongPress = (Runnable) getAdditionalInstanceField(phoneWindowManager, "mVolumeDownLongPress");
        mHandler.removeCallbacks(mVolumeUpLongPress);
        mHandler.removeCallbacks(mVolumeDownLongPress);
    }

    private static void updatePreference(final XSharedPreferences prefs) {
        prefs.reload();
        allowSkipTrack = prefs.getBoolean(GravityBoxSettings.PREF_KEY_VOL_MUSIC_CONTROLS, false);
        mShoudTriggerWakeUp = "enabled".equals(prefs.getString(GravityBoxSettings.PREF_KEY_VOLUME_ROCKER_WAKE, "default")) && prefs.getBoolean(GravityBoxSettings.PREF_KEY_VOLUME_ROCKER_WAKE_ALLOW_MUSIC, false);
        if (DEBUG)
            log("allowSkipTrack = " + allowSkipTrack + "; " + "mShoudTriggerWakeUp=" + mShoudTriggerWakeUp);
    }

    private static void wakeUp() {
        long ident = Binder.clearCallingIdenreplacedy();
        try {
            XposedHelpers.callMethod(mPowerManager, "wakeUp", SystemClock.uptimeMillis());
        } finally {
            Binder.restoreCallingIdenreplacedy(ident);
        }
    }
}

19 Source : TimerTaskService.java
with Apache License 2.0
from wojiaonia

private void acquireWakeLock() {
    if (null == wakeLock) {
        PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "PostLocationService");
        if (null != wakeLock) {
            wakeLock.acquire();
        }
    }
}

19 Source : NoiseAlert.java
with Apache License 2.0
from velmurugan35

/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Defined SoundLevelView in main.xml file
    setContentView(R.layout.main);
    mStatusView = (TextView) findViewById(R.id.status);
    tv_noice = (TextView) findViewById(R.id.tv_noice);
    bar = (ProgressBar) findViewById(R.id.progressBar1);
    // Used to record voice
    mSensor = new SoundMeter();
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "NoiseAlert");
}

19 Source : Shadowsocks.java
with Apache License 2.0
from vaycore

public boolean ignoreBatteryOptimization() {
    // TODO do . ignore_battery_optimization ......................................
    // http://blog.csdn.net/laxian2009/article/details/52474214
    boolean exception;
    try {
        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (powerManager == null) {
            throw new Throwable("power manager get is null");
        }
        String packageName = getPackageName();
        boolean hasIgnored = true;
        if (Build.VERSION.SDK_INT >= 23) {
            hasIgnored = powerManager.isIgnoringBatteryOptimizations(packageName);
        }
        if (!hasIgnored) {
            Intent intent = new Intent();
            intent.setAction(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(android.net.Uri.parse("package:" + packageName));
            startActivity(intent);
        }
        exception = false;
    } catch (Throwable e) {
        exception = true;
    }
    if (exception) {
        try {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            ComponentName cn = new ComponentName("com.android.settings", "com.android.com.settings.Settings@HighPowerApplicationsActivity");
            intent.setComponent(cn);
            startActivity(intent);
            exception = false;
        } catch (Throwable e) {
            exception = true;
        }
    }
    return exception;
}

19 Source : CommonUtil.java
with MIT License
from TuyaInc

public static PowerManager.WakeLock acquireLock(Context context) {
    if (wakeLock == null || !wakeLock.isHeld()) {
        PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "tuya");
        wakeLock.setReferenceCounted(true);
        wakeLock.acquire();
    }
    return wakeLock;
}

19 Source : ActorService.java
with Apache License 2.0
from truecaller

@Override
public void onCreate() {
    super.onCreate();
    mThread = new HandlerThread(mServiceName);
    mThread.start();
    PowerManager.WakeLock wl = null;
    if (mUseWakelocks) {
        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, mServiceName);
        wl.setReferenceCounted(false);
    }
    ServiceMessageSender messageSender = new ServiceMessageSender(new ServiceActorHandler(mThread.getLooper(), mStopDelay, wl));
    mBinder = new Binder();
    mBinder.attachInterface(messageSender, LOCAL_SENDER_INTERFACE);
}

19 Source : UAStateReceiver.java
with GNU General Public License v3.0
from treasure-lau

// -------
// Public configuration for receiver
// -------
public void initService(PjSipService srv) {
    pjService = srv;
    notificationManager = pjService.service.notificationManager;
    if (handlerThread == null) {
        handlerThread = new HandlerThread("UAStateAsyncWorker");
        handlerThread.start();
    }
    if (msgHandler == null) {
        msgHandler = new WorkerHandler(handlerThread.getLooper(), this);
    }
    if (eventLock == null) {
        PowerManager pman = (PowerManager) pjService.service.getSystemService(Context.POWER_SERVICE);
        eventLock = pman.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "com.csipsimple.inEventLock");
        eventLock.setReferenceCounted(true);
    }
    if (ongoingCallLock == null) {
        PowerManager pman = (PowerManager) pjService.service.getSystemService(Context.POWER_SERVICE);
        ongoingCallLock = pman.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "com.csipsimple.ongoingCallLock");
        ongoingCallLock.setReferenceCounted(false);
    }
}

19 Source : EarlyLockModule.java
with GNU General Public License v3.0
from treasure-lau

/**
 * @author r3gis3r
 */
public clreplaced EarlyLockModule implements PjsipModule {

    private static final String THIS_FILE = "EarlyLockModule";

    private EarlyLocker locker;

    private PowerManager pm;

    /*
     * (non-Javadoc)
     * @see
     * com.csipsimple.pjsip.PjSipService.PjsipModule#setContext(android.content
     * .Context)
     */
    @Override
    public void setContext(Context ctxt) {
        pm = (PowerManager) ctxt.getSystemService(Context.POWER_SERVICE);
    }

    /*
     * (non-Javadoc)
     * @see com.csipsimple.pjsip.PjSipService.PjsipModule#onBeforeStartPjsip()
     */
    @Override
    public void onBeforeStartPjsip() {
        pjsua.mod_earlylock_init();
        locker = new EarlyLocker();
        pjsua.mod_earlylock_set_callback(locker);
    }

    /*
     * (non-Javadoc)
     * @see com.csipsimple.pjsip.PjSipService.PjsipModule#
     * onBeforeAccountStartRegistration(int, com.csipsimple.api.SipProfile)
     */
    @Override
    public void onBeforeAccountStartRegistration(int pjId, SipProfile acc) {
    // Nothing to do here
    }

    private clreplaced WorkLocker extends Thread {

        private final long lockTime;

        private WakeLock wl;

        WorkLocker(long time) {
            lockTime = time;
            wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "com.csipsimple.earlylock");
            wl.acquire();
        }

        /*
         * (non-Javadoc)
         * @see java.lang.Thread#run()
         */
        @Override
        public void run() {
            try {
                Log.d(THIS_FILE, "We entered a partial early lock");
                sleep(lockTime);
            } catch (InterruptedException e) {
                Log.e(THIS_FILE, "Unable to lock");
            }
            wl.release();
        }
    }

    private clreplaced EarlyLocker extends EarlyLockCallback {

        public void on_create_early_lock() {
            WorkLocker wl = new WorkLocker(2000);
            wl.start();
        }
    }
}

19 Source : GpsdForwarderService.java
with MIT License
from tiagoshibata

@Override
public void onCreate() {
    super.onCreate();
    try {
        nmeaMessageListener.start((LocationManager) getSystemService(Context.LOCATION_SERVICE), this, this);
    } catch (RuntimeException e) {
        log(e.getMessage());
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        // Setup notification channel
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL, getString(R.string.notification_channel_name), NotificationManager.IMPORTANCE_LOW));
    }
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "GPSdClient:GPSdStreaming");
    wakeLock.acquire();
}

19 Source : WidgetUtils.java
with GNU General Public License v3.0
from thuryn

public static boolean isInteractive(Context context) {
    PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
        return powerManager.isInteractive();
    } else {
        return powerManager.isScreenOn();
    }
}

19 Source : AppWakeUpManager.java
with GNU General Public License v3.0
from thuryn

public clreplaced AppWakeUpManager extends Service {

    private static final String TAG = "AppWakeUpManager";

    public static final int WAKE_UP = 1;

    public static final int FALL_DOWN = 2;

    public static final int SOURCE_CURRENT_WEATHER = 1;

    public static final int SOURCE_WEATHER_FORECAST = 2;

    public static final int SOURCE_NOTIFICATION = 3;

    public static final int SOURCE_LOCATION_UPDATE = 4;

    private static final long WAKEUP_TIMEOUT_IN_MS = 30000L;

    private PowerManager.WakeLock wakeLock;

    private PowerManager powerManager;

    private static List<Integer> wakeUpSources = new ArrayList<>();

    private Lock wakeUpSourcesLock = new ReentrantLock();

    final Messenger messenger = new Messenger(new PowerUpMessageHandler());

    Handler timerWakeUpHandler = new Handler();

    Runnable timerWakeUpRunnable = new Runnable() {

        @Override
        public void run() {
            wakeDown();
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return messenger.getBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return false;
    }

    private void startWakeUp(Integer wakeUpSource) {
        wakeUpSourcesLock.lock();
        try {
            if (!wakeUpSources.contains(wakeUpSource)) {
                wakeUpSources.add(wakeUpSource);
            }
            appendLogWakeupSources(getBaseContext(), TAG, "startWakeUp:", wakeUpSources);
            if ((wakeLock != null) && wakeLock.isHeld()) {
                appendLog(getBaseContext(), TAG, "wakeUp started");
                return;
            }
            wakeUp();
            appendLog(getBaseContext(), TAG, "start wakeup");
        } catch (Exception e) {
            appendLog(getBaseContext(), TAG, "Exception starting wakeup", e);
        } finally {
            wakeUpSourcesLock.unlock();
        }
    }

    private void stopWakeUp(Integer wakeUpSource) {
        wakeUpSourcesLock.lock();
        try {
            if (wakeUpSources.contains(wakeUpSource)) {
                wakeUpSources.remove(wakeUpSource);
            }
            appendLogWakeupSources(getBaseContext(), TAG, "startWakeUp:", wakeUpSources);
            if (!wakeUpSources.isEmpty()) {
                return;
            }
            wakeDown();
        } catch (Exception e) {
            appendLog(getBaseContext(), TAG, "Exception stoping wakeup", e);
        } finally {
            wakeUpSourcesLock.unlock();
        }
    }

    public void wakeDown() {
        timerWakeUpHandler.removeCallbacksAndMessages(null);
        appendLog(getBaseContext(), TAG, "wakeDown wakeLock:", wakeLock);
        if ((wakeLock != null) && wakeLock.isHeld()) {
            try {
                wakeLock.release();
                appendLog(getBaseContext(), TAG, "wakeLock released");
            } catch (Throwable th) {
            // ignoring this exception, probably wakeLock was already released
            }
        }
    }

    public void wakeUp() {
        appendLog(getBaseContext(), TAG, "powerManager:", powerManager);
        boolean isInUse;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
            isInUse = powerManager.isInteractive();
        } else {
            isInUse = powerManager.isScreenOn();
        }
        if (isInUse || ((wakeLock != null) && wakeLock.isHeld())) {
            appendLog(getBaseContext(), TAG, "lock is held");
            return;
        }
        timerWakeUpHandler.postDelayed(timerWakeUpRunnable, WAKEUP_TIMEOUT_IN_MS);
        String wakeUpStrategy = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString(Constants.KEY_WAKE_UP_STRATEGY, "nowakeup");
        appendLog(getBaseContext(), TAG, "wakeLock:wakeUpStrategy:", wakeUpStrategy);
        if (wakeLock != null) {
            try {
                wakeLock.release();
            } catch (Throwable th) {
            // ignoring this exception, probably wakeLock was already released
            }
        }
        if ("nowakeup".equals(wakeUpStrategy)) {
            return;
        }
        int powerLockID;
        if ("wakeupfull".equals(wakeUpStrategy)) {
            powerLockID = PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP;
        } else {
            powerLockID = PowerManager.PARTIAL_WAKE_LOCK;
        }
        appendLog(getBaseContext(), TAG, "wakeLock:powerLockID:", powerLockID);
        wakeLock = powerManager.newWakeLock(powerLockID, "YourLocalWeather:PowerLock");
        appendLog(getBaseContext(), TAG, "wakeLock:", wakeLock, ":", wakeLock.isHeld());
        if (!wakeLock.isHeld()) {
            wakeLock.acquire();
        }
        appendLog(getBaseContext(), TAG, "wakeLock acquired");
    }

    private clreplaced PowerUpMessageHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            int wakeUpSource = msg.arg1;
            appendLog(getBaseContext(), TAG, "handleMessage:", msg.what, ":", wakeUpSource);
            switch(msg.what) {
                case WAKE_UP:
                    startWakeUp(wakeUpSource);
                    break;
                case FALL_DOWN:
                    stopWakeUp(wakeUpSource);
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }
}

19 Source : WakeLockServiceImpl.java
with GNU Affero General Public License v3.0
from threema-ch

private boolean execute() {
    if (this.acquiredSessionIds.size() > 0) {
        if (this.wakeLock == null) {
            logger.debug("create new wakelock");
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
        }
        if (!this.wakeLock.isHeld()) {
            if (ConfigUtils.isNokiaDevice()) {
                // do not hold wake lock for longer than 15 minutes to prevent evenwell power "saver" from killing the app
                this.wakeLock.acquire(15 * DateUtils.MINUTE_IN_MILLIS);
            } else {
                this.wakeLock.acquire();
            }
            logger.debug("acquired");
        } else {
            logger.debug("already acquired");
        }
        return true;
    } else {
        if (this.wakeLock != null && this.wakeLock.isHeld()) {
            this.wakeLock.release();
            // to be sure, remove the wakelock
            this.wakeLock = null;
            logger.debug("released");
        } else {
            logger.debug("already released");
        }
        return false;
    }
}

19 Source : RuntimeUtil.java
with GNU Affero General Public License v3.0
from threema-ch

private static PowerManager.WakeLock acquireWakeLock(PowerManager powerManager, long timeout, String tag) {
    try {
        PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, BuildConfig.APPLICATION_ID + ":" + tag);
        wakeLock.acquire(timeout);
        return wakeLock;
    } catch (Exception e) {
        return null;
    }
}

19 Source : AudioChatAdapterDecorator.java
with GNU Affero General Public License v3.0
from threema-ch

public clreplaced AudioChatAdapterDecorator extends ChatAdapterDecorator {

    private static final Logger logger = LoggerFactory.getLogger(AudioChatAdapterDecorator.clreplaced);

    private static final String LISTENER_TAG = "decorator";

    private MessagePlayer audioMessagePlayer;

    private final PowerManager powerManager;

    private final PowerManager.WakeLock audioPlayerWakelock;

    public AudioChatAdapterDecorator(Context context, AbstractMessageModel messageModel, Helper helper) {
        super(context.getApplicationContext(), messageModel, helper);
        this.powerManager = (PowerManager) context.getApplicationContext().getSystemService(Context.POWER_SERVICE);
        this.audioPlayerWakelock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, BuildConfig.APPLICATION_ID + ":AudioPlayer");
    }

    private void keepScreenOn() {
        if (audioPlayerWakelock.isHeld()) {
            keepScreenOff();
        }
        if (audioPlayerWakelock != null && !audioPlayerWakelock.isHeld()) {
            audioPlayerWakelock.acquire(MAX_VOICE_MESSAGE_LENGTH_MILLIS);
        }
        keepScreenOnUpdate();
    }

    private void keepScreenOnUpdate() {
    /*		RuntimeUtil.runOnUiThread(() -> {
			try {
				helper.getFragment().getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
			} catch (Exception e) {
				//
			}
		});
*/
    }

    private void keepScreenOff() {
        if (audioPlayerWakelock != null && audioPlayerWakelock.isHeld()) {
            audioPlayerWakelock.release();
        }
    /*		RuntimeUtil.runOnUiThread(() -> {
			try {
				helper.getFragment().getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
			} catch (Exception e) {
				//
			}
		});
*/
    }

    @Override
    protected void configureChatMessage(final ComposeMessageHolder holder, final int position) {
        AudioDataModel audioDataModel;
        FileDataModel fileDataModel;
        final long duration;
        final boolean isDownloaded;
        String caption = null;
        if (getMessageModel().getType() == MessageType.VOICEMESSAGE) {
            audioDataModel = this.getMessageModel().getAudioData();
            duration = audioDataModel.getDuration();
            isDownloaded = audioDataModel.isDownloaded();
        } else {
            fileDataModel = this.getMessageModel().getFileData();
            duration = fileDataModel.getDuration();
            isDownloaded = fileDataModel.isDownloaded();
            caption = fileDataModel.getCaption();
        }
        audioMessagePlayer = this.getMessagePlayerService().createPlayer(this.getMessageModel(), helper.getFragment().getActivity(), this.helper.getMessageReceiver());
        this.setOnClickListener(view -> {
        // no action on onClick
        }, holder.messageBlockView);
        holder.messagePlayer = audioMessagePlayer;
        holder.controller.setOnClickListener(v -> {
            int status = holder.controller.getStatus();
            switch(status) {
                case ControllerView.STATUS_READY_TO_PLAY:
                case ControllerView.STATUS_PLAYING:
                case ControllerView.STATUS_READY_TO_DOWNLOAD:
                    if (holder.seekBar != null && audioMessagePlayer != null) {
                        audioMessagePlayer.toggle();
                    }
                    break;
                case ControllerView.STATUS_PROGRESSING:
                    if (getMessageModel().isOutbox() && (getMessageModel().getState() == MessageState.PENDING || getMessageModel().getState() == MessageState.SENDING)) {
                        getMessageService().cancelMessageUpload(getMessageModel());
                    } else {
                        audioMessagePlayer.cancel();
                    }
                    break;
                case ControllerView.STATUS_READY_TO_RETRY:
                    if (onClickRetry != null) {
                        onClickRetry.onClick(getMessageModel());
                    }
            }
        });
        RuntimeUtil.runOnUiThread(() -> {
            holder.controller.setNeutral();
            // reset progressbar
            updateProgressCount(holder, 0);
            if (audioMessagePlayer != null) {
                boolean isPlaying = false;
                if (holder.seekBar != null) {
                    holder.seekBar.setEnabled(false);
                }
                switch(audioMessagePlayer.getState()) {
                    case MessagePlayer.State_NONE:
                        if (isDownloaded) {
                            holder.controller.setPlay();
                        } else {
                            if (helper.getDownloadService().isDownloading(this.getMessageModel().getId())) {
                                holder.controller.setProgressing(false);
                            } else {
                                holder.controller.setReadyToDownload();
                            }
                        }
                        break;
                    case MessagePlayer.State_DOWNLOADING:
                    case MessagePlayer.State_DECRYPTING:
                        // show loading
                        holder.controller.setProgressing();
                        break;
                    case MessagePlayer.State_DOWNLOADED:
                    case MessagePlayer.State_DECRYPTED:
                        holder.controller.setPlay();
                        break;
                    case MessagePlayer.State_PLAYING:
                        isPlaying = true;
                    // fallthrough
                    case MessagePlayer.State_PAUSE:
                    case MessagePlayer.State_INTERRUPTED_PLAY:
                        if (isPlaying) {
                            holder.controller.setPause();
                        } else {
                            holder.controller.setPlay();
                        }
                        if (holder.seekBar != null) {
                            holder.seekBar.setEnabled(true);
                            logger.debug("SeekBar: Duration = " + audioMessagePlayer.getDuration());
                            holder.seekBar.setMax(audioMessagePlayer.getDuration());
                            logger.debug("SeekBar: Position = " + audioMessagePlayer.getPosition());
                            updateProgressCount(holder, audioMessagePlayer.getPosition());
                            holder.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

                                @Override
                                public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                                    if (b) {
                                        audioMessagePlayer.seekTo(i);
                                    }
                                }

                                @Override
                                public void onStartTrackingTouch(SeekBar seekBar) {
                                }

                                @Override
                                public void onStopTrackingTouch(SeekBar seekBar) {
                                }
                            });
                        }
                        break;
                }
                audioMessagePlayer.addListener(LISTENER_TAG, new MessagePlayer.PlayerListener() {

                    @Override
                    public void onError(final String humanReadableMessage) {
                        RuntimeUtil.runOnUiThread(() -> Toast.makeText(getContext(), humanReadableMessage, Toast.LENGTH_SHORT).show());
                    }
                }).addListener(LISTENER_TAG, new MessagePlayer.DecryptionListener() {

                    @Override
                    public void onStart(AbstractMessageModel messageModel) {
                        invalidate(holder, position);
                    }

                    @Override
                    public void onEnd(AbstractMessageModel messageModel, boolean success, final String message, File decryptedFile) {
                        if (!success) {
                            RuntimeUtil.runOnUiThread(() -> {
                                holder.controller.setPlay();
                                if (!TestUtil.empty(message)) {
                                    Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                        invalidate(holder, position);
                    }
                }).addListener(LISTENER_TAG, new MessagePlayer.DownloadListener() {

                    @Override
                    public void onStart(AbstractMessageModel messageModel) {
                        invalidate(holder, position);
                    }

                    @Override
                    public void onStatusUpdate(AbstractMessageModel messageModel, int progress) {
                    }

                    @Override
                    public void onEnd(AbstractMessageModel messageModel, boolean success, final String message) {
                        if (!success) {
                            RuntimeUtil.runOnUiThread(() -> {
                                holder.controller.setReadyToDownload();
                                if (!TestUtil.empty(message)) {
                                    Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                        invalidate(holder, position);
                    }
                }).addListener(LISTENER_TAG, new MessagePlayer.PlaybackListener() {

                    @Override
                    public void onPlay(AbstractMessageModel messageModel, boolean autoPlay) {
                        invalidate(holder, position);
                        keepScreenOn();
                    }

                    @Override
                    public void onPause(AbstractMessageModel messageModel) {
                        invalidate(holder, position);
                        keepScreenOff();
                    }

                    @Override
                    public void onStatusUpdate(AbstractMessageModel messageModel, final int pos) {
                        RuntimeUtil.runOnUiThread(() -> {
                            if (holder.position == position) {
                                if (holder.seekBar != null) {
                                    holder.seekBar.setMax(holder.messagePlayer.getDuration());
                                }
                                updateProgressCount(holder, pos);
                                // make sure pinlock is not activated while playing
                                ThreemaApplication.activityUserInteract(helper.getFragment().getActivity());
                                keepScreenOnUpdate();
                            }
                        });
                    }

                    @Override
                    public void onStop(AbstractMessageModel messageModel) {
                        RuntimeUtil.runOnUiThread(() -> {
                            holder.controller.setPlay();
                            updateProgressCount(holder, 0);
                            invalidate(holder, position);
                            keepScreenOff();
                        });
                    }
                });
            } else {
                // no player => no playable file
                holder.controller.setNeutral();
                if (this.getMessageModel().getState() == MessageState.SENDFAILED) {
                    holder.controller.setRetry();
                }
            }
            if (this.getMessageModel().isOutbox()) {
                // outgoing message
                switch(this.getMessageModel().getState()) {
                    case TRANSCODING:
                        holder.controller.setTranscoding();
                        break;
                    case PENDING:
                    case SENDING:
                        holder.controller.setProgressing();
                        break;
                    case SENDFAILED:
                        holder.controller.setRetry();
                        break;
                    default:
                        break;
                }
            }
        });
        // do not show duration if 0
        if (duration > 0) {
            this.setDatePrefix(StringConversionUtil.secondsToString(duration, false), holder.dateView.getTextSize());
            this.dateContentDescriptionPreifx = getContext().getString(R.string.duration) + ": " + StringConversionUtil.getDurationStringHuman(getContext(), duration);
        }
        if (holder.contentView != null) {
            // one size fits all :-)
            holder.contentView.getLayoutParams().width = helper.getThumbnailWidth();
        }
        // format caption
        if (!TextUtils.isEmpty(caption)) {
            holder.bodyTextView.setText(formatTextString(caption, this.filterString));
            LinkifyUtil.getInstance().linkify((ComposeMessageFragment) helper.getFragment(), holder.bodyTextView, this.getMessageModel(), caption.length() < 80, actionModeStatus.getActionModeEnabled(), onClickElement);
            this.showHide(holder.bodyTextView, true);
        } else {
            this.showHide(holder.bodyTextView, false);
        }
    }

    private void updateProgressCount(final ComposeMessageHolder holder, int value) {
        if (holder != null && holder.size != null && holder.seekBar != null) {
            holder.seekBar.setProgress(value);
            holder.size.setText(StringConversionUtil.secondsToString((long) value / 1000, false));
        }
    }
}

19 Source : UnlockDeviceAndroidJUnitRunner.java
with Apache License 2.0
from therajanmaurya

@SuppressLint("MissingPermission")
@Override
public void onStart() {
    Application application = (Application) getTargetContext().getApplicationContext();
    String simpleName = UnlockDeviceAndroidJUnitRunner.clreplaced.getSimpleName();
    // Unlock the device so that the tests can input keystrokes.
    ((KeyguardManager) application.getSystemService(KEYGUARD_SERVICE)).newKeyguardLock(simpleName).disableKeyguard();
    // Wake up the screen.
    PowerManager powerManager = ((PowerManager) application.getSystemService(POWER_SERVICE));
    mWakeLock = powerManager.newWakeLock(FULL_WAKE_LOCK | ACQUIRE_CAUSES_WAKEUP | ON_AFTER_RELEASE, simpleName);
    mWakeLock.acquire();
    super.onStart();
}

19 Source : HistorySyncService.java
with GNU General Public License v3.0
from TebbeUbben

public clreplaced HistorySyncService extends Service implements StatusCallback, TaskRunner.ResultCallback, ServiceConnectionCallback {

    private DatabaseHelper databaseHelper = null;

    private HistoryResync historyResync = null;

    private SightServiceConnector connector;

    private PowerManager powerManager;

    private AlarmManager alarmManager;

    private SharedPreferences activityPreferences;

    private PendingIntent pendingIntent;

    private long dateTimeOffset;

    private PowerManager.WakeLock wakeLock;

    private String pumpSerialNumber;

    private boolean syncing;

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    public DatabaseHelper getDatabaseHelper() {
        if (databaseHelper == null) {
            databaseHelper = OpenHelperManager.getHelper(this, DatabaseHelper.clreplaced);
        }
        return databaseHelper;
    }

    @Override
    public void onCreate() {
        powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        pendingIntent = PendingIntent.getService(this, 0, new Intent(this, HistorySyncService.clreplaced), 0);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "HistorySyncService");
        connector = new SightServiceConnector(this);
        connector.addStatusCallback(this);
        connector.setConnectionCallback(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent.getStringExtra("action");
        if (HistoryBroadcast.ACTION_START_SYNC.equals(action)) {
            if (pendingIntent != null) {
                alarmManager.cancel(pendingIntent);
                pendingIntent = null;
            }
            if (syncing)
                HistorySendIntent.sendStillSyncing(this, getAppsWithHistoryPermission());
            else
                startSync();
        } else if (HistoryBroadcast.ACTION_START_RESYNC.equals(action)) {
            if (historyResync == null)
                historyResync = new HistoryResync(getApplicationContext(), getDatabaseHelper());
            historyResync.doResync(getAppsWithHistoryPermission());
        }
        if (pendingIntent == null && getBooleanPref(PREF_BOOLEAN_BACKGROUND_SYNC_ENABLED)) {
            pendingIntent = PendingIntent.getService(this, 0, new Intent(this, HistorySyncService.clreplaced), 0);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, AlarmManager.INTERVAL_FIFTEEN_MINUTES, AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent);
        }
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        pendingIntent.cancel();
        if (databaseHelper != null) {
            OpenHelperManager.releaseHelper();
            databaseHelper = null;
        }
    }

    private List<String> getAppsWithHistoryPermission() {
        List<String> packagesWithPermission = new ArrayList<>();
        PackageManager packageManager = getPackageManager();
        List<PackageInfo> packages = packageManager.getInstalledPackages(PackageManager.GET_PERMISSIONS);
        for (PackageInfo packageInfo : packages) {
            if (packageInfo.requestedPermissions == null)
                continue;
            for (String permission : packageInfo.requestedPermissions) {
                if (permission.equals("sugar.free.sightremote.HISTORY_BROADCASTS")) {
                    packagesWithPermission.add(packageInfo.packageName);
                }
            }
        }
        return packagesWithPermission;
    }

    @Override
    public void onStatusChange(Status status, long statusTime, long waitTime) {
        if (status == Status.CONNECTED) {
            connector.connect();
            ReadStatusParamBlockMessage readMessage = new ReadStatusParamBlockMessage();
            readMessage.setStatusBlockId(SystemIdentificationBlock.ID);
            new SingleMessageTaskRunner(connector, readMessage).fetch(this);
        } else if (status == Status.DISCONNECTED) {
            connector.disconnect();
            connector.disconnectFromService();
            syncing = false;
            HistorySendIntent.sendSyncFinished(this, getAppsWithHistoryPermission());
            if (wakeLock.isHeld())
                wakeLock.release();
        }
    }

    @Override
    public void onResult(Object result) {
        if (result instanceof ReadStatusParamBlockMessage) {
            pumpSerialNumber = ((SystemIdentificationBlock) ((ReadStatusParamBlockMessage) result).getStatusBlock()).getSerialNumber();
            new SingleMessageTaskRunner(connector, new ReadDateTimeMessage()).fetch(this);
        } else if (result instanceof ReadHistoryTaskRunner.HistoryResult) {
            ReadHistoryTaskRunner.HistoryResult historyResult = (ReadHistoryTaskRunner.HistoryResult) result;
            List<HistoryFrame> historyFrames = historyResult.getHistoryFrames();
            if (historyResult.getLatestEventNumber() > 0)
                Offset.setOffset(getDatabaseHelper(), pumpSerialNumber, HistoryType.ALL, historyResult.getLatestEventNumber());
            connector.disconnect();
            connector.disconnectFromService();
            processHistoryFrames(historyFrames);
            syncing = false;
            HistorySendIntent.sendSyncFinished(this, getAppsWithHistoryPermission());
            if (wakeLock.isHeld())
                wakeLock.release();
        } else if (result instanceof ReadDateTimeMessage) {
            ReadDateTimeMessage dateTimeMessage = (ReadDateTimeMessage) result;
            Date pumpDate = parseDateTime(dateTimeMessage.getYear(), dateTimeMessage.getMonth(), dateTimeMessage.getDay(), dateTimeMessage.getHour(), dateTimeMessage.getMinute(), dateTimeMessage.getSecond());
            dateTimeOffset = new Date().getTime() - pumpDate.getTime();
            new ReadHistoryTaskRunner(connector, createOpenMessage(HistoryType.ALL), Offset.getOffset(getDatabaseHelper(), pumpSerialNumber, HistoryType.ALL) == -1 ? 20 : Integer.MAX_VALUE).fetch(this);
        }
    }

    private void processHistoryFrames(List<HistoryFrame> historyFrames) {
        List<String> packages = getAppsWithHistoryPermission();
        List<BolusDelivered> bolusDeliveredEntries = new ArrayList<>();
        List<BolusProgrammed> bolusProgrammedEntries = new ArrayList<>();
        List<EndOfTBR> endOfTBREntries = new ArrayList<>();
        List<PumpStatusChanged> pumpStatusChangedEntries = new ArrayList<>();
        List<CannulaFilled> cannulaFilledEntries = new ArrayList<>();
        List<TimeChanged> timeChangedEntries = new ArrayList<>();
        List<DailyTotal> dailyTotalEntries = new ArrayList<>();
        List<TubeFilled> tubeFilledEntries = new ArrayList<>();
        List<CartridgeInserted> cartridgeInsertedEntries = new ArrayList<>();
        List<BatteryInserted> batteryInsertedEntries = new ArrayList<>();
        List<OccurenceOfAlert> occurenceOfAlertEntries = new ArrayList<>();
        for (HistoryFrame historyFrame : historyFrames) {
            Log.d("HistorySyncService", "Received " + historyFrame.getClreplaced().getSimpleName());
            if (historyFrame instanceof BolusDeliveredFrame)
                bolusDeliveredEntries.add(processFrame((BolusDeliveredFrame) historyFrame));
            else if (historyFrame instanceof BolusProgrammedFrame)
                bolusProgrammedEntries.add(processFrame((BolusProgrammedFrame) historyFrame));
            else if (historyFrame instanceof EndOfTBRFrame)
                endOfTBREntries.add(processFrame((EndOfTBRFrame) historyFrame));
            else if (historyFrame instanceof PumpStatusChangedFrame)
                pumpStatusChangedEntries.add(processFrame((PumpStatusChangedFrame) historyFrame));
            else if (historyFrame instanceof TimeChangedFrame)
                timeChangedEntries.add(processFrame((TimeChangedFrame) historyFrame));
            else if (historyFrame instanceof CannulaFilledFrame)
                cannulaFilledEntries.add(processCannulaFilledFrame((CannulaFilledFrame) historyFrame));
            else if (historyFrame instanceof DailyTotalFrame)
                dailyTotalEntries.add(processFrame((DailyTotalFrame) historyFrame));
            else if (historyFrame instanceof TubeFilledFrame)
                tubeFilledEntries.add(processFrame((TubeFilledFrame) historyFrame));
            else if (historyFrame instanceof CartridgeInsertedFrame)
                cartridgeInsertedEntries.add(processFrame((CartridgeInsertedFrame) historyFrame));
            else if (historyFrame instanceof BatteryInsertedFrame)
                batteryInsertedEntries.add(processFrame((BatteryInsertedFrame) historyFrame));
            else if (historyFrame instanceof OccurenceOfErrorFrame)
                occurenceOfAlertEntries.add(processFrame((OccurenceOfErrorFrame) historyFrame));
            else if (historyFrame instanceof OccurenceOfMaintenanceFrame)
                occurenceOfAlertEntries.add(processFrame((OccurenceOfMaintenanceFrame) historyFrame));
            else if (historyFrame instanceof OccurenceOfWarningFrame)
                occurenceOfAlertEntries.add(processFrame((OccurenceOfWarningFrame) historyFrame));
        }
        try {
            for (BolusDelivered bolusDelivered : bolusDeliveredEntries) {
                if (getDatabaseHelper().getBolusDeliveredDao().queryBuilder().where().eq("eventNumber", bolusDelivered.getEventNumber()).and().eq("pump", pumpSerialNumber).countOf() > 0)
                    continue;
                getDatabaseHelper().getBolusDeliveredDao().create(bolusDelivered);
                HistorySendIntent.send(getApplicationContext(), bolusDelivered, false, packages);
            }
            for (BolusProgrammed bolusProgrammed : bolusProgrammedEntries) {
                if (getDatabaseHelper().getBolusProgrammedDao().queryBuilder().where().eq("eventNumber", bolusProgrammed.getEventNumber()).and().eq("pump", pumpSerialNumber).countOf() > 0)
                    continue;
                getDatabaseHelper().getBolusProgrammedDao().create(bolusProgrammed);
                HistorySendIntent.send(getApplicationContext(), bolusProgrammed, false, packages);
            }
            for (EndOfTBR endOfTBR : endOfTBREntries) {
                if (getDatabaseHelper().getEndOfTBRDao().queryBuilder().where().eq("eventNumber", endOfTBR.getEventNumber()).and().eq("pump", pumpSerialNumber).countOf() > 0)
                    continue;
                getDatabaseHelper().getEndOfTBRDao().create(endOfTBR);
                HistorySendIntent.send(getApplicationContext(), endOfTBR, false, packages);
            }
            for (PumpStatusChanged pumpStatusChanged : pumpStatusChangedEntries) {
                if (getDatabaseHelper().getPumpStatusChangedDao().queryBuilder().where().eq("eventNumber", pumpStatusChanged.getEventNumber()).and().eq("pump", pumpSerialNumber).countOf() > 0)
                    continue;
                getDatabaseHelper().getPumpStatusChangedDao().create(pumpStatusChanged);
                PumpStatusChanged oldStatus = getDatabaseHelper().getPumpStatusChangedDao().queryBuilder().orderBy("dateTime", false).where().lt("dateTime", pumpStatusChanged.getDateTime()).queryForFirst();
                if (oldStatus != null)
                    HistorySendIntent.send(getApplicationContext(), pumpStatusChanged, oldStatus.getDateTime(), false, packages);
                else
                    HistorySendIntent.send(getApplicationContext(), pumpStatusChanged, false, packages);
            }
            for (TimeChanged timeChanged : timeChangedEntries) {
                if (getDatabaseHelper().getTimeChangedDao().queryBuilder().where().eq("eventNumber", timeChanged.getEventNumber()).and().eq("pump", pumpSerialNumber).countOf() > 0)
                    continue;
                getDatabaseHelper().getTimeChangedDao().create(timeChanged);
                HistorySendIntent.send(getApplicationContext(), timeChanged, false, packages);
            }
            for (CannulaFilled cannulaFilled : cannulaFilledEntries) {
                if (getDatabaseHelper().getCannulaFilledDao().queryBuilder().where().eq("eventNumber", cannulaFilled.getEventNumber()).and().eq("pump", pumpSerialNumber).countOf() > 0)
                    continue;
                getDatabaseHelper().getCannulaFilledDao().create(cannulaFilled);
                HistorySendIntent.send(getApplicationContext(), cannulaFilled, false, packages);
            }
            for (DailyTotal dailyTotal : dailyTotalEntries) {
                if (getDatabaseHelper().getDailyTotalDao().queryBuilder().where().eq("eventNumber", dailyTotal.getEventNumber()).and().eq("pump", pumpSerialNumber).countOf() > 0)
                    continue;
                getDatabaseHelper().getDailyTotalDao().create(dailyTotal);
                HistorySendIntent.send(getApplicationContext(), dailyTotal, false, packages);
            }
            for (TubeFilled tubeFilled : tubeFilledEntries) {
                if (getDatabaseHelper().getTubeFilledDao().queryBuilder().where().eq("eventNumber", tubeFilled.getEventNumber()).and().eq("pump", pumpSerialNumber).countOf() > 0)
                    continue;
                getDatabaseHelper().getTubeFilledDao().create(tubeFilled);
                HistorySendIntent.send(getApplicationContext(), tubeFilled, false, packages);
            }
            for (CartridgeInserted cartridgeInserted : cartridgeInsertedEntries) {
                if (getDatabaseHelper().getCartridgeInsertedDao().queryBuilder().where().eq("eventNumber", cartridgeInserted.getEventNumber()).and().eq("pump", pumpSerialNumber).countOf() > 0)
                    continue;
                getDatabaseHelper().getCartridgeInsertedDao().create(cartridgeInserted);
                HistorySendIntent.send(getApplicationContext(), cartridgeInserted, false, packages);
            }
            for (BatteryInserted batteryInserted : batteryInsertedEntries) {
                if (getDatabaseHelper().getBatteryInsertedDao().queryBuilder().where().eq("eventNumber", batteryInserted.getEventNumber()).and().eq("pump", pumpSerialNumber).countOf() > 0)
                    continue;
                getDatabaseHelper().getBatteryInsertedDao().create(batteryInserted);
                HistorySendIntent.send(getApplicationContext(), batteryInserted, false, packages);
            }
            for (OccurenceOfAlert occurenceOfAlert : occurenceOfAlertEntries) {
                if (getDatabaseHelper().getOccurenceOfAlertDao().queryBuilder().where().eq("eventNumber", occurenceOfAlert.getEventNumber()).and().eq("pump", pumpSerialNumber).countOf() > 0)
                    continue;
                getDatabaseHelper().getOccurenceOfAlertDao().create(occurenceOfAlert);
                HistorySendIntent.send(getApplicationContext(), occurenceOfAlert, false, packages);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private EndOfTBR processFrame(EndOfTBRFrame frame) {
        EndOfTBR endOfTBR = new EndOfTBR();
        endOfTBR.setDuration(frame.getDuration());
        endOfTBR.setAmount(frame.getAmount());
        endOfTBR.setEventNumber(frame.getEventNumber());
        endOfTBR.setPump(pumpSerialNumber);
        int eventTimeSeconds = frame.getEventHour() * 60 * 60 + frame.getEventMinute() * 60 + frame.getEventSecond();
        int startTimeSeconds = frame.getStartHour() * 60 * 60 + frame.getStartMinute() * 60 + frame.getStartSecond();
        boolean startedOnDayBefore = startTimeSeconds >= eventTimeSeconds;
        Date eventTime = parseDateTimeAddOffset(frame.getEventYear(), frame.getEventMonth(), frame.getEventDay(), frame.getEventHour(), frame.getEventMinute(), frame.getEventSecond());
        Date startTime = parseDateTimeAddOffset(frame.getEventYear(), frame.getEventMonth(), frame.getEventDay() - (startedOnDayBefore ? 1 : 0), frame.getStartHour(), frame.getStartMinute(), frame.getStartSecond());
        endOfTBR.setDateTime(eventTime);
        endOfTBR.setStartTime(startTime);
        return endOfTBR;
    }

    private PumpStatusChanged processFrame(PumpStatusChangedFrame frame) {
        PumpStatusChanged pumpStatusChanged = new PumpStatusChanged();
        pumpStatusChanged.setOldValue(frame.getOldValue());
        pumpStatusChanged.setNewValue(frame.getNewValue());
        pumpStatusChanged.setEventNumber(frame.getEventNumber());
        pumpStatusChanged.setPump(pumpSerialNumber);
        Date eventTime = parseDateTimeAddOffset(frame.getEventYear(), frame.getEventMonth(), frame.getEventDay(), frame.getEventHour(), frame.getEventMinute(), frame.getEventSecond());
        pumpStatusChanged.setDateTime(eventTime);
        return pumpStatusChanged;
    }

    private BolusDelivered processFrame(BolusDeliveredFrame frame) {
        BolusDelivered bolusDelivered = new BolusDelivered();
        bolusDelivered.setBolusId(frame.getBolusId());
        bolusDelivered.setBolusType(frame.getBolusType());
        bolusDelivered.setDuration(frame.getDuration());
        bolusDelivered.setEventNumber(frame.getEventNumber());
        bolusDelivered.setExtendedAmount(frame.getExtendedAmount());
        bolusDelivered.setImmediateAmount(frame.getImmediateAmount());
        bolusDelivered.setPump(pumpSerialNumber);
        int eventTimeSeconds = frame.getEventHour() * 60 * 60 + frame.getEventMinute() * 60 + frame.getEventSecond();
        int startTimeSeconds = frame.getStartHour() * 60 * 60 + frame.getStartMinute() * 60 + frame.getStartSecond();
        boolean startedOnDayBefore = startTimeSeconds >= eventTimeSeconds;
        Date eventTime = parseDateTimeAddOffset(frame.getEventYear(), frame.getEventMonth(), frame.getEventDay(), frame.getEventHour(), frame.getEventMinute(), frame.getEventSecond());
        Date startTime = parseDateTimeAddOffset(frame.getEventYear(), frame.getEventMonth(), frame.getEventDay() - (startedOnDayBefore ? 1 : 0), frame.getStartHour(), frame.getStartMinute(), frame.getStartSecond());
        bolusDelivered.setDateTime(eventTime);
        bolusDelivered.setStartTime(startTime);
        return bolusDelivered;
    }

    private BolusProgrammed processFrame(BolusProgrammedFrame frame) {
        BolusProgrammed bolusProgrammed = new BolusProgrammed();
        bolusProgrammed.setBolusId(frame.getBolusId());
        bolusProgrammed.setBolusType(frame.getBolusType());
        bolusProgrammed.setDuration(frame.getDuration());
        bolusProgrammed.setEventNumber(frame.getEventNumber());
        bolusProgrammed.setExtendedAmount(frame.getExtendedAmount());
        bolusProgrammed.setImmediateAmount(frame.getImmediateAmount());
        bolusProgrammed.setPump(pumpSerialNumber);
        Date eventTime = parseDateTimeAddOffset(frame.getEventYear(), frame.getEventMonth(), frame.getEventDay(), frame.getEventHour(), frame.getEventMinute(), frame.getEventSecond());
        bolusProgrammed.setDateTime(eventTime);
        return bolusProgrammed;
    }

    private TimeChanged processFrame(TimeChangedFrame frame) {
        TimeChanged timeChanged = new TimeChanged();
        timeChanged.setEventNumber(frame.getEventNumber());
        timeChanged.setPump(pumpSerialNumber);
        Date eventTime = parseDateTimeAddOffset(frame.getEventYear(), frame.getEventMonth(), frame.getEventDay(), frame.getEventHour(), frame.getEventMinute(), frame.getEventSecond());
        timeChanged.setDateTime(eventTime);
        Date beforeTime = parseDateTimeAddOffset(frame.getBeforeYear(), frame.getBeforeMonth(), frame.getBeforeDay(), frame.getBeforeHour(), frame.getBeforeMinute(), frame.getBeforeSecond());
        timeChanged.setTimeBefore(beforeTime);
        return timeChanged;
    }

    private CannulaFilled processCannulaFilledFrame(CannulaFilledFrame frame) {
        CannulaFilled cannulaFilled = new CannulaFilled();
        cannulaFilled.setEventNumber(frame.getEventNumber());
        cannulaFilled.setPump(pumpSerialNumber);
        cannulaFilled.setAmount(frame.getAmount());
        Date eventTime = parseDateTimeAddOffset(frame.getEventYear(), frame.getEventMonth(), frame.getEventDay(), frame.getEventHour(), frame.getEventMinute(), frame.getEventSecond());
        cannulaFilled.setDateTime(eventTime);
        return cannulaFilled;
    }

    private TubeFilled processFrame(TubeFilledFrame frame) {
        TubeFilled tubeFilled = new TubeFilled();
        tubeFilled.setEventNumber(frame.getEventNumber());
        tubeFilled.setPump(pumpSerialNumber);
        tubeFilled.setAmount(frame.getAmount());
        Date eventTime = parseDateTimeAddOffset(frame.getEventYear(), frame.getEventMonth(), frame.getEventDay(), frame.getEventHour(), frame.getEventMinute(), frame.getEventSecond());
        tubeFilled.setDateTime(eventTime);
        return tubeFilled;
    }

    private CartridgeInserted processFrame(CartridgeInsertedFrame frame) {
        CartridgeInserted cartridgeInserted = new CartridgeInserted();
        cartridgeInserted.setEventNumber(frame.getEventNumber());
        cartridgeInserted.setPump(pumpSerialNumber);
        cartridgeInserted.setAmount(frame.getAmount());
        Date eventTime = parseDateTimeAddOffset(frame.getEventYear(), frame.getEventMonth(), frame.getEventDay(), frame.getEventHour(), frame.getEventMinute(), frame.getEventSecond());
        cartridgeInserted.setDateTime(eventTime);
        return cartridgeInserted;
    }

    private BatteryInserted processFrame(BatteryInsertedFrame frame) {
        BatteryInserted batteryInserted = new BatteryInserted();
        batteryInserted.setEventNumber(frame.getEventNumber());
        batteryInserted.setPump(pumpSerialNumber);
        Date eventTime = parseDateTimeAddOffset(frame.getEventYear(), frame.getEventMonth(), frame.getEventDay(), frame.getEventHour(), frame.getEventMinute(), frame.getEventSecond());
        batteryInserted.setDateTime(eventTime);
        return batteryInserted;
    }

    private DailyTotal processFrame(DailyTotalFrame frame) {
        DailyTotal dailyTotal = new DailyTotal();
        dailyTotal.setEventNumber(frame.getEventNumber());
        dailyTotal.setBasalTotal(frame.getBasalTotal());
        dailyTotal.setBolusTotal(frame.getBolusTotal());
        Date eventTime = parseDateTimeAddOffset(frame.getEventYear(), frame.getEventMonth(), frame.getEventDay(), frame.getEventHour(), frame.getEventMinute(), frame.getEventSecond());
        dailyTotal.setDateTime(eventTime);
        Date totalDate = parseDateTime(frame.getTotalYear(), frame.getTotalMonth(), frame.getTotalDay(), 0, 0, 0);
        dailyTotal.setTotalDate(totalDate);
        return dailyTotal;
    }

    private OccurenceOfAlert processFrame(OccurenceOfAlertFrame frame) {
        OccurenceOfAlert occurenceOfAlert = new OccurenceOfAlert();
        occurenceOfAlert.setEventNumber(frame.getEventNumber());
        occurenceOfAlert.setAlertType(frame.getAlertType().getSimpleName());
        occurenceOfAlert.setAlertId(frame.getAlertId());
        Date eventTime = parseDateTimeAddOffset(frame.getEventYear(), frame.getEventMonth(), frame.getEventDay(), frame.getEventHour(), frame.getEventMinute(), frame.getEventSecond());
        occurenceOfAlert.setDateTime(eventTime);
        return occurenceOfAlert;
    }

    private OpenHistoryReadingSessionMessage createOpenMessage(HistoryType historyType) {
        OpenHistoryReadingSessionMessage openMessage = new OpenHistoryReadingSessionMessage();
        openMessage.setHistoryType(historyType);
        long offset = Offset.getOffset(getDatabaseHelper(), pumpSerialNumber, historyType);
        if (offset != -1) {
            openMessage.setOffset(offset + 1);
            openMessage.setReadingDirection(HistoryReadingDirection.FORWARD);
        } else {
            openMessage.setOffset(0xFFFFFFFF);
            openMessage.setReadingDirection(HistoryReadingDirection.BACKWARD);
        }
        return openMessage;
    }

    private Date parseDateTime(int year, int month, int day, int hour, int minute, int second) {
        Calendar calendar = new GregorianCalendar(TimeZone.getDefault(), Locale.getDefault());
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, day);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, second);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    private Date parseDateTimeAddOffset(int year, int month, int day, int hour, int minute, int second) {
        Date date = parseDateTime(year, month, day, hour, minute, second);
        date = new Date(date.getTime() + dateTimeOffset);
        return date;
    }

    @Override
    public void onError(Exception e) {
        e.printStackTrace();
        connector.disconnect();
        connector.disconnectFromService();
        syncing = false;
        HistorySendIntent.sendSyncFinished(this, getAppsWithHistoryPermission());
        if (wakeLock.isHeld())
            wakeLock.release();
    }

    private void startSync() {
        if (!wakeLock.isHeld())
            wakeLock.acquire(60000);
        syncing = true;
        connector.connectToService();
        HistorySendIntent.sendSyncStarted(this, getAppsWithHistoryPermission());
    }

    @Override
    public void onServiceConnected() {
        if (!connector.isUseable())
            connector.disconnectFromService();
        else {
            connector.connect();
            if (connector.getStatus() == Status.CONNECTED) {
                onStatusChange(Status.CONNECTED, 0, 0);
            }
        }
    }

    @Override
    public void onServiceDisconnected() {
        syncing = false;
        if (wakeLock.isHeld())
            wakeLock.release();
    }
}

19 Source : DownloadService.java
with GNU General Public License v3.0
from TachibanaGeneralLaboratories

private void setKeepCpuAwake(boolean enable) {
    if (enable) {
        if (wakeLock == null) {
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        }
        if (!wakeLock.isHeld())
            wakeLock.acquire();
    } else {
        if (wakeLock == null)
            return;
        if (wakeLock.isHeld())
            wakeLock.release();
    }
}

19 Source : ForegroundService.java
with GNU General Public License v3.0
from Swing-team

/**
 * Put the service in a foreground state to prevent app from being killed
 * by the OS.
 */
@SuppressLint("WakelockTimeout")
private void keepAwake() {
    JSONObject settings = BackgroundMode.getSettings();
    boolean isSilent = settings.optBoolean("silent", false);
    if (!isSilent) {
        startForeground(NOTIFICATION_ID, makeNotification());
    }
    PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
    wakeLock = pm.newWakeLock(PARTIAL_WAKE_LOCK, "backgroundmode:wakelock");
    wakeLock.acquire();
}

19 Source : BackgroundModeExt.java
with GNU General Public License v3.0
from Swing-team

/**
 * Returns if the screen is active.
 */
@SuppressWarnings("deprecation")
private boolean isDimmed() {
    PowerManager pm = (PowerManager) getService(POWER_SERVICE);
    if (SDK_INT < 20) {
        return !pm.isScreenOn();
    }
    return !pm.isInteractive();
}

19 Source : BackgroundModeExt.java
with GNU General Public License v3.0
from Swing-team

/**
 * Acquires a wake lock to wake up the device.
 */
@SuppressWarnings("deprecation")
private void acquireWakeLock() {
    PowerManager pm = (PowerManager) getService(POWER_SERVICE);
    releaseWakeLock();
    if (!isDimmed())
        return;
    int level = PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP;
    wakeLock = pm.newWakeLock(level, "backgroundmode:wakelock");
    wakeLock.setReferenceCounted(false);
    wakeLock.acquire(1000);
}

19 Source : S_MVP.java
with Apache License 2.0
from stytooldex

private void takeWakeLock() {
    if (wakeLock == null) {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        // Many (all?) devices seem to not properly honor a
        // PARTIAL_WAKE_LOCK,
        // which should prevent CPU throttling. This has been
        // well-complained-about on android-developers.
        // For these devices, we have a config option to force the phone
        // into a
        // full wake lock.
        if (fullWake) {
            wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, WAKE_LOCK_TAG);
        } else {
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKE_LOCK_TAG);
        }
        wakeLock.setReferenceCounted(false);
    }
    // myLog.d("Acquiring wake lock");
    wakeLock.acquire();
}

19 Source : ScreenListener.java
with Apache License 2.0
from stytooldex

/**
 * 获取screen状态
 */
private void getScreenState() {
    PowerManager manager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
    if (manager.isScreenOn()) {
        if (mScreenStateListener != null) {
            mScreenStateListener.onScreenOn();
        }
    } else {
        if (mScreenStateListener != null) {
            mScreenStateListener.onScreenOff();
        }
    }
}

19 Source : RedPacketService.java
with Apache License 2.0
from stytooldex

/**
 * 判断是否处于亮屏状态
 *
 * @return true-亮屏,false-暗屏
 */
private boolean isScreenOn() {
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    /*
      用于判断是否屏幕是亮着的
     */
    boolean isScreenOn = pm.isScreenOn();
    Log.e("isScreenOn", isScreenOn + "");
    return isScreenOn;
}

19 Source : SpaceInvadersActivity.java
with GNU General Public License v3.0
from StringMon

public clreplaced SpaceInvadersActivity extends Activity implements SensorEventListener {

    /**
     * Called when the activity is first created.
     */
    private InvaderView mView = null;

    private PowerManager mPowerManager;

    private SensorManager mSensorManager;

    // private WakeLock mWakeLock;
    private Sensor mAccelerometer;

    private Timer mUpdate;

    private InvaderTimer mEvent;

    private boolean mUseAccelerometer = false;

    private int mAccelerometerThreshold = 20;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get an instance of the SensorManager
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        // Get an instance of the PowerManager
        mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
        // Create a bright wake lock
        // mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK,
        // getClreplaced().getName());
        mView = new InvaderView(getApplicationContext());
        setContentView(mView);
        mUpdate = new Timer();
        mEvent = new InvaderTimer();
        mUpdate.schedule(mEvent, 0, 80);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // mWakeLock.acquire();
        if (mView != null) {
            mView.updatePrefs();
        }
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // mWakeLock.release();
        mSensorManager.unregisterListener(this);
    }

    clreplaced InvaderTimer extends TimerTask {

        @Override
        public void run() {
            runOnUiThread(new Runnable() {

                public void run() {
                    mView.postInvalidate();
                }
            });
        }
    }

    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1) {
    // Do Nothing
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (mUseAccelerometer) {
            accelerometerControl(event);
            return;
        } else {
            return;
        }
    }

    private void accelerometerControl(SensorEvent event) {
        float xSens;
        if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
            return;
        xSens = event.values[1];
    // if(xSens > mAccelerometerThreshold){
    // mMove = true;
    // mMoveLeft = false;
    // mTouch = true;
    // return;
    // }
    // if(xSens < -mAccelerometerThreshold){
    // mMove = true;
    // mTouch = true;
    // mMoveLeft = true;
    // return;
    // }
    // mMove = false;
    // if(mFire == false){
    // mTouch = false;
    // }
    }
}

19 Source : DataLoggerService.java
with MIT License
from STRCWearlab

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).setContentreplacedle(getResources().getString(R.string.notification_content_replacedle)).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.clreplaced), 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));
    }
}

19 Source : SteamService.java
with GNU General Public License v3.0
from steevp

/**
 * Acquire WakeLock to keep the CPU from sleeping
 */
public void acquireWakeLock() {
    if (wakeLock == null) {
        Log.i(TAG, "Acquiring WakeLock");
        final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
        wakeLock.acquire();
    }
}

19 Source : MainActivity.java
with Apache License 2.0
from sofwerx

protected boolean isOptimizingBattery() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        return pm != null && !pm.isIgnoringBatteryOptimizations(getPackageName());
    } else
        return false;
}

19 Source : ScreenManager.java
with GNU General Public License v3.0
from socoolby

public static void turnScreenOff() {
    PowerManager pm = (PowerManager) ClockApplication.getContext().getSystemService(Activity.POWER_SERVICE);
    pm.goToSleep(SystemClock.uptimeMillis());
}

19 Source : XmppActivity.java
with GNU General Public License v3.0
from snikket-im

protected boolean isOptimizingBattery() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        return pm != null && !pm.isIgnoringBatteryOptimizations(getPackageName());
    } else {
        return false;
    }
}

19 Source : WakeLockManager.java
with GNU Affero General Public License v3.0
from Shouheng88

/**
 * Utility clreplaced to preplaced {@link WakeLock} objects with intents. It contains a
 * factory, which has to be initialized in {@link Application#onCreate()} or
 * otherwise there will be an exception. Instance maintains a {@link Map} of
 * String tag to {@link WakeLock} wakelock
 */
public clreplaced WakeLockManager {

    private static final String EXTRA_WAKELOCK_TAG = "WakeLockManager.EXTRA_WAKELOCK_TAG";

    private static final String EXTRA_WAKELOCK_HASH = "WakeLockManager.EXTRA_WAKELOCK_HASH";

    private static volatile WakeLockManager sInstance;

    private final CopyOnWriteArrayList<WakeLock> wakeLocks;

    private final PowerManager powerManager;

    @Deprecated
    public static WakeLockManager getWakeLockManager() {
        if (sInstance == null) {
            throw new RuntimeException("WakeLockManager was not initialized");
        }
        return sInstance;
    }

    @Deprecated
    public static void init(Context context, boolean debug) {
        if (sInstance != null) {
            LogUtils.d("init: " + "Attempt to re-initialize");
            WakeLockManager oldManager = sInstance;
            sInstance = new WakeLockManager(context, debug);
            sInstance.wakeLocks.addAllAbsent(oldManager.wakeLocks);
        } else {
            sInstance = new WakeLockManager(context, debug);
        }
    }

    private WakeLockManager(Context context, boolean debug) {
        powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        wakeLocks = new CopyOnWriteArrayList<>();
    }

    /**
     * Acquires a partial {@link WakeLock}, stores it internally and puts the
     * tag into the {@link Intent}. To be used with {@link WakeLockManager#releasePartialWakeLock(Intent)}
     *
     * @param intent intent
     * @param wlTag tag
     */
    public void acquirePartialWakeLock(Intent intent, String wlTag) {
        final WakeLock wl = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, wlTag);
        wl.acquire();
        wakeLocks.add(wl);
        intent.putExtra(WakeLockManager.EXTRA_WAKELOCK_HASH, wl.hashCode());
        intent.putExtra(WakeLockManager.EXTRA_WAKELOCK_TAG, wlTag);
        LogUtils.d("acquirePartialWakeLock: " + wl.toString() + " " + wlTag + " was acquired");
    }

    /**
     * Releases a partial {@link WakeLock} with a tag contained in the given{@link Intent}
     *
     * @param intent intent
     */
    private void releasePartialWakeLock(Intent intent) {
        if (intent.hasExtra(WakeLockManager.EXTRA_WAKELOCK_TAG)) {
            final int hash = intent.getIntExtra(WakeLockManager.EXTRA_WAKELOCK_HASH, -1);
            final String tag = intent.getStringExtra(WakeLockManager.EXTRA_WAKELOCK_TAG);
            // We use copy on write list. Iterator won't cause ConcurrentModificationException
            for (WakeLock wakeLock : wakeLocks) {
                if (hash == wakeLock.hashCode()) {
                    if (wakeLock.isHeld()) {
                        wakeLock.release();
                        LogUtils.d("releasePartialWakeLock: " + wakeLock.toString() + " " + tag + " was released");
                    } else {
                        LogUtils.d("releasePartialWakeLock: " + wakeLock.toString() + " " + tag + " was already released!");
                    }
                    wakeLocks.remove(wakeLock);
                    return;
                }
            }
            LogUtils.e("releasePartialWakeLock: " + "Hash " + hash + " was not found");
        }
    }
}

19 Source : DeviceUtils.java
with Apache License 2.0
from Shouheng88

public static void reboot(final String reason) {
    PowerManager pm = (PowerManager) UtilsApp.getApp().getSystemService(Context.POWER_SERVICE);
    // noinspection ConstantConditions
    pm.reboot(reason);
}

19 Source : GlobalParameters.java
with MIT License
from Sentaroh

@SuppressLint("NewApi")
static public boolean isScreenOn(Context context, CommonUtilities util) {
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    if (Build.VERSION.SDK_INT >= 23) {
        util.addDebugMsg(1, "I", "isDeviceIdleMode()=" + pm.isDeviceIdleMode() + ", isPowerSaveMode()=" + pm.isPowerSaveMode() + ", isInteractive()=" + pm.isInteractive());
    } else {
        util.addDebugMsg(1, "I", "isPowerSaveMode()=" + pm.isPowerSaveMode() + ", isInteractive()=" + pm.isInteractive());
    }
    return pm.isInteractive();
}

19 Source : CameraPlugin.java
with Apache License 2.0
from Samsung

/**
 * Allows to start and interact with a device camera.
 */
public clreplaced CameraPlugin implements AbstractPlugin {

    private static final String TAG = CameraPlugin.clreplaced.getSimpleName();

    public static final String OPEN_FOR_PIC_ACTION = "OPEN_FOR_PIC";

    public static final String OPEN_FOR_VIDEO_ACTION = "OPEN_FOR_VIDEO";

    public static final String ACTION_TAKE_PICTURE = "TAKE_PIC";

    public static final String ACTION_TAKE_VIDEO = "START_VIDEO";

    public static final String ACTION_TOGGLE_CAMERA = "TOGGLE_CAMERA";

    public static final String ACTION_STOP_VIDEO = "STOP_VIDEO";

    public static final String ACTION_CLOSE = "CLOSE";

    private PowerManager mPowerManager;

    private PowerManager.WakeLock mWakeLock;

    private int m_CurrentState;

    private int m_NextState;

    private PlayAudioPresenter playAudioPresenter;

    private MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
            performOnEnd();
        }
    };

    @Override
    public void handleEntry(CmdArg cmd) {
        Context ctx = MBApp.getApp();
        if (mPowerManager == null) {
            mPowerManager = (PowerManager) ctx.getApplicationContext().getSystemService(Context.POWER_SERVICE);
            mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, TAG);
        }
        int cmdArg = cmd.getCMD();
        if (cmdArg == EventSubCodes.SAMSUNG_CAMERA_EVT_STOP_PHOTO_MODE || cmdArg == EventSubCodes.SAMSUNG_CAMERA_EVT_STOP_VIDEO_MODE) {
            Intent intent = new Intent(ACTION_CLOSE);
            ctx.sendBroadcast(intent);
            return;
        }
        mWakeLock.acquire(5 * 1000);
        switch(cmd.getCMD()) {
            case EventSubCodes.SAMSUNG_CAMERA_EVT_LAUNCH_PHOTO_MODE:
                m_CurrentState = EventSubCodes.SAMSUNG_CAMERA_EVT_LAUNCH_PHOTO_MODE;
                m_NextState = EventSubCodes.SAMSUNG_CAMERA_EVT_LAUNCH_PHOTO_MODE;
                if (playAudioPresenter != null) {
                    playAudioPresenter.stop();
                } else {
                    playAudioPresenter = new PlayAudioPresenter();
                }
                playAudioPresenter.setInternalPathForPlay(InternalPaths.LAUNCH_CAMERA_AUDIO_PHOTO);
                playAudioPresenter.setCallBack(onCompletionListener);
                playAudioPresenter.start();
                break;
            case EventSubCodes.SAMSUNG_CAMERA_EVT_LAUNCH_VIDEO_MODE:
                m_CurrentState = EventSubCodes.SAMSUNG_CAMERA_EVT_LAUNCH_VIDEO_MODE;
                m_NextState = EventSubCodes.SAMSUNG_CAMERA_EVT_LAUNCH_VIDEO_MODE;
                if (playAudioPresenter != null) {
                    playAudioPresenter.stop();
                } else {
                    playAudioPresenter = new PlayAudioPresenter();
                }
                playAudioPresenter.setInternalPathForPlay(InternalPaths.LAUNCH_CAMERA_AUDIO_VIDEO);
                playAudioPresenter.setCallBack(onCompletionListener);
                playAudioPresenter.start();
                break;
            case EventSubCodes.SAMSUNG_CAMERA_EVT_TAKE_PHOTO:
                m_NextState = EventSubCodes.SAMSUNG_CAMERA_EVT_TAKE_PHOTO;
                performOnEnd();
                break;
            case EventSubCodes.SAMSUNG_CAMERA_EVT_START_VIDEO_CAPTURE:
                m_NextState = EventSubCodes.SAMSUNG_CAMERA_EVT_START_VIDEO_CAPTURE;
                performOnEnd();
                break;
            case EventSubCodes.SAMSUNG_CAMERA_EVT_STOP_VIDEO_CAPTURE:
                recVideoStop();
                break;
            case EventSubCodes.SAMSUNG_CAMERA_EVT_TOGGLE_FRONT_REAR:
                toggleCamera();
                break;
            default:
                Log.e(TAG, "Unknown Event subCode : " + cmd.getCMD());
                break;
        }
    }

    @Override
    public void destroy() {
        if (playAudioPresenter != null) {
            playAudioPresenter.stop();
            playAudioPresenter.setCallBack(null);
            playAudioPresenter = null;
        }
    }

    /**
     * Provides some actions needed to perform at the end.
     */
    private void performOnEnd() {
        Log.d(TAG, "Next state - " + m_NextState);
        switch(m_NextState) {
            case EventSubCodes.SAMSUNG_CAMERA_EVT_LAUNCH_PHOTO_MODE:
                launchCamera(true);
                break;
            case EventSubCodes.SAMSUNG_CAMERA_EVT_LAUNCH_VIDEO_MODE:
                launchCamera(false);
                break;
            case EventSubCodes.SAMSUNG_CAMERA_EVT_TAKE_PHOTO:
                takePic();
                break;
            case EventSubCodes.SAMSUNG_CAMERA_EVT_START_VIDEO_CAPTURE:
                recVideoStart();
                break;
        }
    }

    /**
     * Sends a broadcast intent to take a picture.
     */
    private static void takePic() {
        Intent intent = new Intent(ACTION_TAKE_PICTURE);
        MBApp.getApp().sendBroadcast(intent);
    }

    /**
     * Sends a broadcast intent to start video recording.
     */
    private static void recVideoStart() {
        Intent intent = new Intent(ACTION_TAKE_VIDEO);
        MBApp.getApp().sendBroadcast(intent);
    }

    /**
     * Sends a broadcast intent to stop video recording.
     */
    private static void recVideoStop() {
        Intent intent = new Intent(ACTION_STOP_VIDEO);
        MBApp.getApp().sendBroadcast(intent);
    }

    /**
     * Sends a broadcast intent to turn on/off a camera.
     */
    private static void toggleCamera() {
        Intent intent = new Intent(ACTION_TOGGLE_CAMERA);
        MBApp.getApp().sendBroadcast(intent);
    }

    /**
     * Starts activity to take a picture or to record a video.
     */
    private void launchCamera(boolean launchForPic) {
        Context context = MBApp.getApp();
        Intent mIntent = new Intent(context, CameraActivityPermissionChecker.clreplaced);
        mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        if (launchForPic) {
            mIntent.setAction(OPEN_FOR_PIC_ACTION);
        } else {
            mIntent.setAction(OPEN_FOR_VIDEO_ACTION);
        }
        context.startActivity(mIntent);
    }
}

19 Source : RunningActivity.java
with Apache License 2.0
from SailFlorve

// 获取唤醒锁
private void acquireWakeLock() {
    if (null == wakeLock) {
        PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "RunHDU: PostLocationService");
        if (null != wakeLock) {
            wakeLock.acquire(10 * 60 * 1000L);
        }
    }
}

See More Examples