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:co.taqat.call.CallIncomingActivity.java

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

    if (getResources().getBoolean(R.bool.orientation_portrait_only)) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }/*w  ww  . jav  a2 s .  c  om*/

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    setContentView(R.layout.call_incoming);

    name = (TextView) findViewById(R.id.contact_name);
    number = (TextView) findViewById(R.id.contact_number);
    contactPicture = (ImageView) findViewById(R.id.contact_picture);

    // set this flag so this activity will stay in front of the keyguard
    int flags = WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
            | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
    getWindow().addFlags(flags);

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);

    final int screenWidth = getResources().getDisplayMetrics().widthPixels;

    acceptUnlock = (LinearLayout) findViewById(R.id.acceptUnlock);
    declineUnlock = (LinearLayout) findViewById(R.id.declineUnlock);

    accept = (ImageView) findViewById(R.id.accept);
    decline = (ImageView) findViewById(R.id.decline);
    accept.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            decline.setVisibility(View.GONE);
            acceptUnlock.setVisibility(View.VISIBLE);

        }
    });

    accept.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            float curX;
            switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                acceptUnlock.setVisibility(View.VISIBLE);
                decline.setVisibility(View.GONE);
                answerX = motionEvent.getX();
                break;
            case MotionEvent.ACTION_MOVE:
                curX = motionEvent.getX();
                if ((answerX - curX) >= 0)
                    view.scrollBy((int) (answerX - curX), view.getScrollY());
                answerX = curX;
                if (curX < screenWidth / 4) {
                    answer();
                    return true;
                }
                break;
            case MotionEvent.ACTION_UP:
                view.scrollTo(0, view.getScrollY());
                decline.setVisibility(View.VISIBLE);
                acceptUnlock.setVisibility(View.GONE);
                break;
            }
            return true;
        }
    });

    decline.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            float curX;
            switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                declineUnlock.setVisibility(View.VISIBLE);
                accept.setVisibility(View.GONE);
                declineX = motionEvent.getX();
                break;
            case MotionEvent.ACTION_MOVE:
                curX = motionEvent.getX();
                view.scrollBy((int) (declineX - curX), view.getScrollY());
                declineX = curX;
                Log.w(curX);
                if (curX > (screenWidth / 2)) {
                    decline();
                    return true;
                }
                break;
            case MotionEvent.ACTION_UP:
                view.scrollTo(0, view.getScrollY());
                accept.setVisibility(View.VISIBLE);
                declineUnlock.setVisibility(View.GONE);
                break;

            }
            return true;
        }
    });

    decline.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            accept.setVisibility(View.GONE);
            acceptUnlock.setVisibility(View.VISIBLE);
        }
    });

    mListener = new LinphoneCoreListenerBase() {
        @Override
        public void callState(LinphoneCore lc, LinphoneCall call, State state, String message) {
            if (call == mCall && State.CallEnd == state) {
                finish();
            }
            if (state == State.StreamsRunning) {
                // The following should not be needed except some devices need it (e.g. Galaxy S).
                LinphoneManager.getLc().enableSpeaker(LinphoneManager.getLc().isSpeakerEnabled());
            }
        }
    };

    super.onCreate(savedInstanceState);
    instance = this;
}

From source file:cn.xcom.helper.chat.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  www .ja v  a 2s  . 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();

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

    inviteMessgeDao = new InviteMessgeDao(this);
    userDao = new UserDao(this);
    conversationListFragment = new ConversationListFragment();
    contactListFragment = new ContactListFragment();
    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:at.tugraz.ist.akm.webservice.server.SimpleWebServer.java

public SimpleWebServer(Context context, WebserverProtocolConfig serverConfig, IHttpAccessCallback callback)
        throws Exception {
    mHttpAuthCallback = callback;//from  w  w  w  .j  a v  a  2  s .  co  m
    mContext = context;
    PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);

    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    WifiIpAddress wifiAddressReader = new WifiIpAddress(context);

    mSocketAddress = InetAddress.getByName(wifiAddressReader.readLocalIpAddress());
    wifiAddressReader.close();
    wifiAddressReader = null;

    setNewServerConfiguration(serverConfig);

    mLog.debug("building server for [" + mServerConfig.protocolName + "://" + mSocketAddress + ":"
            + mServerConfig.port + "]");
    readRequestHandlers();
    readRequestInterceptors();
}

From source file:it.baywaylabs.jumpersumo.robot.Daemon.java

/**
 * Method auto invoked pre execute the task.
 *///from   ww  w . j a v a2  s  .c  o m
@Override
protected void onPreExecute() {
    super.onPreExecute();
    // take CPU lock to prevent CPU from going off if the user
    // presses the power button during download
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
    mWakeLock.acquire();
    folder = new File(Constants.DIR_ROBOT_DAEMON);
    if (!folder.exists()) {
        folder.mkdir();
    }
}

From source file:com.hyphenate.chatuidemo.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 .  ja  v a  2s. co 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);

    showExceptionDialogFromIntent(getIntent());

    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:com.mobile.lapa.waitandsee.MyGcmListenerService.java

/**
 * Create and show a simple notification containing the received GCM message.
 *
 * @param title//  ww  w  . j a va2 s .  c o m
 * @param message GCM message received.
 */
private void sendNotification(String title, String message) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);

    intent.putExtra("TITLE_KEY", title);
    intent.putExtra("MESSAGE_KEY", message);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.game_finished);
    //Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.sap_logo).setContentTitle(title).setContentText(message)
            .setAutoCancel(true).setSound(defaultSoundUri).setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);

    //        Random random = new Random();
    //        int notificationId = random.nextInt(9999 - 1000) + 1000;
    notificationManager.notify(0 /*notificationId*/, notificationBuilder.build());

    // -------- Wake up the phone and show the main activity
    PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock mWakeLock = pm.newWakeLock(
            (PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "MainServiceTag");
    mWakeLock.acquire();

    // ------- Send notification to the android system
    startActivity(intent);
    mWakeLock.release();
}

From source file:net.czlee.debatekeeper.AlertManager.java

/**
 * Constructor.// w w  w . j  a v a 2s.  c  o m
 * @param debatingTimerService The instance of {@link DebatingTimerService} to which this
 * AlertManager relates
 */
public AlertManager(Service debatingTimerService) {

    mService = debatingTimerService;

    // System services
    mNotificationManager = (NotificationManager) debatingTimerService
            .getSystemService(Context.NOTIFICATION_SERVICE);
    mVibrator = (Vibrator) debatingTimerService.getSystemService(Context.VIBRATOR_SERVICE);
    mPowerManager = (PowerManager) mService.getSystemService(Context.POWER_SERVICE);

    // Create a PendingIntent for the notification we raise while the timer is running.
    Intent intent = new Intent(debatingTimerService, DebatingActivity.class);
    // This flag prevents the activity from having multiple instances on the back stack,
    // so that when the user presses the notification while already in Debatekeeper, pressing
    // back won't make the user go through several instances of Debatekeeper on the back stack.
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    mIntentForOngoingNotification = PendingIntent.getActivity(debatingTimerService, 0, intent, 0);

    // Set up defaults
    Resources res = mService.getResources();
    mSilentMode = res.getBoolean(R.bool.prefDefault_silentMode);
    mVibrateMode = res.getBoolean(R.bool.prefDefault_vibrateMode);

    createWakeLock();
}

From source file:net.micode.soundrecorder.RecorderService.java

@Override
public void onCreate() {
    super.onCreate();
    mRecorder = null;/*w  w w .j  ava 2 s  . c o  m*/
    mLowStorageNotification = null;
    mRemainingTimeCalculator = new RemainingTimeCalculator();
    mNeedUpdateRemainingTime = false;
    mNotifiManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "SoundRecorder");
    mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);

    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    mAudioSampleRate = Integer
            .parseInt(settings.getString("p_audio_samplerate", Constants.DEFAULT_AUDIO_SAMPLE_RATE));

}

From source file:com.groundupworks.wings.core.WingsService.java

/**
 * Acquires a wake lock.//from  ww  w.j  av  a2  s  .c  o m
 *
 * @param context the {@link Context}.
 */
private synchronized static void acquireWakeLock(Context context) {
    // Setup wake lock.
    if (sWakeLock == null) {
        PowerManager powerManager = (PowerManager) context.getApplicationContext()
                .getSystemService(Context.POWER_SERVICE);
        sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, NAME);
        sWakeLock.setReferenceCounted(true);
    }

    // Acquire lock.
    sWakeLock.acquire();

    sLogger.log(WingsService.class, "acquireWakeLock", "sWakeLock=" + sWakeLock);
}

From source file:com.ichi2.async.Connection.java

public Connection() {
    sIsCancelled = false;/*from w w  w  .  ja  v  a  2s .c o  m*/
    sIsCancellable = false;
    Context context = AnkiDroidApp.getInstance().getApplicationContext();
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Connection");
}