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:com.tct.mail.utils.NotificationUtils.java

/**
 * Validate the notifications notification.
 *//*from  w  w w.ja  v a2s.c o m*/
private static void validateNotifications(Context context, final Folder folder, final Account account,
        boolean getAttention, boolean ignoreUnobtrusiveSetting, NotificationKey key,
        final ContactPhotoFetcher photoFetcher) {

    NotificationManagerCompat nm = NotificationManagerCompat.from(context);

    final NotificationMap notificationMap = getNotificationMap(context);
    if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
        LogUtils.i(LOG_TAG,
                "Validating Notification: %s mapSize: %d "
                        + "folder: %s getAttention: %b ignoreUnobtrusive: %b",
                createNotificationString(notificationMap), notificationMap.size(), folder.name, getAttention,
                ignoreUnobtrusiveSetting);
    } else {
        LogUtils.i(LOG_TAG, "Validating Notification, mapSize: %d " + "getAttention: %b ignoreUnobtrusive: %b",
                notificationMap.size(), getAttention, ignoreUnobtrusiveSetting);
    }
    // The number of unread messages for this account and label.
    final Integer unread = notificationMap.getUnread(key);
    final int unreadCount = unread != null ? unread.intValue() : 0;
    final Integer unseen = notificationMap.getUnseen(key);
    int unseenCount = unseen != null ? unseen.intValue() : 0;

    Cursor cursor = null;

    try {
        final Uri.Builder uriBuilder = folder.conversationListUri.buildUpon();
        uriBuilder.appendQueryParameter(UIProvider.SEEN_QUERY_PARAMETER, Boolean.FALSE.toString());
        // Do not allow this quick check to disrupt any active network-enabled conversation
        // cursor.
        uriBuilder.appendQueryParameter(UIProvider.ConversationListQueryParameters.USE_NETWORK,
                Boolean.FALSE.toString());
        cursor = context.getContentResolver().query(uriBuilder.build(), UIProvider.CONVERSATION_PROJECTION,
                null, null, null);
        if (cursor == null) {
            // This folder doesn't exist.
            LogUtils.i(LOG_TAG, "The cursor is null, so the specified folder probably does not exist");
            clearFolderNotification(context, account, folder, false);
            return;
        }
        final int cursorUnseenCount = cursor.getCount();

        // Make sure the unseen count matches the number of items in the cursor.  But, we don't
        // want to overwrite a 0 unseen count that was specified in the intent
        if (unseenCount != 0 && unseenCount != cursorUnseenCount) {
            LogUtils.i(LOG_TAG, "Unseen count doesn't match cursor count.  unseen: %d cursor count: %d",
                    unseenCount, cursorUnseenCount);
            unseenCount = cursorUnseenCount;
        }

        // For the purpose of the notifications, the unseen count should be capped at the num of
        // unread conversations.
        if (unseenCount > unreadCount) {
            unseenCount = unreadCount;
        }

        final int notificationId = getNotificationId(account.getAccountManagerAccount(), folder);

        NotificationKey notificationKey = new NotificationKey(account, folder);

        if (unseenCount == 0) {
            LogUtils.i(LOG_TAG, "validateNotifications - cancelling account %s / folder %s",
                    LogUtils.sanitizeName(LOG_TAG, account.getEmailAddress()),
                    LogUtils.sanitizeName(LOG_TAG, folder.persistentId));
            //TS: Gantao 2015-08-25 EMAIL BUGFIX_1073998 MOD_S
            //May happen SecurityException while cancle notification,only catch it.
            try {
                nm.cancel(notificationId);
            } catch (SecurityException se) {
                LogUtils.e(LOG_TAG, "Can not find the pacakage while cancle the notification: %d",
                        notificationId);
            }
            //TS: Gantao 2015-08-25 EMAIL BUGFIX_1073998 MOD_E
            cancelConversationNotifications(notificationKey, nm);

            return;
        }

        // We now have all we need to create the notification and the pending intent
        PendingIntent clickIntent = null;

        NotificationCompat.Builder notification = new NotificationCompat.Builder(context);
        NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender();
        Map<Integer, NotificationBuilders> msgNotifications = new ArrayMap<Integer, NotificationBuilders>();

        if (com.tct.mail.utils.Utils.isRunningLOrLater()) {
            notification.setColor(context.getResources().getColor(R.color.notification_icon_mail_orange));
        }
        // TODO(shahrk) - fix for multiple mail
        // if(folder.notificationIconResId != 0 || unseenCount <=  2)
        notification.setSmallIcon(R.drawable.ic_notification_mail_24dp);
        notification.setTicker(account.getDisplayName());
        notification.setVisibility(NotificationCompat.VISIBILITY_PRIVATE);

        final long when;

        final long oldWhen = NotificationActionUtils.sNotificationTimestamps.get(notificationId);
        if (oldWhen != 0) {
            when = oldWhen;
        } else {
            when = System.currentTimeMillis();
        }

        notification.setWhen(when);

        // The timestamp is now stored in the notification, so we can remove it from here
        NotificationActionUtils.sNotificationTimestamps.delete(notificationId);

        // Dispatch a CLEAR_NEW_MAIL_NOTIFICATIONS intent if the user taps the "X" next to a
        // notification.  Also this intent gets fired when the user taps on a notification as
        // the AutoCancel flag has been set
        final Intent cancelNotificationIntent = new Intent(
                MailIntentService.ACTION_CLEAR_NEW_MAIL_NOTIFICATIONS);
        cancelNotificationIntent.setPackage(context.getPackageName());
        cancelNotificationIntent.setData(Utils.appendVersionQueryParameter(context, folder.folderUri.fullUri));
        cancelNotificationIntent.putExtra(Utils.EXTRA_ACCOUNT, account);
        cancelNotificationIntent.putExtra(Utils.EXTRA_FOLDER, folder);

        notification.setDeleteIntent(
                PendingIntent.getService(context, notificationId, cancelNotificationIntent, 0));

        // Ensure that the notification is cleared when the user selects it
        notification.setAutoCancel(true);

        boolean eventInfoConfigured = false;

        final boolean isInbox = folder.folderUri.equals(account.settings.defaultInbox);
        final FolderPreferences folderPreferences = new FolderPreferences(context, account.getAccountId(),
                folder, isInbox);

        if (isInbox) {
            final AccountPreferences accountPreferences = new AccountPreferences(context,
                    account.getAccountId());
            moveNotificationSetting(accountPreferences, folderPreferences);
        }

        if (!folderPreferences.areNotificationsEnabled()) {
            LogUtils.i(LOG_TAG, "Notifications are disabled for this folder; not notifying");
            // Don't notify
            return;
        }

        if (unreadCount > 0) {
            // How can I order this properly?
            if (cursor.moveToNext()) {
                final Intent notificationIntent;

                // Launch directly to the conversation, if there is only 1 unseen conversation
                final boolean launchConversationMode = (unseenCount == 1);
                if (launchConversationMode) {
                    notificationIntent = createViewConversationIntent(context, account, folder, cursor);
                } else {
                    notificationIntent = createViewConversationIntent(context, account, folder, null);
                }

                Analytics.getInstance().sendEvent("notification_create",
                        launchConversationMode ? "conversation" : "conversation_list",
                        folder.getTypeDescription(), unseenCount);

                if (notificationIntent == null) {
                    LogUtils.e(LOG_TAG, "Null intent when building notification");
                    return;
                }

                clickIntent = createClickPendingIntent(context, notificationIntent);

                configureLatestEventInfoFromConversation(context, account, folderPreferences, notification,
                        wearableExtender, msgNotifications, notificationId, cursor, clickIntent,
                        notificationIntent, unreadCount, unseenCount, folder, when, photoFetcher);
                eventInfoConfigured = true;
            }
        }

        final boolean vibrate = folderPreferences.isNotificationVibrateEnabled();
        final String ringtoneUri = folderPreferences.getNotificationRingtoneUri();
        //TS: junwei-xu 2015-2-12 EMAIL BUGFIX_884937 MOD_S
        //final boolean notifyOnce = !folderPreferences.isEveryMessageNotificationEnabled();

        //if (!ignoreUnobtrusiveSetting && notifyOnce) {
        //    // If the user has "unobtrusive notifications" enabled, only alert the first time
        //    // new mail is received in this account.  This is the default behavior.  See
        //    // bugs 2412348 and 2413490.
        //    LogUtils.d(LOG_TAG, "Setting Alert Once");
        //    notification.setOnlyAlertOnce(true);
        //}
        //TS: junwei-xu 2015-2-12 EMAIL BUGFIX_884937 MOD_E

        LogUtils.i(LOG_TAG, "Account: %s vibrate: %s",
                LogUtils.sanitizeName(LOG_TAG, account.getEmailAddress()),
                Boolean.toString(folderPreferences.isNotificationVibrateEnabled()));

        int defaults = 0;

        // Check if any current conversation notifications exist previously.  Only notify if
        // one of them is new.
        boolean hasNewConversationNotification;
        Set<Integer> prevConversationNotifications = sConversationNotificationMap.get(notificationKey);
        if (prevConversationNotifications != null) {
            hasNewConversationNotification = false;
            for (Integer currentNotificationId : msgNotifications.keySet()) {
                if (!prevConversationNotifications.contains(currentNotificationId)) {
                    hasNewConversationNotification = true;
                    break;
                }
            }
        } else {
            hasNewConversationNotification = true;
        }

        //TS:zheng.zou 2015-12-17 EMAIL BUGFIX_861247  ADD_S
        final int lastUnreadCount = sLastNotificationUnreadCount.get(notificationId);
        final int lastUnseenCount = sLastNotificationUnseenCount.get(notificationId);
        final long lastWhen = sLastNotificationTimestamps.get(notificationId);
        boolean suppressSound = when - lastWhen < sMinDisturbTimeGap;
        if (lastUnreadCount == unreadCount && lastUnseenCount == unseenCount && suppressSound) {
            LogUtils.i(LOG_TAG, "same with unseen count and unread count, return");
            return;
        }
        LogUtils.i(LOG_TAG, "suppressSound = " + suppressSound);
        //TS:zheng.zou 2015-12-17 EMAIL BUGFIX_861247  ADD_E
        LogUtils.d(LOG_TAG, "getAttention=%s,oldWhen=%s,hasNewConversationNotification=%s", getAttention,
                oldWhen, hasNewConversationNotification);

        /*
         * We do not want to notify if this is coming back from an Undo notification, hence the
         * oldWhen check.
         */
        if (getAttention && oldWhen == 0 && hasNewConversationNotification && !suppressSound) { //TS:zheng.zou 2015-12-17 EMAIL BUGFIX_861247  MOD
            final AccountPreferences accountPreferences = new AccountPreferences(context,
                    account.getAccountId());
            if (accountPreferences.areNotificationsEnabled()) {
                if (vibrate) {
                    defaults |= Notification.DEFAULT_VIBRATE;
                }

                notification.setSound(TextUtils.isEmpty(ringtoneUri) ? null : Uri.parse(ringtoneUri));
                LogUtils.i(LOG_TAG, "New email in %s vibrateWhen: %s, playing notification: %s",
                        LogUtils.sanitizeName(LOG_TAG, account.getEmailAddress()), vibrate, ringtoneUri);
                sLastNotificationTimestamps.put(notificationId, when); //TS:zheng.zou 2015-12-17 EMAIL BUGFIX_861247  ADD
            }
        }

        // TODO(skennedy) Why do we do any of the above if we're just going to bail here?
        if (eventInfoConfigured) {
            // TS: zheng.zou 2015-09-10 EMAIL BUGFIX-557052 MOD_S
            // TS: Gantao 2015-09-10 EMAIL BUGFIX-625126 MOD_S
            defaults |= Notification.DEFAULT_LIGHTS;
            //                defaults |= Notification.FLAG_SHOW_LIGHTS;
            // TS: Gantao 2015-09-10 EMAIL BUGFIX-625126 MOD_E
            notification.setDefaults(defaults);
            notification.setLights(0xff00ff00, 280, 2080);
            // TS: zheng.zou 2015-09-10 EMAIL BUGFIX-557052 MOD_E

            if (oldWhen != 0) {
                // We do not want to display the ticker again if we are re-displaying this
                // notification (like from an Undo notification)
                notification.setTicker(null);
            }

            notification.extend(wearableExtender);

            // create the *public* form of the *private* notification we have been assembling
            // TS: xiaolin.li 2014-01-23 EMAIL BUGFIX-900921 ADD_S
            /*final Notification publicNotification = createPublicNotification(context, account,
                folder, when, unseenCount, unreadCount, clickIntent);
            notification.setPublicVersion(publicNotification);*/
            try {
                final Notification publicNotification = createPublicNotification(context, account, folder, when,
                        unseenCount, unreadCount, clickIntent);
                notification.setPublicVersion(publicNotification);
            } catch (Exception e) {
                LogUtils.i(LOG_TAG, "createPublicNotification Exception.");
            }
            // TS: xiaolin.li 2014-01-23 EMAIL BUGFIX-900921 ADD_E
            LogUtils.i(LOG_TAG, " --- notify notification notificationId = " + notificationId); //TS: zheng.zolu 2015-11-09 EMAIL LOG-839780 ADD
            nm.notify(notificationId, notification.build());

            //[BUGFIX]-Add-BEGINbySCDTABLET.yafang.wei,09/06/2016,2848903,
            // SetscreenonwhencomesnewEmail
            Boolean def_is_wakeup_when_receive_email = context.getResources()
                    .getBoolean(R.bool.def_is_wakeup_when_receive_email);
            if (def_is_wakeup_when_receive_email) {
                PowerManager powerManager = (PowerManager) (context.getSystemService(Context.POWER_SERVICE));
                PowerManager.WakeLock wakeLock = null;
                wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK
                        | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE,
                        "Email_wake_lock");
                long wakeUpTime = 0;
                try {
                    ContentResolver cr = context.getContentResolver();
                    wakeUpTime = android.provider.Settings.System.getInt(cr,
                            Settings.System.SCREEN_OFF_TIMEOUT);
                } catch (Settings.SettingNotFoundException e) {
                }
                wakeLock.acquire(wakeUpTime);
            }
            //[BUGFIX]-Add-ENDbySCDTABLET.yafang.wei

            //TS:zheng.zou 2015-12-17 EMAIL BUGFIX_861247  ADD_S
            sLastNotificationUnreadCount.put(notificationId, unreadCount);
            sLastNotificationUnseenCount.put(notificationId, unseenCount);
            //TS:zheng.zou 2015-12-17 EMAIL BUGFIX_861247  ADD_E

            if (prevConversationNotifications != null) {
                Set<Integer> currentNotificationIds = msgNotifications.keySet();
                for (Integer prevConversationNotificationId : prevConversationNotifications) {
                    if (!currentNotificationIds.contains(prevConversationNotificationId)) {
                        nm.cancel(prevConversationNotificationId);
                        LogUtils.d(LOG_TAG, "canceling conversation notification %s",
                                prevConversationNotificationId);
                    }
                }
            }

            // TS: junwei-xu 2015-03-24 EMAIL BUGFIX-957471, ADD_S
            try {
                for (Map.Entry<Integer, NotificationBuilders> entry : msgNotifications.entrySet()) {
                    NotificationBuilders builders = entry.getValue();
                    builders.notifBuilder.extend(builders.wearableNotifBuilder);
                    nm.notify(entry.getKey(), builders.notifBuilder.build());
                    LogUtils.i(LOG_TAG, "notifying conversation notification %s", entry.getKey());// TS: zheng.zolu 2015-11-09 EMAIL LOG-839780 MOD
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            // TS: junwei-xu 2015-03-24 EMAIL BUGFIX-957471, ADD_E

            Set<Integer> conversationNotificationIds = new HashSet<Integer>();
            conversationNotificationIds.addAll(msgNotifications.keySet());
            sConversationNotificationMap.put(notificationKey, conversationNotificationIds);
        } else {
            LogUtils.i(LOG_TAG, "event info not configured - not notifying");
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

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

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

    new Thread(new Runnable() {
        public void run() {
            Looper.prepare();/*from  w  ww.j  av a2s. c  o  m*/

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

            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, mediaPlayer.getAudioSessionId());
                i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
                sendBroadcast(i);
            } catch (Throwable e) {
                // Froyo or lower
            }

            mediaPlayerLooper = Looper.myLooper();
            mediaPlayerHandler = new Handler(mediaPlayerLooper);
            Looper.loop();
        }
    }).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);

    SharedPreferences prefs = Util.getPreferences(this);
    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);

    instance = this;
    lifecycleSupport.onCreate();

    if (prefs.getBoolean(Constants.PREFERENCES_EQUALIZER_ON, false)) {
        getEqualizerController();
    }
}

From source file:com.ifeng.util.download.DownloadThread.java

/**
 * Executes the download in a separate thread
 *//*from www. j  ava2 s  . c  o m*/
@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    State state = new State(mInfo);
    ProxyHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    int finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;

    try {
        PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
        wakeLock.acquire();

        if (Constants.LOGV) {
            Log.v(Constants.TAG, "initiating download for " + mInfo.mUri);
        }

        client = new ProxyHttpClient(mContext, userAgent());
        boolean finished = false;
        while (!finished) {
            Log.i(Constants.TAG, "Initiating request for download " + mInfo.mId);
            HttpGet request = new HttpGet(state.mRequestUri.trim());
            try {
                executeDownload(state, client, request);
                finished = true;
            } catch (RetryDownload exc) {
                // fall through
                exc.printStackTrace();
            } finally {
                request.abort();
                request = null;
            }
        }

        if (Constants.LOGV) {
            Log.v(Constants.TAG, "download completed for " + mInfo.mUri);
        }
        finalizeDestinationFile(state);
        finalStatus = Downloads.Impl.STATUS_SUCCESS;
    } catch (StopRequest error) {
        // remove the cause before printing, in case it contains PII
        Log.w(Constants.TAG, "Aborting request for download " + mInfo.mId + ": " + error.getMessage());
        Log.w(Constants.TAG, "download error:", error);
        finalStatus = error.mFinalStatus;
        displayMsg(finalStatus, error.getMessage());
        // 
        mInfo.mFailedReason = mInfo.mFailedReason + " |||| " + Utils.getStackTraceString(error);
        // fall through to finally block
    } catch (Throwable ex) { // sometimes the socket code throws unchecked
        // exceptions
        Log.w(Constants.TAG, "Exception for id " + mInfo.mId + ": " + ex);
        Log.w(Constants.TAG, "download error:", ex);
        finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;
        displayMsg(finalStatus, ex.getMessage());
        // 
        mInfo.mFailedReason = mInfo.mFailedReason + "||||" + Utils.getStackTraceString(ex);
        // falls through to the code that reports an error
    } finally {
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        if (client != null) {
            client.close();
            client = null;
        }
        cleanupDestination(state, finalStatus);

        notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter, state.mRedirectCount,
                state.mGotData, state.mFilename, state.mNewUri, state.mMimeType);

        --DownloadService.mCurrentThreadNum;
        if (!Downloads.Impl.isStatusCompleted(finalStatus)) {
            mInfo.mHasActiveThread = false;
        }
    }
}

From source file:com.b44t.messenger.NotificationsController.java

public NotificationsController() {
    mContext = ApplicationLoader.applicationContext;
    notificationManager = NotificationManagerCompat.from(ApplicationLoader.applicationContext);
    SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications",
            Context.MODE_PRIVATE);
    inChatSoundEnabled = preferences.getBoolean("EnableInChatSound", true);

    try {/*from w w w .ja v a2s  .  com*/
        audioManager = (AudioManager) ApplicationLoader.applicationContext
                .getSystemService(Context.AUDIO_SERVICE);
    } catch (Exception e) {
        FileLog.e("messenger", e);
    }
    try {
        alarmManager = (AlarmManager) ApplicationLoader.applicationContext
                .getSystemService(Context.ALARM_SERVICE);
    } catch (Exception e) {
        FileLog.e("messenger", e);
    }

    try {
        PowerManager pm = (PowerManager) ApplicationLoader.applicationContext
                .getSystemService(Context.POWER_SERVICE);
        notificationDelayWakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "lock");
        notificationDelayWakelock.setReferenceCounted(false);
    } catch (Exception e) {
        FileLog.e("messenger", e);
    }

    notificationDelayRunnable = new Runnable() {
        @Override
        public void run() {
            FileLog.e("messenger", "delay reached");
            if (!delayedPushMessages.isEmpty()) {
                showOrUpdateNotification(true);
                delayedPushMessages.clear();
            }
            try {
                if (notificationDelayWakelock.isHeld()) {
                    notificationDelayWakelock.release();
                }
            } catch (Exception e) {
                FileLog.e("messenger", e);
            }
        }
    };
}

From source file:org.eclipse.paho.android.service.MqttConnection.java

private void parseMqttMessageV2(String topic, MqttMessage mqttMessage) throws Exception {
    Log.v("mqtt", "parseMqttMessageV2");
    Context ctx = NanuService.getContext();
    byte origMqttMsgByte[] = mqttMessage.getPayload();
    int mqttIndex = 0;
    boolean processVTagSuccess = false;

    boolean processPTagSuccess = false;
    long mqttPacketValue = 0;

    boolean processTTagSuccess = false;
    long mqttTimestampValue = 0;

    boolean processLTagSuccess = false;
    int mqttMsgLengthValue = 0;

    boolean processMTagSuccess = false;
    String mqttMessageValue = "";
    String mqttMembersValue = "";

    boolean processGTagSuccess = false;
    long mqttGroupIDValue = 0;

    boolean processSTagSuccess = false;
    String mqttSubjectValue = "";

    boolean processCTagSuccess = false;
    int mqttMemberCountValue = 0;

    boolean processNTagSuccess = false;
    int mqttAdminCountValue = 0;

    boolean processATagSuccess = false;
    String mqttAdminsValue = "";

    String[] topicArray = topic.split("\\/");

    String sender = topicArray[2];
    if (topicArray.length == 4) {
        processGTagSuccess = true;//from ww w .  j  ava2s  . c o  m
        try {
            mqttGroupIDValue = Long.parseLong(topicArray[3].toString().trim());
        } catch (NumberFormatException nfe) {
            processGTagSuccess = false;
            nfe.printStackTrace();
        }

        if (mqttGroupIDValue == 0) {
            try {
                mqttGroupIDValue = Long.valueOf(topicArray[3].trim());
            } catch (Exception err) {
                processGTagSuccess = false;
                err.printStackTrace();
            }
        }
    }

    String mqttMsgDateValue = "";
    for (int indexMqttCounter = 0; indexMqttCounter < origMqttMsgByte.length; indexMqttCounter++) {
        /*       Log.v(SettingsManager.TAG, "MqttService origMqttMsgByte[" + indexMqttCounter + "] = " + origMqttMsgByte[indexMqttCounter]); */
    }

    for (int indexMqttCounter = 0; indexMqttCounter < origMqttMsgByte.length; indexMqttCounter++) {
        if (indexMqttCounter == 0) {
            mqttIndex = indexMqttCounter;
            long mqttVTag = getMqttTag(origMqttMsgByte, mqttIndex);
            if (mqttVTag != -1) {
                if (mqttVTag == 86) // "V"
                {
                    processVTagSuccess = true;
                    mqttIndex = mqttIndex + 2;
                } else {
                    processVTagSuccess = false;
                    break;
                }
            }
        } else {
            if (mqttIndex == indexMqttCounter) {
                long mqttTag = getMqttTag(origMqttMsgByte, mqttIndex);
                if (mqttTag != -1) {
                    if (mqttTag == 80) /* "P" */ {
                        mqttIndex = mqttIndex + 1;
                        long mPValue = origMqttMsgByte[mqttIndex];
                        mqttPacketValue = mPValue;
                        mqttIndex = mqttIndex + 1;
                        processPTagSuccess = true;
                    } else if (mqttTag == 84) /* "T" */ {
                        mqttIndex = mqttIndex + 1;
                        byte timeStampArray[] = new byte[8];
                        for (int i = 0; i < 8; i++) {
                            timeStampArray[i] = origMqttMsgByte[mqttIndex + i];
                        }
                        mqttTimestampValue = ByteBuffer.wrap(timeStampArray).order(ByteOrder.LITTLE_ENDIAN)
                                .getLong();

                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                        String messageYear = sdf.format(mqttTimestampValue);
                        if (messageYear.length() != 4) {
                            mqttTimestampValue = ByteBuffer.wrap(timeStampArray).order(ByteOrder.BIG_ENDIAN)
                                    .getLong();
                        }
                        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String messageDate = sdfDate.format(mqttTimestampValue);
                        processTTagSuccess = true;
                        mqttIndex = mqttIndex + 8;
                    } else if (mqttTag == 76) /* "L" */ {
                        if (processPTagSuccess) {
                            if (mqttPacketValue == -128 || (mqttPacketValue == -117)
                                    || (mqttPacketValue == -115) || (mqttPacketValue == -126)) {
                                mqttIndex = mqttIndex + 1;
                                mqttMsgLengthValue = origMqttMsgByte[mqttIndex];
                                processLTagSuccess = true;
                                mqttIndex = mqttIndex + 1;
                            } else if (mqttPacketValue == 0) {
                                mqttIndex = mqttIndex + 1;
                                byte msgLengthArray[] = new byte[4];
                                for (int i = 0; i < 4; i++) {
                                    msgLengthArray[i] = origMqttMsgByte[mqttIndex + i];
                                }
                                mqttMsgLengthValue = ByteBuffer.wrap(msgLengthArray)
                                        .order(ByteOrder.LITTLE_ENDIAN).getInt();
                                processLTagSuccess = true;
                                mqttIndex = mqttIndex + 4;
                            }
                        }
                    } else if (mqttTag == 77) /* "M" */ {
                        if (processPTagSuccess) {
                            if ((mqttPacketValue == -128) || (mqttPacketValue == -124)
                                    || (mqttPacketValue == -126) || (mqttPacketValue == -117)) {

                                if (processCTagSuccess) {
                                    mqttIndex = mqttIndex + 1;
                                    for (int i = 0; i < mqttMemberCountValue; i++) {
                                        byte groupMembersArray[] = new byte[8];
                                        for (int j = 0; j < 8; j++) {
                                            groupMembersArray[j] = origMqttMsgByte[mqttIndex + j];
                                        }
                                        long participants = ByteBuffer.wrap(groupMembersArray)
                                                .order(ByteOrder.LITTLE_ENDIAN).getLong();
                                        mqttIndex = mqttIndex + 8;
                                        if (i == (mqttMemberCountValue - 1)) {
                                            mqttMembersValue = mqttMembersValue + participants;
                                        } else {
                                            mqttMembersValue = mqttMembersValue + participants + ",";
                                        }
                                    }
                                    processMTagSuccess = true;
                                } else {
                                    break;
                                }
                            } else if (mqttPacketValue == 0) {
                                if (processLTagSuccess) {
                                    mqttIndex = mqttIndex + 1;
                                    if (mqttMsgLengthValue > 0) {
                                        byte messageArray[] = null;
                                        try {
                                            messageArray = new byte[mqttMsgLengthValue];
                                        } catch (Exception err) {
                                            err.printStackTrace();
                                            processMTagSuccess = false;
                                            break;
                                        }

                                        for (int i = 0; i < mqttMsgLengthValue; i++) {
                                            messageArray[i] = origMqttMsgByte[mqttIndex + i];
                                        }
                                        mqttMessageValue = new String(messageArray);
                                        processMTagSuccess = true;
                                        mqttIndex = mqttIndex + mqttMsgLengthValue + 1;
                                    }
                                } else {
                                    break;
                                }
                            }
                        }
                    } else if (mqttTag == 71) /* "G" */ {
                        mqttIndex = mqttIndex + 1;
                        byte groupIDArray[] = new byte[8];
                        for (int i = 0; i < 8; i++) {
                            groupIDArray[i] = origMqttMsgByte[mqttIndex + i];
                        }
                        mqttGroupIDValue = ByteBuffer.wrap(groupIDArray).order(ByteOrder.LITTLE_ENDIAN)
                                .getLong();
                        processGTagSuccess = true;
                        mqttIndex = mqttIndex + 8;
                    } else if (mqttTag == 83) /* "S" */ {
                        if (processLTagSuccess) {
                            mqttIndex = mqttIndex + 1;
                            if (mqttMsgLengthValue > 0) {
                                byte subjectArray[] = null;
                                try {
                                    subjectArray = new byte[mqttMsgLengthValue];
                                } catch (Exception err) {
                                    err.printStackTrace();
                                    processSTagSuccess = false;
                                    break;
                                }
                                for (int i = 0; i < mqttMsgLengthValue; i++) {
                                    subjectArray[i] = origMqttMsgByte[mqttIndex + i];
                                }
                                mqttSubjectValue = new String(subjectArray);
                                processSTagSuccess = true;
                                mqttIndex = mqttIndex + mqttMsgLengthValue;
                            }
                        } else {
                            break;
                        }
                    } else if (mqttTag == 67) /* "C" */ {
                        mqttIndex = mqttIndex + 1;
                        mqttMemberCountValue = origMqttMsgByte[mqttIndex];
                        processCTagSuccess = true;
                        mqttIndex = mqttIndex + 1;
                    } else if (mqttTag == 78) /* "N" */ {
                        mqttIndex = mqttIndex + 1;
                        mqttAdminCountValue = origMqttMsgByte[mqttIndex];
                        processNTagSuccess = true;
                        mqttIndex = mqttIndex + 1;
                    } else if (mqttTag == 65) /* "A" */ {
                        if (processPTagSuccess) {
                            if (mqttPacketValue == -117) {
                                if (processNTagSuccess) {
                                    mqttIndex = mqttIndex + 1;
                                    for (int i = 0; i < mqttAdminCountValue; i++) {
                                        byte groupAdminsArray[] = new byte[8];
                                        for (int j = 0; j < 8; j++) {
                                            groupAdminsArray[j] = origMqttMsgByte[mqttIndex + j];
                                        }
                                        long admins = ByteBuffer.wrap(groupAdminsArray)
                                                .order(ByteOrder.LITTLE_ENDIAN).getLong();
                                        mqttIndex = mqttIndex + 8;
                                        if (i == (mqttAdminCountValue - 1)) {
                                            mqttAdminsValue = mqttAdminsValue + admins;
                                        } else {
                                            mqttAdminsValue = mqttAdminsValue + admins + ",";
                                        }
                                    }
                                    processATagSuccess = true;
                                } else {
                                    break;
                                }
                            }
                        }
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }
        }
    }

    if (!processVTagSuccess) {
        return;
    }

    PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
    boolean isScreenOn = pm.isScreenOn();
    if (isScreenOn == false) {
        WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP
                | PowerManager.ON_AFTER_RELEASE, "MyLock");
        if (wl.isHeld()) {
            wl.release();
        }
        wl.acquire(10000);
        WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyCpuLock");
        if (wl_cpu.isHeld()) {
            wl_cpu.release();
        }
        wl_cpu.acquire(10000);
    }

    String message = mqttMessageValue;
    Log.v("mqtt", "from: " + sender);
    Log.v("mqtt", "message: " + message);
    Intent intent = new Intent();
    intent.setClassName(ctx, "org.eclipse.paho.android.service.sample.MainActivity");
    intent.putExtra("handle", clientHandle);
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = (NotificationManager) ctx.getSystemService(ns);
    int messageNotificationId = 1;
    mNotificationManager.cancel(messageNotificationId);
    Calendar.getInstance().getTime().toString();
    long when = System.currentTimeMillis();
    String ticker = sender + " " + mqttMessageValue;
    PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 3, intent, 0);
    NotificationCompat.Builder notificationCompat = new NotificationCompat.Builder(ctx);
    notificationCompat.setAutoCancel(true).setContentTitle(sender).setContentIntent(pendingIntent)
            .setContentText(mqttMessageValue).setTicker(ticker).setWhen(when)
            .setSmallIcon(R.drawable.ic_launcher);

    //  Notification notification = notificationCompat.build();
    Bitmap iconLarge = BitmapFactory.decodeResource(ctx.getResources(), R.drawable.ic_launcher);
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ctx)
            .setSmallIcon(R.drawable.ic_launcher).setLargeIcon(iconLarge).setContentTitle(sender)
            .setContentText(mqttMessageValue);

    mBuilder.setContentIntent(pendingIntent);
    mBuilder.setTicker(message);
    mBuilder.setAutoCancel(true);
    mBuilder.setDefaults(
            Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS);
    mNotificationManager.notify(messageNotificationId, mBuilder.build());
}

From source file:org.videolan.vlc.PlaybackService.java

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

    if (!VLCInstance.testCompatibleCPU(this)) {
        stopSelf();/* www  .jav a2 s.  c o m*/
        return;
    }

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    mDetectHeadset = prefs.getBoolean("enable_headset_detection", true);

    mMediaListPlayer = MediaWrapperListPlayer.getInstance();

    mCallback = new HashMap<IPlaybackServiceCallback, Integer>();
    mCurrentIndex = -1;
    mPrevIndex = -1;
    mNextIndex = -1;
    mPrevious = new Stack<Integer>();
    mEventHandler = EventHandler.getInstance();
    mRemoteControlClientReceiverComponent = new ComponentName(BuildConfig.APPLICATION_ID,
            RemoteControlClientReceiver.class.getName());

    // Make sure the audio player will acquire a wake-lock while playing. If we don't do
    // that, the CPU might go to sleep while the song is playing, causing playback to stop.
    PowerManager pm = (PowerManager) VLCApplication.getAppContext().getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

    IntentFilter filter = new IntentFilter();
    filter.setPriority(Integer.MAX_VALUE);
    filter.addAction(ACTION_REMOTE_BACKWARD);
    filter.addAction(ACTION_REMOTE_PLAYPAUSE);
    filter.addAction(ACTION_REMOTE_PLAY);
    filter.addAction(ACTION_REMOTE_PAUSE);
    filter.addAction(ACTION_REMOTE_STOP);
    filter.addAction(ACTION_REMOTE_FORWARD);
    filter.addAction(ACTION_REMOTE_LAST_PLAYLIST);
    filter.addAction(ACTION_WIDGET_INIT);
    filter.addAction(Intent.ACTION_HEADSET_PLUG);
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    filter.addAction(VLCApplication.SLEEP_INTENT);
    filter.addAction(VLCApplication.INCOMING_CALL_INTENT);
    filter.addAction(VLCApplication.CALL_ENDED_INTENT);
    registerReceiver(serviceReceiver, filter);

    final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    boolean stealRemoteControl = pref.getBoolean("enable_steal_remote_control", false);

    if (!AndroidUtil.isFroyoOrLater() || stealRemoteControl) {
        /* Backward compatibility for API 7 */
        filter = new IntentFilter();
        if (stealRemoteControl)
            filter.setPriority(Integer.MAX_VALUE);
        filter.addAction(Intent.ACTION_MEDIA_BUTTON);
        mRemoteControlClientReceiver = new RemoteControlClientReceiver();
        registerReceiver(mRemoteControlClientReceiver, filter);
    }
    try {
        getPackageManager().getPackageInfo("com.getpebble.android", PackageManager.GET_ACTIVITIES);
        mPebbleEnabled = true;
    } catch (PackageManager.NameNotFoundException e) {
        mPebbleEnabled = false;
    }
}

From source file:com.dragon4.owo.ar_trace.ARCore.MixView.java

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    DataSource.createIcons(getResources());

    try {/*  w  ww  . j  av  a2  s .  c  om*/
        // ??
        final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        // ?    ?? ?
        this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "My Tag");
        // ?? 
        locationMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //  ?? . 2 ?? (1/1000s), 3 ?? (m)? ? 
        locationMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 3, this);

        //orientation sensor 
        sensorMgr_ori = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        orientationSensor = sensorMgr_ori.getDefaultSensor(Sensor.TYPE_ORIENTATION);

        killOnError(); // ?  ?
        requestWindowFeature(Window.FEATURE_NO_TITLE); // ?   ? 

        //  ?? 
        FrameLayout frameLayout = new FrameLayout(this);

        //  ?    ?, ? 
        frameLayout.setMinimumWidth(3000);
        frameLayout.setPadding(10, 0, 10, 10);

        // ? ? ? ?? ?
        camScreen = new CameraSurface(this);
        augScreen = new AugmentedView(this);
        setContentView(camScreen); // ? ?? ?  ? 

        // ? ?? ? 
        addContentView(augScreen, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        // ? ? ? ?   ?.
        // ? ?  ?  ?? ?  ?  ?
        addContentView(frameLayout, new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT, Gravity.BOTTOM));

        topLayoutOnMixView = new TopLayoutOnMixView(this);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
        addContentView(topLayoutOnMixView.mainArView, params);

        // ? ? ? topLayoutOnMixView ?  ?
        handleIntent(getIntent()); // ?? 

        //  ? ? ?
        if (!isInited) {
            mixContext = new MixContext(this); // ? ?
            // ? ?
            mixContext.downloadManager = new DownloadManager(mixContext);

            //? ?  ? 
            navigator = new Navigator(mixContext, topLayoutOnMixView.naverFragment);

            // ? ? ?? ? ?
            dWindow = new PaintScreen();
            dataView = new DataView(mixContext);

            isInited = true; //   true

        }

        if (mixContext.isActualLocation() == false) {
            Toast.makeText(this, getString(DataView.CONNECTION_GPS_DIALOG_TEXT), Toast.LENGTH_LONG).show();
        }

    } catch (Exception ex) {
        doError(ex); //  ? ? 
    }

    //   ? 
    IntentFilter naviBraodFilter = new IntentFilter();
    naviBraodFilter.addAction("NAVI");
    registerReceiver(naviRecevicer, naviBraodFilter);
}

From source file:com.dzt.musicplay.player.AudioService.java

@Override
public void onCreate() {
    super.onCreate();
    GlobalConstants.print_i(getClass(), "onCreate");
    // Get libVLC instance
    try {/*from  ww  w  .j  a  va  2  s .c  om*/
        mLibVLC = VLCInstance.getLibVlcInstance(getApplicationContext());
    } catch (LibVlcException e) {
        e.printStackTrace();
    }
    StartLoadFileThread();

    mCallback = new HashMap<IAudioServiceCallback, Integer>();
    mMediaList = new ArrayList<Media>();
    mCurrentIndex = -1;
    mPrevIndex = -1;
    mNextIndex = -1;
    mPrevious = new Stack<Integer>();
    mEventHandler = EventHandler.getInstance();
    mRemoteControlClientReceiverComponent = new ComponentName(getPackageName(),
            RemoteControlClientReceiver.class.getName());

    // Make sure the audio player will acquire a wake-lock while playing. If
    // we don't do
    // that, the CPU might go to sleep while the song is playing, causing
    // playback to stop.
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

    IntentFilter filter = new IntentFilter();
    filter.setPriority(Integer.MAX_VALUE);
    filter.addAction(ACTION_REMOTE_BACKWARD);
    filter.addAction(ACTION_REMOTE_PLAYPAUSE);
    filter.addAction(ACTION_REMOTE_PLAY);
    filter.addAction(ACTION_REMOTE_PAUSE);
    filter.addAction(ACTION_REMOTE_STOP);
    filter.addAction(ACTION_REMOTE_FORWARD);
    filter.addAction(ACTION_REMOTE_LAST_PLAYLIST);
    filter.addAction(ACTION_WIDGET_INIT);
    filter.addAction(Intent.ACTION_HEADSET_PLUG);
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    filter.addAction(SLEEP_INTENT);
    registerReceiver(serviceReceiver, filter);

    final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    boolean stealRemoteControl = pref.getBoolean("enable_steal_remote_control", false);

    if (!LibVlcUtil.isFroyoOrLater() || stealRemoteControl) {
        /* Backward compatibility for API 7 */
        filter = new IntentFilter();
        if (stealRemoteControl)
            filter.setPriority(Integer.MAX_VALUE);
        filter.addAction(Intent.ACTION_MEDIA_BUTTON);
        mRemoteControlClientReceiver = new RemoteControlClientReceiver();
        registerReceiver(mRemoteControlClientReceiver, filter);
    }
    GlobalConstants.print_i(getClass(), "onCreate----end");
}

From source file:com.saulcintero.moveon.services.MoveOnService.java

@SuppressWarnings("deprecation")
private void acquireWakeLock() {
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    int wakeFlags;

    if (prefs.getString("operation_level", "run_in_background").equals("wake_up"))
        wakeFlags = PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP;
    else if (prefs.getString("operation_level", "run_in_background").equals("keep_screen_on"))
        wakeFlags = PowerManager.SCREEN_DIM_WAKE_LOCK;
    else//from  w ww .j a v  a 2  s. co m
        wakeFlags = PowerManager.PARTIAL_WAKE_LOCK;

    wakeLock = pm.newWakeLock(wakeFlags, TAG);
    wakeLock.acquire();
}

From source file:com.xorcode.andtweet.AndTweetService.java

private PowerManager.WakeLock getWakeLock() {
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    wakeLock.acquire();/*from   w ww .  j  av a  2 s.  c o  m*/
    return wakeLock;
}