Example usage for android.content Context POWER_SERVICE

List of usage examples for android.content Context POWER_SERVICE

Introduction

In this page you can find the example usage for android.content Context POWER_SERVICE.

Prototype

String POWER_SERVICE

To view the source code for android.content Context POWER_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.os.PowerManager for controlling power management, including "wake locks," which let you keep the device on while you're running long tasks.

Usage

From source file:com.keithcassidy.finishline.FinishLineService.java

private void acquireWakeLock() {
    try {//  w  w  w  .  j  a va 2 s  . c  o m
        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (powerManager == null) {
            Log.e(TAG, "powerManager is null.");
            return;
        }

        if (wakeLock == null) {
            wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
            if (wakeLock == null) {
                Log.e(TAG, "wakeLock is null.");
                return;
            }
        }

        if (!wakeLock.isHeld()) {
            wakeLock.acquire();
            if (!wakeLock.isHeld()) {
                Log.e(TAG, "Unable to hold wakeLock.");
            }
        }

    } catch (RuntimeException e) {
        Log.e(TAG, "Caught RuntimeException exception in acquireWakeLock", e);
    }
}

From source file:com.easemob.ui.ChatActivity.java

private void setUpView() {
    activityInstance = this;
    iv_emoticons_normal.setOnClickListener(this);
    iv_emoticons_checked.setOnClickListener(this);
    // position = getIntent().getIntExtra("position", -1);
    clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
            .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");
    // ???//from w  w  w . ja  v  a  2 s.co m
    chatType = getIntent().getIntExtra("chatType", CHATTYPE_SINGLE);

    if (chatType == CHATTYPE_SINGLE) { // ??
        toChatUsername = getIntent().getStringExtra("userId");
        ((TextView) findViewById(R.id.name))
                .setText(TextUtils.isEmpty(user.getRealName()) ? user.getUsername() : user.getRealName());
    } else {
        // ?
        findViewById(R.id.container_to_group).setVisibility(View.VISIBLE);
        findViewById(R.id.container_remove).setVisibility(View.GONE);
        toChatUsername = getIntent().getStringExtra("groupId");
        group = EMGroupManager.getInstance().getGroup(toChatUsername);
        ((TextView) findViewById(R.id.name)).setText(group.getGroupName());
    }
    conversation = EMChatManager.getInstance().getConversation(toChatUsername);
    // ?0
    conversation.resetUnsetMsgCount();
    adapter = new MessageAdapter(this, toChatUsername, chatType);
    // ?
    listView.setAdapter(adapter);
    listView.setOnScrollListener(new ListScrollListener());
    int count = listView.getCount();
    if (count > 0) {
        listView.setSelection(count - 1);
    }

    listView.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            hideKeyboard();
            more.setVisibility(View.GONE);
            iv_emoticons_normal.setVisibility(View.VISIBLE);
            iv_emoticons_checked.setVisibility(View.INVISIBLE);
            expressionContainer.setVisibility(View.GONE);
            btnContainer.setVisibility(View.GONE);
            return false;
        }
    });
    // ?
    receiver = new NewMessageBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
    // Mainacitivity,??chat??????
    intentFilter.setPriority(5);
    registerReceiver(receiver, intentFilter);

    // ack?BroadcastReceiver
    IntentFilter ackMessageIntentFilter = new IntentFilter(
            EMChatManager.getInstance().getAckMessageBroadcastAction());
    ackMessageIntentFilter.setPriority(5);
    registerReceiver(ackMessageReceiver, ackMessageIntentFilter);

    // ????T
    groupListener = new GroupListener();
    EMGroupManager.getInstance().addGroupChangeListener(groupListener);

    // show forward message if the message is not null
    String forward_msg_id = getIntent().getStringExtra("forward_msg_id");
    if (forward_msg_id != null) {
        // ?????
        forwardMessage(forward_msg_id);
    }

}

From source file:com.cityfreqs.littlesirecho.MainActivity.java

private void runScheduler() {
    PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    wakeLock.acquire();/* w w w .j  a  va  2s.  co  m*/

    scheduler = Executors.newSingleThreadScheduledExecutor();
    scheduler.scheduleAtFixedRate(new Runnable() {
        public void run() {
            logger("executor echo.");
            echoNotification();
        }
    }, userSelectedWaitTime, userSelectedWaitTime, TimeUnit.MILLISECONDS);
}

From source file:github.daneren2005.dsub.service.DownloadService.java

@Override
public void onCreate() {
    super.onCreate();

    final SharedPreferences prefs = Util.getPreferences(this);
    new Thread(new Runnable() {
        public void run() {
            Looper.prepare();/*from   w w w .  j  a  v a 2  s. c om*/

            mediaPlayer = new MediaPlayer();
            mediaPlayer.setWakeMode(DownloadService.this, PowerManager.PARTIAL_WAKE_LOCK);

            audioSessionId = -1;
            Integer id = prefs.getInt(Constants.CACHE_AUDIO_SESSION_ID, -1);
            if (id != -1) {
                try {
                    audioSessionId = id;
                    mediaPlayer.setAudioSessionId(audioSessionId);
                } catch (Throwable e) {
                    audioSessionId = -1;
                }
            }

            if (audioSessionId == -1) {
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    audioSessionId = mediaPlayer.getAudioSessionId();
                    prefs.edit().putInt(Constants.CACHE_AUDIO_SESSION_ID, audioSessionId).commit();
                } catch (Throwable t) {
                    // Froyo or lower
                }
            }

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
                    handleError(new Exception("MediaPlayer error: " + what + " (" + more + ")"));
                    return false;
                }
            });

            try {
                Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
                i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, audioSessionId);
                i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
                sendBroadcast(i);
            } catch (Throwable e) {
                // Froyo or lower
            }

            effectsController = new AudioEffectsController(DownloadService.this, audioSessionId);
            if (prefs.getBoolean(Constants.PREFERENCES_EQUALIZER_ON, false)) {
                getEqualizerController();
            }

            mediaPlayerLooper = Looper.myLooper();
            mediaPlayerHandler = new Handler(mediaPlayerLooper);

            if (runListenersOnInit) {
                onSongsChanged();
                onSongProgress();
                onStateUpdate();
            }

            Looper.loop();
        }
    }, "DownloadService").start();

    Util.registerMediaButtonEventReceiver(this);

    if (mRemoteControl == null) {
        // Use the remote control APIs (if available) to set the playback state
        mRemoteControl = RemoteControlClientHelper.createInstance();
        ComponentName mediaButtonReceiverComponent = new ComponentName(getPackageName(),
                MediaButtonIntentReceiver.class.getName());
        mRemoteControl.register(this, mediaButtonReceiverComponent);
    }

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

    try {
        timerDuration = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_SLEEP_TIMER_DURATION, "5"));
    } catch (Throwable e) {
        timerDuration = 5;
    }
    sleepTimer = null;

    keepScreenOn = prefs.getBoolean(Constants.PREFERENCES_KEY_KEEP_SCREEN_ON, false);

    mediaRouter = new MediaRouteManager(this);

    instance = this;
    shufflePlayBuffer = new ShufflePlayBuffer(this);
    artistRadioBuffer = new ArtistRadioBuffer(this);
    lifecycleSupport.onCreate();
}

From source file:com.inloc.dr.StepService.java

private void acquireWakeLock() {
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    int wakeFlags;
    if (mPedometerSettings.wakeAggressively()) {
        wakeFlags = PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP;
    } else if (mPedometerSettings.keepScreenOn()) {
        wakeFlags = PowerManager.SCREEN_DIM_WAKE_LOCK;
    } else {//from   w  ww.  j  ava  2s  .com
        wakeFlags = PowerManager.PARTIAL_WAKE_LOCK;
    }
    wakeLock = pm.newWakeLock(wakeFlags, TAG);
    wakeLock.acquire();
}

From source file:com.putlocker.upload.DownloadService.java

@Override
protected void onHandleIntent(Intent intent) {
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Download Wakelock");
    wl.acquire();//from ww  w .ja va  2s  .  c  om

    ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    WifiLock wifiLock = null;
    // We only want to aquire the wifi wake lock
    if (mWifi.isConnected()) {
        wifiLock = ((WifiManager) this.getSystemService(Context.WIFI_SERVICE))
                .createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY, "WlanSilencerScanLock");
        wifiLock.acquire();
    }

    if (intent.hasExtra(JOB_EXTRA_DOWNLOAD)) {
        handleDownloadIntent(intent);
    } else {
        handleUploadIntent(intent);
    }

    if (wifiLock != null && wifiLock.isHeld()) {
        wifiLock.release();
    }

    wl.release();
}

From source file:com.snt.bt.recon.activities.MainActivity.java

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(com.snt.bt.recon.R.layout.activity_main);
    ButterKnife.bind(this);
    logDebug("Activity", "######################## On Create ########################");
    //Lock orientation
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    //Leave screen on
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    //leave cpu on
    wl = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
            "wlTag");
    wl.acquire();/* w  ww . j av a  2  s  . co  m*/

    //For device id
    telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

    //for connectivity
    cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    try {

        logDebug("DatabaseTest", "Reading all trips..");
        List<Trip> trips = db.getAll(Trip.class);
        for (Trip trip : trips) {
            String log = "session id: " + trip.getSessionId() + " imei: " + trip.getImei() + " transport: "
                    + trip.getTransport() + " TS: " + trip.getTimestampStart() + " TE: "
                    + trip.getTimestampEnd() + " upload status: " + trip.getUploadStatus();
            logDebug("DatabaseTest", log);
        }
        logDebug("DatabaseTest", "Reading all locations..");
        List<GPSLocation> locs = db.getAll(GPSLocation.class);
        for (GPSLocation loc : locs) {
            String log = "loc id: " + loc.getLocationId() + " sess id: " + loc.getSessionId() + " timestamp: "
                    + loc.getTimestamp() + " upload status: " + loc.getUploadStatus();
            logDebug("DatabaseTest", log);
        }
        logDebug("DatabaseTest", "Reading all bc..");
        List<BluetoothClassicEntry> bcs = db.getAll(BluetoothClassicEntry.class);
        for (BluetoothClassicEntry bc : bcs) {
            String log = "sess id: " + bc.getSessionId() + " loc id: " + bc.getLocationId() + " upload status: "
                    + bc.getUploadStatus();
            logDebug("DatabaseTest", log);
        }
        logDebug("DatabaseTest", "Reading all ble..");
        List<BluetoothLowEnergyEntry> bles = db.getAll(BluetoothLowEnergyEntry.class);
        for (BluetoothLowEnergyEntry ble : bles) {
            String log = "sess id: " + ble.getSessionId() + " loc id: " + ble.getLocationId()
                    + " upload status: " + ble.getUploadStatus();
            logDebug("DatabaseTest", log);
        }
    } catch (InstantiationException | IllegalAccessException e) {
        e.printStackTrace();
    }

    //Show select transpot mode
    new TransportMode(this).show();

    // Show EULA
    new AppEULA(this).show();

    //displayFeedbackDialog();

    //avtivity recognition start
    mActivityRecognitionScan = new ActivityRecognitionUtil(this);
    mActivityRecognitionScan.startActivityRecognitionScan();
    //Filter the Intent and register broadcast receiver
    registerReceiver(ActivityRecognitionReceiver, new IntentFilter("ImActive"));

    //gps
    gpsStatusCheck();

    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    locationListener = new MyLocationListener();
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 3, locationListener);

    //bt
    mBluetoothUtils = new BluetoothUtils(this);

    //ble
    mLeDeviceStore = new BluetoothLeDeviceStore();
    mLeScanner = new BluetoothLeScanner(mLeScanCallback, mBluetoothUtils);
    //bc
    mBcDeviceList = new ArrayList<>();

    final Handler h = new Handler();
    final int delay = 60000;

    h.postDelayed(new Runnable() {
        public void run() {
            syncServerDatabase();

            h.postDelayed(this, delay);
        }
    }, delay);

    //Clean BLE table in case device last timestamp is > 10 seconds
    final Handler h2 = new Handler();
    h2.postDelayed(new Runnable() {
        public void run() {
            //clear old ble devices
            for (BluetoothLeDevice device : mLeDeviceStore.getDeviceList()) {
                long diff = System.currentTimeMillis() - device.getTimestamp();
                if (diff > 10000) {
                    mLeDeviceStore.removeDevice(device);
                    //Refresh the listview
                    final EasyObjectCursor<BluetoothLeDevice> c = mLeDeviceStore.getDeviceCursor();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mLeDeviceListAdapter.swapCursor(c);
                        }
                    });
                }
            }

            h2.postDelayed(this, 1000);//1 sec
        }
    }, 1000);
}

From source file:com.google.android.apps.watchme.StreamerActivity.java

private void startStreaming() {
    Log.d(MainActivity.APP_NAME, "startStreaming");

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, this.getClass().getName());
    wakeLock.acquire();//w w  w .  j a v  a 2s  .c o m

    if (!streamerService.isStreaming()) {

        String cameraPermission = Manifest.permission.CAMERA;
        String microphonePermission = Manifest.permission.RECORD_AUDIO;
        int hasCamPermission = checkSelfPermission(cameraPermission);
        int hasMicPermission = checkSelfPermission(microphonePermission);
        List<String> permissions = new ArrayList<String>();
        if (hasCamPermission != PackageManager.PERMISSION_GRANTED) {
            permissions.add(cameraPermission);
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                // Provide rationale in Snackbar to request permission
                //                    Snackbar.make(preview, R.string.permission_camera_rationale,
                //                            Snackbar.LENGTH_INDEFINITE).show();
            } else {
                // Explain in Snackbar to turn on permission in settings
                //                    Snackbar.make(preview, R.string.permission_camera_explain,
                //                            Snackbar.LENGTH_INDEFINITE).show();
            }
        }
        if (hasMicPermission != PackageManager.PERMISSION_GRANTED) {
            permissions.add(microphonePermission);
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
                // Provide rationale in Snackbar to request permission
                //                    Snackbar.make(preview, R.string.permission_microphone_rationale,
                //                            Snackbar.LENGTH_INDEFINITE).show();
            } else {
                // Explain in Snackbar to turn on permission in settings
                //                    Snackbar.make(preview, R.string.permission_microphone_explain,
                //                            Snackbar.LENGTH_INDEFINITE).show();
            }
        }
        if (!permissions.isEmpty()) {
            String[] params = permissions.toArray(new String[permissions.size()]);
            ActivityCompat.requestPermissions(this, params, REQUEST_CAMERA_MICROPHONE);
        } else {
            // We already have permission, so handle as normal
            streamerService.startStreaming(rtmpUrl);
        }
    }
}

From source file:com.interestfriend.activity.FeedBackActivity.java

private void setUpView() {
    activityInstance = this;
    iv_emoticons_normal.setOnClickListener(this);
    iv_emoticons_checked.setOnClickListener(this);
    // position = getIntent().getIntExtra("position", -1);
    clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
            .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");
    // //  w w  w .  java  2 s  .c  o  m
    chatType = CHATTYPE_SINGLE;
    txt_title.setText("");
    conversation = EMChatManager.getInstance().getConversation(toChatUsername);
    // 0
    conversation.resetUnsetMsgCount();
    adapter = new ChatAdapter(this, toChatUsername, chatType, -1);
    // 
    listView.setAdapter(adapter);
    listView.setOnScrollListener(new ListScrollListener());
    int count = listView.getCount();
    if (count > 0) {
        listView.setSelection(count - 1);
    }

    listView.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            hideKeyboard();
            more.setVisibility(View.GONE);
            iv_emoticons_normal.setVisibility(View.VISIBLE);
            iv_emoticons_checked.setVisibility(View.INVISIBLE);
            expressionContainer.setVisibility(View.GONE);
            return false;
        }
    });
    // 
    receiver = new NewMessageBroadcastReceiver();
    IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
    // Mainacitivity,chat
    intentFilter.setPriority(5);
    registerReceiver(receiver, intentFilter);

    // ackBroadcastReceiver
    IntentFilter ackMessageIntentFilter = new IntentFilter(
            EMChatManager.getInstance().getAckMessageBroadcastAction());
    ackMessageIntentFilter.setPriority(5);
    registerReceiver(ackMessageReceiver, ackMessageIntentFilter);

    // BroadcastReceiver
    IntentFilter deliveryAckMessageIntentFilter = new IntentFilter(
            EMChatManager.getInstance().getDeliveryAckMessageBroadcastAction());
    deliveryAckMessageIntentFilter.setPriority(5);
    registerReceiver(deliveryAckMessageReceiver, deliveryAckMessageIntentFilter);

    // show forward message if the message is not null
    String forward_msg_id = getIntent().getStringExtra("forward_msg_id");
    if (forward_msg_id != null) {
        // 
        forwardMessage(forward_msg_id);
    }

}

From source file:com.yi4all.rupics.ImageDetailActivity.java

public void startSlideShow() {
    Runnable slide = new Runnable() {

        @Override//from   w w w  . j a v  a2 s  .  c  o m
        public void run() {
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, LOGTAG);
            wl.acquire();
            while (isSlideshow) {
                if (imageSequence < imgList.size() - 1) {
                    // back to the next image
                    imageSequence++;
                    setCurrentPage();
                } else {
                    // give a tip to user
                    Utils.toastMsg(ImageDetailActivity.this, R.string.alreadyLast);
                    isSlideshow = false;
                }
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    Log.e(LOGTAG, "startSlideShow:" + ((e != null) ? e.getMessage() : "exception is null"));
                }

                // if(ImageDetailActivity.this.)
            }
            if (wl.isHeld())
                wl.release();
        }
    };
    new Thread(slide).start();

}