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.volosyukivan.WiFiInputMethod.java

@Override
public void onCreate() {
    super.onCreate();
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE,
            "wifikeyboard");
    //    Debug.d("WiFiInputMethod started");
    serviceConnection = new ServiceConnection() {
        //@Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //        Debug.d("WiFiInputMethod connected to HttpService.");
            try {
                remoteKeyboard = RemoteKeyboard.Stub.asInterface(service);
                keyboardListener = new RemoteKeyListener.Stub() {
                    @Override//from  w  w w.j  av a  2 s .  co m
                    public void keyEvent(int code, boolean pressed) throws RemoteException {
                        // Debug.d("got key in WiFiInputMethod");
                        receivedKey(code, pressed);
                    }

                    @Override
                    public void charEvent(int code) throws RemoteException {
                        // Debug.d("got key in WiFiInputMethod");
                        receivedChar(code);
                    }

                    @Override
                    public boolean setText(String text) throws RemoteException {
                        return WiFiInputMethod.this.setText(text);
                    }

                    @Override
                    public String getText() throws RemoteException {
                        return WiFiInputMethod.this.getText();
                    }
                };
                RemoteKeyboard.Stub.asInterface(service).registerKeyListener(keyboardListener);
            } catch (RemoteException e) {
                throw new RuntimeException("WiFiInputMethod failed to connected to HttpService.", e);
            }
        }

        //@Override
        public void onServiceDisconnected(ComponentName name) {
            //        Debug.d("WiFiInputMethod disconnected from HttpService.");
        }
    };
    if (this.bindService(new Intent(this, HttpService.class), serviceConnection, BIND_AUTO_CREATE) == false) {
        throw new RuntimeException("failed to connect to HttpService");
    }
}

From source file:cx.ring.fragments.CallFragment.java

@Override
public void onCreate(Bundle savedBundle) {
    Log.i(TAG, "onCreate");
    super.onCreate(savedBundle);

    audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);

    setHasOptionsMenu(true);/*from   w  ww. j a v a2  s  .  c o  m*/
    PowerManager powerManager = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
    mScreenWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
            | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "cx.ring.onIncomingCall");
    mScreenWakeLock.setReferenceCounted(false);

    Log.d(TAG, "Acquire wake up lock");
    if (mScreenWakeLock != null && !mScreenWakeLock.isHeld()) {
        mScreenWakeLock.acquire();
    }
}

From source file:com.aniruddhc.acemusic.player.AsyncTasks.AsyncGetGooglePlayMusicMetadataTask.java

@Override
protected void onPreExecute() {
    super.onPreExecute();

    //Hide the actionbar.
    mApp.setIsBuildingLibrary(true);//  www  . j  ava 2 s.com

    //Acquire a wakelock to prevent the CPU from sleeping while the process is running.
    pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
            "com.aniruddhc.acemusic.player.AsyncTasks.AsyncGetGooglePlayMusicMetadata");
    wakeLock.acquire();

    //Set the initial setting of the progressbar as indeterminate.
    currentTask = mContext.getResources().getString(R.string.contacting_google_play_music);

}

From source file:com.jams.music.player.AsyncTasks.AsyncGetGooglePlayMusicMetadataTask.java

@Override
protected void onPreExecute() {
    super.onPreExecute();

    //Hide the actionbar.
    mApp.setIsBuildingLibrary(true);//from  w w  w  .ja  v  a  2  s.  c o m

    //Acquire a wakelock to prevent the CPU from sleeping while the process is running.
    pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
            "com.jams.music.player.AsyncTasks.AsyncGetGooglePlayMusicMetadata");
    wakeLock.acquire();

    //Set the initial setting of the progressbar as indeterminate.
    currentTask = mContext.getResources().getString(R.string.contacting_google_play_music);

}

From source file:com.digutsoft.metronome.DMFSetTempo.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.settempo, container, false);

    sbTempo = (SeekBar) rootView.findViewById(R.id.sbTempo);
    tvTempo = (TextView) rootView.findViewById(R.id.tvTempo);
    final CircledImageView btStart = (CircledImageView) rootView.findViewById(R.id.btStart);
    final CircledImageView btPlus = (CircledImageView) rootView.findViewById(R.id.btPlus);
    final CircledImageView btMinus = (CircledImageView) rootView.findViewById(R.id.btMinus);

    mContext = getActivity().getApplicationContext();

    final Context mContext = getActivity();
    sharedPreferences = mContext.getSharedPreferences("dMetronome", 0);
    int defaultTempo = sharedPreferences.getInt("tempo", 80);
    setTempo(defaultTempo);/*ww w  .  ja  v a  2s .  c om*/

    Intent viewIntent = new Intent(getActivity(), DMAMain.class);
    PendingIntent viewPendingIntent = PendingIntent.getActivity(getActivity(), 0, viewIntent, 0);

    notificationBuilder = new NotificationCompat.Builder(getActivity()).setOngoing(true)
            .setSmallIcon(R.drawable.ic_launcher).setContentTitle(getString(R.string.app_name))
            .setContentIntent(viewPendingIntent);

    notificationManager = NotificationManagerCompat.from(getActivity());

    Vibrator vibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
    metronome = new DMCMetronome(getActivity(), vibrator, rootView.findViewById(R.id.bilBackground));

    PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getString(R.string.app_name));

    sbTempo.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            setTempo(i);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });

    btStart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (mTempo == 0) {
                Toast.makeText(getActivity(), R.string.tempo_zero, Toast.LENGTH_LONG).show();
                return;
            }

            if (DMCMetronome.mRunning) {
                metronome.stopTick();

                sbTempo.setEnabled(true);
                tvTempo.setText(Integer.toString(mTempo));
                btStart.setImageDrawable(getResources().getDrawable(R.drawable.ic_start));
                btStart.setCircleColor(getResources().getColor(R.color.green));
                btPlus.setVisibility(View.VISIBLE);
                btMinus.setVisibility(View.VISIBLE);

                wakeLock.release();

                notificationManager.cancel(1);
            } else {
                metronome.startTick(mTempo);

                sbTempo.setEnabled(false);
                btStart.setImageDrawable(getResources().getDrawable(R.drawable.ic_stop));
                btStart.setCircleColor(getResources().getColor(R.color.red));
                btPlus.setVisibility(View.GONE);
                btMinus.setVisibility(View.GONE);

                wakeLock.acquire();

                notificationBuilder
                        .setContentText(String.format(getString(R.string.notification_running), mTempo));
                notificationManager.notify(1, notificationBuilder.build());

                sharedPreferences.edit().putInt("tempo", mTempo).apply();
            }
        }
    });

    btPlus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            setTempo(mTempo + 1);
        }
    });

    btMinus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            setTempo(mTempo - 1);
        }
    });

    return rootView;
}

From source file:com.smart.taxi.GcmIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();/*from  w  ww .j a  v a 2s .c  o m*/
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    // The getMessageType() intent parameter must be the intent you received
    // in your BroadcastReceiver.
    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) { // has effect of unparcelling Bundle
        String msg = extras.toString();
        /*
         * Filter messages based on message type. Since it is likely that GCM
         * will be extended in the future with new message types, just ignore
         * any message types you're not interested in, or that you don't
         * recognize.
         */
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
            sendNotification("Send error: " + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            sendNotification("Deleted messages on server: " + extras.toString());
            // If it's a regular GCM message, do some work.
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
            // This loop represents the service doing some work.
            /*for (int i=0; i<0; i++) {
            Log.i(TAG, "Working... " + (i+1)
                    + "/5 @ " + SystemClock.elapsedRealtime());
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
            }
            }*/
            Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
            // Post notification of received message.
            sendNotification(extras);
            try {

                PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
                PowerManager.WakeLock wl = pm.newWakeLock(
                        PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "My Tag");
                wl.acquire();
                wl.release();

            } catch (Exception ex) {
                Log.e("Wake lock acquire error:", ex.toString());
            }
            // Log.i(TAG, "Received: " + extras.toString());

        }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

From source file:com.abroad.ruianju.im.ui.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        String packageName = getPackageName();
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (!pm.isIgnoringBatteryOptimizations(packageName)) {
            Intent intent = new Intent();
            intent.setAction(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + packageName));
            startActivity(intent);/*w w w  .  j a  v  a 2 s.c  o  m*/
        }
    }

    //make sure activity will not in background if user is logged into another device or removed
    if (savedInstanceState != null && savedInstanceState.getBoolean(Constant.ACCOUNT_REMOVED, false)) {
        DemoHelper.getInstance().logout(false, null);
        finish();
        startActivity(new Intent(this, LoginActivity.class));
        return;
    } else if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) {
        finish();
        startActivity(new Intent(this, LoginActivity.class));
        return;
    }
    setContentView(R.layout.em_activity_main);
    // runtime permission for android 6.0, just require all permissions here for simple
    requestPermissions();

    initView();

    //umeng api
    //      MobclickAgent.updateOnlineConfig(this);
    //      UmengUpdateAgent.setUpdateOnlyWifi(false);
    //      UmengUpdateAgent.update(this);

    if (getIntent().getBooleanExtra(Constant.ACCOUNT_CONFLICT, false) && !isConflictDialogShow) {
        showConflictDialog();
    } else if (getIntent().getBooleanExtra(Constant.ACCOUNT_REMOVED, false) && !isAccountRemovedDialogShow) {
        showAccountRemovedDialog();
    }

    inviteMessgeDao = new InviteMessgeDao(this);
    UserDao userDao = new UserDao(this);
    conversationListFragment = new ConversationListFragment();
    contactListFragment = new ContactListFragment();
    SettingsFragment settingFragment = new SettingsFragment();
    fragments = new Fragment[] { conversationListFragment, contactListFragment, settingFragment };

    getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, conversationListFragment)
            .add(R.id.fragment_container, contactListFragment).hide(contactListFragment)
            .show(conversationListFragment).commit();

    //register broadcast receiver to receive the change of group from DemoHelper
    registerBroadcastReceiver();

    EMClient.getInstance().contactManager().setContactListener(new MyContactListener());
    //debug purpose only
    registerInternalDebugReceiver();
}

From source file:me.myatminsoe.myansms.SmsReceiver.java

static void handleOnReceive(final BroadcastReceiver receiver, final Context context, final Intent intent) {
    final String action = intent.getAction();
    final PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    final PowerManager.WakeLock wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    wakelock.acquire();/*w w  w .  j ava  2  s  .  c  o  m*/

    try {

        Thread.sleep(SLEEP);
    } catch (InterruptedException e) {

        e.printStackTrace();
    }
    String t = null;
    if (SenderActivity.MESSAGE_SENT_ACTION.equals(action)) {
        handleSent(context, intent, receiver.getResultCode());
    } else {
        boolean silent = false;

        if (ACTION_SMS_OLD.equals(action) || ACTION_SMS_NEW.equals(action)) {
            Bundle b = intent.getExtras();
            assert b != null;
            Object[] messages = (Object[]) b.get("pdus");
            SmsMessage[] smsMessage = new SmsMessage[messages.length];
            int l = messages.length;
            for (int i = 0; i < l; i++) {
                smsMessage[i] = SmsMessage.createFromPdu((byte[]) messages[i]);
            }
            t = null;
            if (l > 0) {
                // concatenate multipart SMS body
                StringBuilder sbt = new StringBuilder();
                for (int i = 0; i < l; i++) {
                    sbt.append(smsMessage[i].getMessageBody());
                }
                t = sbt.toString();

                // ! Check in blacklist db - filter spam
                String s = smsMessage[0].getDisplayOriginatingAddress();

                // this code is used to strip a forwarding agent and display the orginated number as sender
                final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
                if (prefs.getBoolean(PreferencesActivity.PREFS_FORWARD_SMS_CLEAN, false) && t.contains(":")) {
                    Pattern smsPattern = Pattern.compile("([0-9a-zA-Z+]+):");
                    Matcher m = smsPattern.matcher(t);
                    if (m.find()) {
                        s = m.group(1);
                        // now strip the sender from the message
                        Pattern textPattern = Pattern.compile("^[0-9a-zA-Z+]+: (.*)");
                        Matcher m2 = textPattern.matcher(t);
                        if (t.contains(":") && m2.find()) {
                            t = m2.group(1);
                            Log.d(TAG, "stripped the message");
                        }
                    }
                }

                final SpamDB db = new SpamDB(context);
                db.open();
                if (db.isInDB(smsMessage[0].getOriginatingAddress())) {

                    silent = true;
                }
                db.close();

                if (action.equals(ACTION_SMS_NEW)) {
                    // API19+: save message to the database
                    ContentValues values = new ContentValues();
                    values.put("address", s);
                    values.put("body", t);
                    context.getContentResolver().insert(Uri.parse("content://sms/inbox"), values);
                }
            }
        } else if (ACTION_MMS_OLD.equals(action) || ACTION_MMS_MEW.equals(action)) {
            t = MMS_BODY;
            // TODO API19+ MMS code
        }

        if (!silent) {

            int count = MAX_SPINS;
            do {

                try {

                    Thread.sleep(SLEEP);
                } catch (InterruptedException e) {

                    e.printStackTrace();
                }
                --count;
            } while (updateNewMessageNotification(context, t) <= 0 && count > 0);
            if (count == 0) { // use messages as they are available
                updateNewMessageNotification(context, null);
            }
        }
    }
    wakelock.release();
    Log.i(TAG, "wakelock released");
}

From source file:com.google.android.marvin.mytalkback.ProcessorVolumeStream.java

@SuppressWarnings("deprecation")
public ProcessorVolumeStream(TalkBackService service) {
    mContext = service;//from  w ww.j a  v a 2s  . c  o  m
    mAudioManager = (AudioManager) service.getSystemService(Context.AUDIO_SERVICE);
    mCursorController = service.getCursorController();
    mLongPressHandler = new LongPressHandler(this);

    final PowerManager pm = (PowerManager) service.getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, WL_TAG);
}

From source file:com.avcall.app.ui.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        String packageName = getPackageName();
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (!pm.isIgnoringBatteryOptimizations(packageName)) {
            Intent intent = new Intent();
            intent.setAction(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + packageName));
            startActivity(intent);/*from w  w w.java2s.  com*/
        }
    }

    //make sure activity will not in background if user is logged into another device or removed
    if (savedInstanceState != null && savedInstanceState.getBoolean(Constant.ACCOUNT_REMOVED, false)) {
        AvcallHelper.getInstance().logout(false, null);
        finish();
        startActivity(new Intent(this, LoginActivity.class));
        return;
    } else if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) {
        finish();
        startActivity(new Intent(this, LoginActivity.class));
        return;
    }
    setContentView(R.layout.em_activity_main);
    // runtime permission for android 6.0, just require all permissions here for simple
    requestPermissions();

    initView();

    if (getIntent().getBooleanExtra(Constant.ACCOUNT_CONFLICT, false) && !isConflictDialogShow) {
        showConflictDialog();
    } else if (getIntent().getBooleanExtra(Constant.ACCOUNT_REMOVED, false) && !isAccountRemovedDialogShow) {
        showAccountRemovedDialog();
    }

    inviteMessgeDao = new InviteMessgeDao(this);
    UserDao userDao = new UserDao(this);
    conversationListFragment = new ConversationListFragment();
    contactListFragment = new ContactListFragment();
    SettingsFragment settingFragment = new SettingsFragment();
    fragments = new Fragment[] { conversationListFragment, contactListFragment, settingFragment };

    getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, conversationListFragment)
            .add(R.id.fragment_container, contactListFragment).hide(contactListFragment)
            .show(conversationListFragment).commit();

    //register broadcast receiver to receive the change of group from DemoHelper
    registerBroadcastReceiver();

    EMClient.getInstance().contactManager().setContactListener(new MyContactListener());
    //debug purpose only
    registerInternalDebugReceiver();
}