Example usage for android.os PowerManager newWakeLock

List of usage examples for android.os PowerManager newWakeLock

Introduction

In this page you can find the example usage for android.os PowerManager newWakeLock.

Prototype

public WakeLock newWakeLock(int levelAndFlags, String tag) 

Source Link

Document

Creates a new wake lock with the specified level and flags.

Usage

From source file:org.gateshipone.malp.application.artworkdatabase.BulkDownloadService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    if (intent != null && intent.getAction() != null && intent.getAction().equals(ACTION_START_BULKDOWNLOAD)) {
        Log.v(TAG, "Starting bulk download in service with thread id: " + Thread.currentThread().getId());

        // reset counter
        mRemainingArtists = 0;//from  www  .  j a v  a 2s.c  o m
        mRemainingAlbums = 0;
        mSumImageDownloads = 0;

        String artistProvider = getString(R.string.pref_artwork_provider_artist_default);
        String albumProvider = getString(R.string.pref_artwork_provider_album_default);
        mWifiOnly = true;

        // read setting from extras
        Bundle extras = intent.getExtras();
        if (extras != null) {
            artistProvider = extras.getString(BUNDLE_KEY_ARTIST_PROVIDER,
                    getString(R.string.pref_artwork_provider_artist_default));
            albumProvider = extras.getString(BUNDLE_KEY_ALBUM_PROVIDER,
                    getString(R.string.pref_artwork_provider_album_default));
            mWifiOnly = intent.getBooleanExtra(BUNDLE_KEY_WIFI_ONLY, true);
        }

        ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (null == netInfo) {
            return START_NOT_STICKY;
        }
        boolean isWifi = netInfo.getType() == ConnectivityManager.TYPE_WIFI
                || netInfo.getType() == ConnectivityManager.TYPE_ETHERNET;

        if (mWifiOnly && !isWifi) {
            return START_NOT_STICKY;
        }

        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        mWakelock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MALP_BulkDownloader");

        ArtworkManager artworkManager = ArtworkManager.getInstance(getApplicationContext());
        artworkManager.initialize(artistProvider, albumProvider, mWifiOnly);

        // FIXME do some timeout checking. e.g. 5 minutes no new image then cancel the process
        mWakelock.acquire();
        ConnectionManager.reconnectLastServer(this);
    }
    return START_NOT_STICKY;

}

From source file:com.daiv.android.twitter.utils.NotificationUtils.java

public static void sendTestNotification(Context context) {

    if (!TEST_NOTIFICATION) {
        return;/*from   w ww .j a va 2  s  .  com*/
    }

    AppSettings settings = AppSettings.getInstance(context);

    SharedPreferences sharedPrefs = context.getSharedPreferences("com.daiv.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    Intent markRead = new Intent(context, MarkReadService.class);
    PendingIntent readPending = PendingIntent.getService(context, 0, markRead, 0);

    String shortText = "Test Test";
    String longText = "Here is a test for Test's notifications";

    Intent resultIntent = new Intent(context, RedirectToMentions.class);

    PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0);

    NotificationCompat.Builder mBuilder;

    Intent deleteIntent = new Intent(context, NotificationDeleteReceiverOne.class);

    mBuilder = new NotificationCompat.Builder(context).setContentTitle(shortText).setContentText(longText)
            .setSmallIcon(R.drawable.ic_stat_icon)
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
            .setContentIntent(resultPendingIntent).setAutoCancel(true).setTicker(shortText)
            .setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0))
            .setPriority(NotificationCompat.PRIORITY_HIGH);

    // Pebble notification
    if (sharedPrefs.getBoolean("pebble_notification", false)) {
        sendAlertToPebble(context, shortText, shortText);
    }

    // Light Flow notification
    sendToLightFlow(context, shortText, shortText);

    if (settings.vibrate) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

    if (settings.sound) {
        try {
            mBuilder.setSound(Uri.parse(settings.ringtone));
        } catch (Exception e) {
            e.printStackTrace();
            mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        }
    }

    if (settings.led)
        mBuilder.setLights(0xFFFFFF, 1000, 1000);

    // Get an instance of the NotificationManager service
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

    Intent reply = null;
    MentionsDataSource data = MentionsDataSource.getInstance(context);
    PendingIntent replyPending = PendingIntent.getActivity(context, 0, reply, 0);

    RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY).setLabel("@" + "daiv" + " ").build();

    // Create the notification action
    NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
            R.drawable.ic_action_reply_dark, context.getResources().getString(R.string.noti_reply),
            replyPending).addRemoteInput(remoteInput).build();

    NotificationCompat.Action.Builder action = new NotificationCompat.Action.Builder(
            R.drawable.ic_action_read_dark, context.getResources().getString(R.string.mark_read), readPending);

    mBuilder.addAction(replyAction);
    mBuilder.addAction(action.build());

    // Build the notification and issues it with notification manager.
    notificationManager.notify(1, mBuilder.build());

    // if we want to wake the screen on a new message
    if (settings.wakeScreen) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
        wakeLock.acquire(5000);
    }
}

From source file:com.android.talkback.eventprocessor.ProcessorVolumeStream.java

@SuppressWarnings("deprecation")
public ProcessorVolumeStream(FeedbackController feedbackController, CursorController cursorController,
        DimScreenController dimScreenController, TalkBackService service) {
    if (feedbackController == null)
        throw new IllegalStateException("CachedFeedbackController is null");
    if (cursorController == null)
        throw new IllegalStateException("CursorController is null");
    if (dimScreenController == null)
        throw new IllegalStateException("DimScreenController is null");

    mAudioManager = (AudioManager) service.getSystemService(Context.AUDIO_SERVICE);
    mCursorController = cursorController;
    mFeedbackController = feedbackController;

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

    mPrefs = SharedPreferencesUtils.getSharedPreferences(service);
    mService = service;//from   w w  w  .j  ava 2s. c o  m
    mDimScreenController = dimScreenController;
    mPatternDetector = new VolumeButtonPatternDetector();
    mPatternDetector.setOnPatternMatchListener(this);
}

From source file:org.jonblack.bluetrack.activities.LiveTrackingFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    Log.d(TAG, "onActivityCreated");

    super.onActivityCreated(savedInstanceState);

    PowerManager pm = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
    wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Bluetrack");

    // Restore state
    if (savedInstanceState != null) {
        mSessionId = savedInstanceState.getLong("sessionId");
        mTracking = savedInstanceState.getBoolean("tracking");

        Log.v(TAG, String.format("Restoring state: mSessionId=%d mTracking=%s", mSessionId, mTracking));

        if (mTracking) {
            // This should get the loader that was already created.
            getLoaderManager().initLoader(0, null, this);
        }//from  www  .j a  v a 2 s.  c o m
    }

    // Register broadcast receiver for bluetooth status changes
    getActivity().registerReceiver(this.mBtStateChangedReceiver,
            new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));

    // Configure the ListView adapter, which will connect to the database.
    mAdapter = new LiveTrackingCursorAdapter(getActivity(), null, 0);
    setListAdapter(mAdapter);
}

From source file:com.brayanarias.alarmproject.activity.AlarmScreenActivity.java

@Override
protected void onResume() {
    super.onResume();
    Log.e(TAG, "on Resume Method");
    // Set the window to keep screen on
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

    // Acquire wakelock
    PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
    if (wakeLock == null) {
        wakeLock = pm.newWakeLock((PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), tag);
    }//from w  w w  .  j a v  a 2s . co  m

    if (!wakeLock.isHeld()) {
        wakeLock.acquire();
    }
}

From source file:org.deviceconnect.android.deviceplugin.wear.activity.WearKeyEventProfileActivity.java

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    mWakeLock = powerManager.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK
            | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TouchWakelockTag");

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    if (!mWakeLock.isHeld()) {
        mWakeLock.acquire();/*  w  w  w  .j ava2  s  .c  o m*/
    }
    setRegisterEvent(getIntent());
    setContentView(R.layout.activity_wear_keyevent_profile);

    WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
    stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
        @Override
        public void onLayoutInflated(final WatchViewStub stub) {
            mBtnKeyMode = (Button) stub.findViewById(R.id.button_key_mode);
            mBtnKeyMode.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View v) {
                    // Update Key Mode.
                    mKeyMode++;
                    if (mKeyMode >= KM_MAX_CNT) {
                        mKeyMode = KM_STD_KEY;
                    }

                    String keyMode;
                    switch (mKeyMode) {
                    case KM_MEDIA_CTRL:
                        keyMode = getString(R.string.key_mode_media_ctrl);
                        break;
                    case KM_DPAD_BUTTON:
                        keyMode = getString(R.string.key_mode_dpad_button);
                        break;
                    case KM_USER:
                        keyMode = getString(R.string.key_mode_user);
                        break;
                    case KM_STD_KEY:
                    default:
                        keyMode = getString(R.string.key_mode_std_key);
                        break;
                    }
                    mBtnKeyMode.setText(keyMode);
                }
            });

            mBtnCancel = (Button) stub.findViewById(R.id.button_cancel);
            mBtnCancel.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(final View view, final MotionEvent event) {
                    int action = event.getAction();
                    switch (action) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_UP:
                        sendMessageData(action, KEYCODE_CANCEL);
                        break;
                    default:
                        break;
                    }
                    return false;
                }
            });

            mBtnOk = (Button) stub.findViewById(R.id.button_ok);
            mBtnOk.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(final View view, final MotionEvent event) {
                    int action = event.getAction();
                    switch (action) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_UP:
                        sendMessageData(action, KEYCODE_OK);
                        break;
                    default:
                        break;
                    }
                    return false;
                }
            });

        }
    });

    Intent i = new Intent(WearConst.ACTION_WEAR_PING_SERVICE);
    LocalBroadcastManager.getInstance(this).sendBroadcast(i);
}

From source file:org.interactiverobotics.headset_launcher.LauncherService.java

/**
 *    ?./*from ww  w .j  a v  a  2 s  .  c o m*/
 *
 */
@SuppressWarnings("deprecation")
private void unlockScreen() {

    final KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);

    mKeyguardLock = keyguardManager.newKeyguardLock("HeadsetLauncherLock");

    mKeyguardLock.disableKeyguard();

    final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

    mWakeLock = powerManager.newWakeLock(
            PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE,
            "HeadsetLauncherWakeLock");

    mWakeLock.acquire();

    // ?  ?  ?

    mTimeoutHandler.postDelayed(mTimeoutRunnable, Constants.NOTIFICATION_TIMEOUT * 1000);
}

From source file:com.daiv.android.twitter.utils.NotificationUtils.java

public static void notifySecondDMs(Context context, int secondAccount) {
    DMDataSource data = DMDataSource.getInstance(context);

    SharedPreferences sharedPrefs = context.getSharedPreferences("com.daiv.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);

    int numberNew = sharedPrefs.getInt("dm_unread_" + secondAccount, 0);

    int smallIcon = R.drawable.ic_stat_icon;
    Bitmap largeIcon;//www.java2s  .  co  m

    NotificationCompat.Builder mBuilder;

    String title = context.getResources().getString(R.string.app_name) + " - "
            + context.getResources().getString(R.string.sec_acc);
    String name;
    String message;
    String messageLong;

    NotificationCompat.InboxStyle inbox = null;
    if (numberNew == 1) {
        name = data.getNewestName(secondAccount);

        // if they are muted, and you don't want them to show muted mentions
        // then just quit
        if (sharedPrefs.getString("muted_users", "").contains(name)
                && !sharedPrefs.getBoolean("show_muted_mentions", false)) {
            return;
        }

        message = context.getResources().getString(R.string.mentioned_by) + " @" + name;
        messageLong = "<b>@" + name + "</b>: " + data.getNewestMessage(secondAccount);
        largeIcon = getImage(context, name);
    } else { // more than one dm
        message = numberNew + " " + context.getResources().getString(R.string.new_mentions);
        messageLong = "<b>" + context.getResources().getString(R.string.mentions) + "</b>: " + numberNew + " "
                + context.getResources().getString(R.string.new_mentions);
        largeIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_user_dark);

        inbox = getDMInboxStyle(numberNew, secondAccount, context, message);
    }

    Intent markRead = new Intent(context, MarkReadSecondAccService.class);
    PendingIntent readPending = PendingIntent.getService(context, 0, markRead, 0);

    AppSettings settings = AppSettings.getInstance(context);

    Intent deleteIntent = new Intent(context, NotificationDeleteReceiverTwo.class);

    mBuilder = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(TweetLinkUtils.removeColorHtml(message, settings)).setSmallIcon(smallIcon)
            .setLargeIcon(largeIcon).setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0))
            .setAutoCancel(true).setPriority(NotificationCompat.PRIORITY_HIGH);

    if (inbox == null) {
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(Html.fromHtml(
                settings.addonTheme ? messageLong.replaceAll("FF8800", settings.accentColor) : messageLong)));
    } else {
        mBuilder.setStyle(inbox);
    }

    if (settings.vibrate) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

    if (settings.sound) {
        try {
            mBuilder.setSound(Uri.parse(settings.ringtone));
        } catch (Exception e) {
            mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        }
    }

    if (settings.led)
        mBuilder.setLights(0xFFFFFF, 1000, 1000);

    if (settings.notifications) {

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

        notificationManager.notify(9, mBuilder.build());

        // if we want to wake the screen on a new message
        if (settings.wakeScreen) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                    | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
            wakeLock.acquire(5000);
        }

        // Pebble notification
        if (sharedPrefs.getBoolean("pebble_notification", false)) {
            sendAlertToPebble(context, title, messageLong);
        }

        // Light Flow notification
        sendToLightFlow(context, title, messageLong);
    }
}

From source file:org.ligi.android.dubwise_mk.BaseActivity.java

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

    DUBwisePrefs.init(this);

    if (DUBwisePrefs.keepLightNow()) {
        if (mWakeLock == null) {
            final PowerManager pm = (PowerManager) (getSystemService(Context.POWER_SERVICE));
            mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "DUBwise");
        }/*www .ja  v  a  2  s.c  om*/
        mWakeLock.acquire();
    }

    // do only once
    if (!did_init) {
        //BluetoothMaster.init(activity);
        VoicePrefs.init(this);
        StatusVoice.getInstance().init(this);
        BlackBoxPrefs.init(this);

        // start the default connection
        StartupConnectionService.start(this);

        if (BlackBoxPrefs.isBlackBoxEnabled()) {
            DUBwiseBackgroundHandler.getInstance().addAndStartTask(BlackBox.getInstance());
        }

        did_init = true;
    }

    if (VoicePrefs.isVoiceEnabled() && !DUBwiseBackgroundHandler.getInstance().getBackgroundTasks()
            .contains(StatusVoice.getInstance())) {
        DUBwiseBackgroundHandler.getInstance().addAndStartTask(StatusVoice.getInstance());
    }

    setContentView(R.layout.base_layout);
    contentView = (ViewGroup) findViewById(R.id.content_frame);

    drawerList = (ListView) findViewById(R.id.left_drawer);

    drawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            IconicMenuItem item = ((IconicMenuItem) (drawerList.getAdapter().getItem(position)));

            if (item.intent != null) {
                startActivity(item.intent);
            }

        }
    });
    refresh_list();

    //mTitle = mDrawerTitle = getTitle();
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.drawer_open,
            R.string.drawer_close) {

        /** Called when a drawer has settled in a completely closed state. */
        public void onDrawerClosed(View view) {
            //getActionBar().setTitle(mTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        /** Called when a drawer has settled in a completely open state. */
        public void onDrawerOpened(View drawerView) {
            //getActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };

    drawerLayout.setDrawerListener(drawerToggle);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    // a little hack because I strongly disagree with the style guide here
    // ;-)
    // not having the Actionbar overfow menu also with devices with hardware
    // key really helps discoverability
    // http://stackoverflow.com/questions/9286822/how-to-force-use-of-overflow-menu-on-devices-with-menu-button
    try {
        ViewConfiguration config = ViewConfiguration.get(this);
        Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
        if (menuKeyField != null) {
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        }
    } catch (Exception ex) {
        // Ignore - but at least we tried ;-)
    }

}

From source file:org.protocoderrunner.base.BaseActivity.java

public void setWakeLock(boolean b) {

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    if (wl == null) {
        wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        if (b) {//from   w  w  w.  ja va2  s .  co m
            wl.acquire();
        }
    } else {
        if (!b) {
            wl.release();
        }
    }

}