Example usage for android.util Log ERROR

List of usage examples for android.util Log ERROR

Introduction

In this page you can find the example usage for android.util Log ERROR.

Prototype

int ERROR

To view the source code for android.util Log ERROR.

Click Source Link

Document

Priority constant for the println method; use Log.e.

Usage

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

/**
 * Registers listeners, sets service info, loads preferences. This should be
 * called from {@link #onServiceConnected} and when TalkBack resumes from a
 * suspended state.//from  w w w . ja  va 2s. c  o  m
 */
private void resumeInfrastructure() {
    if (isServiceActive()) {
        LogUtils.log(this, Log.ERROR, "Attempted to resume while not suspended");
        return;
    }

    setServiceState(ServiceState.ACTIVE);
    stopForeground(true);

    final AccessibilityServiceInfo info = new AccessibilityServiceInfo();
    info.eventTypes = AccessibilityEvent.TYPES_ALL_MASK;
    info.feedbackType |= AccessibilityServiceInfo.FEEDBACK_SPOKEN;
    info.feedbackType |= AccessibilityServiceInfo.FEEDBACK_AUDIBLE;
    info.feedbackType |= AccessibilityServiceInfo.FEEDBACK_HAPTIC;
    info.flags |= AccessibilityServiceInfo.DEFAULT;
    info.flags |= AccessibilityServiceInfoCompatUtils.FLAG_REQUEST_ENHANCED_WEB_ACCESSIBILITY;
    info.flags |= AccessibilityServiceInfoCompatUtils.FLAG_REPORT_VIEW_IDS;
    info.flags |= AccessibilityServiceInfoCompatUtils.FLAG_REQUEST_FILTER_KEY_EVENTS;
    info.notificationTimeout = 0;

    // Ensure the initial touch exploration request mode is correct.
    if (SUPPORTS_TOUCH_PREF && SharedPreferencesUtils.getBooleanPref(mPrefs, getResources(),
            R.string.pref_explore_by_touch_key, R.bool.pref_explore_by_touch_default)) {
        info.flags |= AccessibilityServiceInfoCompatUtils.FLAG_REQUEST_TOUCH_EXPLORATION_MODE;
    }

    setServiceInfo(info);

    if (mCallStateMonitor != null) {
        registerReceiver(mCallStateMonitor, mCallStateMonitor.getFilter());
    }

    if (mRingerModeAndScreenMonitor != null) {
        registerReceiver(mRingerModeAndScreenMonitor, mRingerModeAndScreenMonitor.getFilter());
    }

    if (mTextToSpeechManager != null) {
        mTextToSpeechManager.startDiscovery();
    }

    if (mRadialMenuManager != null) {
        registerReceiver(mRadialMenuManager, mRadialMenuManager.getFilter());
    }

    if (mVolumeMonitor != null) {
        registerReceiver(mVolumeMonitor, mVolumeMonitor.getFilter());
    }

    mPrefs.registerOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener);

    // Add the broadcast listener for gestures.
    final IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_PERFORM_GESTURE);
    registerReceiver(mActiveReceiver, filter, PERMISSION_TALKBACK, null);

    // Enable the proxy activity for long-press search.
    final PackageManager packageManager = getPackageManager();
    final ComponentName shortcutProxy = new ComponentName(this, ShortcutProxyActivity.class);
    packageManager.setComponentEnabledSetting(shortcutProxy, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);

    reloadPreferences();
}

From source file:com.android.talkback.SpeechController.java

/**
 * @return The utterance ID, or -1 if the ID is invalid.
 *//*from  ww  w.  ja  va 2s .  c  o m*/
private static int parseUtteranceId(String utteranceId) {
    // Check for bad utterance ID. This should never happen.
    if (!utteranceId.startsWith(UTTERANCE_ID_PREFIX)) {
        LogUtils.log(SpeechController.class, Log.ERROR, "Bad utterance ID: %s", utteranceId);
        return -1;
    }

    try {
        return Integer.parseInt(utteranceId.substring(UTTERANCE_ID_PREFIX.length()));
    } catch (NumberFormatException e) {
        e.printStackTrace();
        return -1;
    }
}

From source file:com.google.android.marvin.talkback.TalkBackService.java

/**
 * Registers listeners, sets service info, loads preferences. This should be
 * called from {@link #onServiceConnected} and when TalkBack resumes from a
 * suspended state.// w w  w.  j  av  a2s  .  c o  m
 */
private void resumeInfrastructure() {
    if (isServiceActive()) {
        LogUtils.log(this, Log.ERROR, "Attempted to resume while not suspended");
        return;
    }

    setServiceState(ServiceState.ACTIVE);
    stopForeground(true);

    final AccessibilityServiceInfo info = new AccessibilityServiceInfo();
    info.eventTypes = AccessibilityEvent.TYPES_ALL_MASK;
    info.feedbackType |= AccessibilityServiceInfo.FEEDBACK_SPOKEN;
    info.feedbackType |= AccessibilityServiceInfo.FEEDBACK_AUDIBLE;
    info.feedbackType |= AccessibilityServiceInfo.FEEDBACK_HAPTIC;
    info.flags |= AccessibilityServiceInfo.DEFAULT;
    info.flags |= AccessibilityServiceInfoCompatUtils.FLAG_REQUEST_ENHANCED_WEB_ACCESSIBILITY;
    info.flags |= AccessibilityServiceInfoCompatUtils.FLAG_REPORT_VIEW_IDS;
    info.flags |= AccessibilityServiceInfoCompatUtils.FLAG_REQUEST_FILTER_KEY_EVENTS;
    info.notificationTimeout = 0;

    // Ensure the initial touch exploration request mode is correct.
    if (SUPPORTS_TOUCH_PREF && SharedPreferencesUtils.getBooleanPref(mPrefs, getResources(),
            R.string.pref_explore_by_touch_key, R.bool.pref_explore_by_touch_default)) {
        info.flags |= AccessibilityServiceInfoCompatUtils.FLAG_REQUEST_TOUCH_EXPLORATION_MODE;
    }

    setServiceInfo(info);

    if (mCallStateMonitor != null) {
        registerReceiver(mCallStateMonitor, mCallStateMonitor.getFilter());
    }

    if (mRingerModeAndScreenMonitor != null) {
        registerReceiver(mRingerModeAndScreenMonitor, mRingerModeAndScreenMonitor.getFilter());
    }

    if (mTextToSpeechManager != null) {
        mTextToSpeechManager.startDiscovery();
    }

    if (mRadialMenuManager != null) {
        registerReceiver(mRadialMenuManager, mRadialMenuManager.getFilter());
    }

    if (mVolumeMonitor != null) {
        registerReceiver(mVolumeMonitor, mVolumeMonitor.getFilter());
    }

    if (mPackageReceiver != null) {
        registerReceiver(mPackageReceiver, mPackageReceiver.getFilter());
        if (mLabelManager != null) {
            mLabelManager.ensureDataConsistency();
        }
    }

    mPrefs.registerOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener);

    // Add the broadcast listener for gestures.
    final IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_PERFORM_GESTURE_ACTION);
    registerReceiver(mActiveReceiver, filter, PERMISSION_TALKBACK, null);

    // Enable the proxy activity for long-press search.
    final PackageManager packageManager = getPackageManager();
    final ComponentName shortcutProxy = new ComponentName(this, ShortcutProxyActivity.class);
    packageManager.setComponentEnabledSetting(shortcutProxy, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);

    reloadPreferences();
}

From source file:com.android.talkback.SpeechController.java

/**
 * Called when transitioning from an idle state to a speaking state, e.g.
 * the queue was empty, there was no current speech, and a speech item was
 * added to the queue.// w ww . j  av a2  s.  co m
 *
 * @see #handleSpeechCompleted()
 */
private void handleSpeechStarting() {
    // Always enable the proximity sensor when speaking.
    setProximitySensorState(true);

    boolean useAudioFocus = mUseAudioFocus;
    if (BuildCompat.isAtLeastN()) {
        List<AudioRecordingConfiguration> recordConfigurations = mAudioManager
                .getActiveRecordingConfigurations();
        if (recordConfigurations.size() != 0)
            useAudioFocus = false;
    }

    if (useAudioFocus) {
        mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
    }

    if (mIsSpeaking) {
        LogUtils.log(this, Log.ERROR, "Started speech while already speaking!");
    }

    mIsSpeaking = true;
}

From source file:com.google.android.marvin.screenspeak.ScreenSpeakService.java

/**
 * Registers listeners, sets service info, loads preferences. This should be
 * called from {@link #onServiceConnected} and when ScreenSpeak resumes from a
 * suspended state./*  w  ww .j a va2 s .  c om*/
 */
private void resumeInfrastructure() {
    if (isServiceActive()) {
        if (LogUtils.LOG_LEVEL <= Log.ERROR) {
            Log.e(LOGTAG, "Attempted to resume while not suspended");
        }
        return;
    }

    setServiceState(SERVICE_STATE_ACTIVE);
    stopForeground(true);

    final AccessibilityServiceInfo info = new AccessibilityServiceInfo();
    info.eventTypes = AccessibilityEvent.TYPES_ALL_MASK;
    info.feedbackType |= AccessibilityServiceInfo.FEEDBACK_SPOKEN;
    info.feedbackType |= AccessibilityServiceInfo.FEEDBACK_AUDIBLE;
    info.feedbackType |= AccessibilityServiceInfo.FEEDBACK_HAPTIC;
    info.flags |= AccessibilityServiceInfo.DEFAULT;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        info.flags |= AccessibilityServiceInfo.FLAG_REQUEST_ENHANCED_WEB_ACCESSIBILITY;
        info.flags |= AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS;
        info.flags |= AccessibilityServiceInfo.FLAG_REQUEST_FILTER_KEY_EVENTS;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        info.flags |= AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS;
    }
    info.notificationTimeout = 0;

    // Ensure the initial touch exploration request mode is correct.
    if (mSupportsTouchScreen && SharedPreferencesUtils.getBooleanPref(mPrefs, getResources(),
            R.string.pref_explore_by_touch_key, R.bool.pref_explore_by_touch_default)) {
        info.flags |= AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE;
    }

    setServiceInfo(info);

    if (mRingerModeAndScreenMonitor != null) {
        registerReceiver(mRingerModeAndScreenMonitor, mRingerModeAndScreenMonitor.getFilter());
        // It could now be confused with the current screen state
        mRingerModeAndScreenMonitor.updateScreenState();
    }

    if (mVolumeMonitor != null) {
        registerReceiver(mVolumeMonitor, mVolumeMonitor.getFilter());
    }

    if (mBatteryMonitor != null) {
        registerReceiver(mBatteryMonitor, mBatteryMonitor.getFilter());
    }

    if (mPackageReceiver != null) {
        registerReceiver(mPackageReceiver, mPackageReceiver.getFilter());
        if (mLabelManager != null) {
            mLabelManager.ensureDataConsistency();
        }
    }

    if (mSideTapManager != null) {
        registerReceiver(mSideTapManager, SideTapManager.getFilter());
    }

    mPrefs.registerOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener);

    // Add the broadcast listener for gestures.
    final IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_PERFORM_GESTURE_ACTION);
    registerReceiver(mActiveReceiver, filter, PERMISSION_SCREENSPEAK, null);

    // Enable the proxy activity for long-press search.
    final PackageManager packageManager = getPackageManager();
    final ComponentName shortcutProxy = new ComponentName(this, ShortcutProxyActivity.class);
    packageManager.setComponentEnabledSetting(shortcutProxy, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);

    reloadPreferences();

    if (mDimScreenController.isDimmingEnabled()) {
        mDimScreenController.makeScreenDim();
    }
}

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

/**
 * Registers listeners, sets service info, loads preferences. This should be
 * called from {@link #onServiceConnected} and when TalkBack resumes from a
 * suspended state./*from w  ww.ja  va 2 s. c o m*/
 */
private void suspendInfrastructure() {
    if (!isServiceActive()) {
        LogUtils.log(this, Log.ERROR, "Attempted to suspend while already suspended");
        return;
    }

    interruptAllFeedback();
    setServiceState(ServiceState.SUSPENDED);

    setServiceInfo(new AccessibilityServiceInfo());

    mPrefs.unregisterOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener);

    unregisterReceiver(mActiveReceiver);

    if (mCallStateMonitor != null) {
        unregisterReceiver(mCallStateMonitor);
    }

    if (mRingerModeAndScreenMonitor != null) {
        unregisterReceiver(mRingerModeAndScreenMonitor);
    }

    if (mRadialMenuManager != null) {
        unregisterReceiver(mRadialMenuManager);
        mRadialMenuManager.clearCache();
    }

    if (mVolumeMonitor != null) {
        unregisterReceiver(mVolumeMonitor);
        mVolumeMonitor.releaseControl();
    }

    if (mShakeDetector != null) {
        mShakeDetector.setEnabled(false);
    }

    if (SUPPORTS_TOUCH_PREF) {
        final ContentResolver resolver = getContentResolver();
        resolver.unregisterContentObserver(mTouchExploreObserver);
    }

    // Disable the proxy activity for long-press search.
    final PackageManager packageManager = getPackageManager();
    final ComponentName shortcutProxy = new ComponentName(this, ShortcutProxyActivity.class);
    packageManager.setComponentEnabledSetting(shortcutProxy, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP);

    // Remove any pending notifications that shouldn't persist.
    final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    nm.cancelAll();

    if (mTtsOverlay != null) {
        mTtsOverlay.hide();
    }
}

From source file:com.android.talkback.SpeechController.java

/**
 * Called when transitioning from a speaking state to an idle state, e.g.
 * all queued utterances have been spoken and the last utterance has
 * completed./*  w w w.j  a  va2  s.  c  o  m*/
 *
 * @see #handleSpeechStarting()
 */
private void handleSpeechCompleted() {
    // If the screen is on, keep the proximity sensor on.
    setProximitySensorState(mScreenIsOn);

    if (mUseAudioFocus) {
        mAudioManager.abandonAudioFocus(mAudioFocusListener);
    }

    if (!mIsSpeaking) {
        LogUtils.log(this, Log.ERROR, "Completed speech while already completed!");
    }

    mIsSpeaking = false;
}

From source file:com.irccloud.android.Notifications.java

private void showMessageNotifications(String ticker) {
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());
    String text = "";
    String weartext = "";
    ArrayList<Notification> notifications = getMessageNotifications();

    int notify_type = Integer.parseInt(prefs.getString("notify_type", "1"));
    boolean notify = false;
    if (notify_type == 1 || (notify_type == 2 && NetworkConnection.getInstance().isVisible()))
        notify = true;/*from  ww w.j  a  v a  2 s. com*/

    if (notifications.size() > 0 && notify) {
        int lastbid = notifications.get(0).bid;
        int count = 0;
        long[] eids = new long[notifications.size()];
        String[] auto_messages = new String[notifications.size()];
        Notification last = null;
        count = 0;
        boolean show = false;
        for (Notification n : notifications) {
            if (n.bid != lastbid) {
                if (show) {
                    String title = last.chan;
                    if (title == null || title.length() == 0)
                        title = last.nick;
                    if (title == null || title.length() == 0)
                        title = last.network;

                    Intent replyIntent = new Intent(RemoteInputService.ACTION_REPLY);
                    replyIntent.putExtra("bid", last.bid);
                    replyIntent.putExtra("cid", last.cid);
                    replyIntent.putExtra("eids", eids);
                    replyIntent.putExtra("network", last.network);
                    if (last.buffer_type.equals("channel"))
                        replyIntent.putExtra("to", last.chan);
                    else
                        replyIntent.putExtra("to", last.nick);

                    String body = "";
                    if (last.buffer_type.equals("channel")) {
                        if (last.message_type.equals("buffer_me_msg"))
                            body = "<b> " + last.nick + "</b> " + last.message;
                        else
                            body = "<b>&lt;" + last.nick + "&gt;</b> " + last.message;
                    } else {
                        if (last.message_type.equals("buffer_me_msg"))
                            body = " " + last.nick + " " + last.message;
                        else
                            body = last.message;
                    }

                    NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext())
                            .notify(lastbid,
                                    buildNotification(ticker, lastbid, eids, title, body, Html.fromHtml(text),
                                            count, replyIntent, Html.fromHtml(weartext), last.network,
                                            auto_messages));
                }
                lastbid = n.bid;
                text = "";
                weartext = "";
                count = 0;
                eids = new long[notifications.size()];
                show = false;
                auto_messages = new String[notifications.size()];
            }
            if (count < 3) {
                if (text.length() > 0)
                    text += "<br/>";
                if (n.buffer_type.equals("conversation") && n.message_type.equals("buffer_me_msg"))
                    text += " " + n.message;
                else if (n.buffer_type.equals("conversation"))
                    text += n.message;
                else if (n.message_type.equals("buffer_me_msg"))
                    text += "<b> " + n.nick + "</b> " + n.message;
                else
                    text += "<b>" + n.nick + "</b> " + n.message;
            }
            if (weartext.length() > 0)
                weartext += "<br/><br/>";
            if (n.message_type.equals("buffer_me_msg"))
                weartext += "<b> " + n.nick + "</b> " + n.message;
            else
                weartext += "<b>&lt;" + n.nick + "&gt;</b> " + n.message;

            if (n.buffer_type.equals("conversation")) {
                if (n.message_type.equals("buffer_me_msg"))
                    auto_messages[count] = " " + n.nick + " " + Html.fromHtml(n.message).toString();
                else
                    auto_messages[count] = Html.fromHtml(n.message).toString();
            } else {
                if (n.message_type.equals("buffer_me_msg"))
                    auto_messages[count] = " " + n.nick + " " + Html.fromHtml(n.message).toString();
                else
                    auto_messages[count] = n.nick + " said: " + Html.fromHtml(n.message).toString();
            }

            if (!n.shown) {
                n.shown = true;
                show = true;

                if (prefs.getBoolean("notify_sony", false)) {
                    long time = System.currentTimeMillis();
                    long sourceId = NotificationUtil.getSourceId(
                            IRCCloudApplication.getInstance().getApplicationContext(),
                            SonyExtensionService.EXTENSION_SPECIFIC_ID);
                    if (sourceId == NotificationUtil.INVALID_ID) {
                        Crashlytics.log(Log.ERROR, "IRCCloud",
                                "Sony LiveWare Manager not configured, disabling Sony notifications");
                        SharedPreferences.Editor editor = prefs.edit();
                        editor.putBoolean("notify_sony", false);
                        editor.commit();
                    } else {
                        ContentValues eventValues = new ContentValues();
                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.EVENT_READ_STATUS,
                                false);
                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.DISPLAY_NAME,
                                n.nick);

                        if (n.buffer_type.equals("channel") && n.chan != null && n.chan.length() > 0)
                            eventValues.put(
                                    com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.TITLE,
                                    n.chan);
                        else
                            eventValues.put(
                                    com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.TITLE,
                                    n.network);

                        if (n.message_type.equals("buffer_me_msg"))
                            eventValues.put(
                                    com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.MESSAGE,
                                    " " + Html.fromHtml(n.message).toString());
                        else
                            eventValues.put(
                                    com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.MESSAGE,
                                    Html.fromHtml(n.message).toString());

                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.PERSONAL,
                                1);
                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.PUBLISHED_TIME,
                                time);
                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.SOURCE_ID,
                                sourceId);
                        eventValues.put(
                                com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.FRIEND_KEY,
                                String.valueOf(n.bid));

                        try {
                            IRCCloudApplication.getInstance().getApplicationContext().getContentResolver()
                                    .insert(com.sonyericsson.extras.liveware.aef.notification.Notification.Event.URI,
                                            eventValues);
                        } catch (IllegalArgumentException e) {
                            Log.e("IRCCloud", "Failed to insert event", e);
                        } catch (SecurityException e) {
                            Log.e("IRCCloud", "Failed to insert event, is Live Ware Manager installed?", e);
                        } catch (SQLException e) {
                            Log.e("IRCCloud", "Failed to insert event", e);
                        }
                    }
                }

                if (prefs.getBoolean("notify_pebble", false)) {
                    String pebbleTitle = n.network + ":\n";
                    String pebbleBody = "";
                    if (n.buffer_type.equals("channel") && n.chan != null && n.chan.length() > 0)
                        pebbleTitle = n.chan + ":\n";

                    if (n.message_type.equals("buffer_me_msg"))
                        pebbleBody = " " + n.message;
                    else
                        pebbleBody = n.message;

                    if (n.nick != null && n.nick.length() > 0)
                        notifyPebble(n.nick, pebbleTitle + Html.fromHtml(pebbleBody).toString());
                    else
                        notifyPebble(n.network, pebbleTitle + Html.fromHtml(pebbleBody).toString());
                }
            }
            eids[count++] = n.eid;
            last = n;
        }

        if (show) {
            String title = last.chan;
            if (title == null || title.length() == 0)
                title = last.nick;
            if (title == null || title.length() == 0)
                title = last.network;

            Intent replyIntent = new Intent(RemoteInputService.ACTION_REPLY);
            replyIntent.putExtra("bid", last.bid);
            replyIntent.putExtra("cid", last.cid);
            replyIntent.putExtra("network", last.network);
            replyIntent.putExtra("eids", eids);
            if (last.buffer_type.equals("channel"))
                replyIntent.putExtra("to", last.chan);
            else
                replyIntent.putExtra("to", last.nick);

            String body = "";
            if (last.buffer_type.equals("channel")) {
                if (last.message_type.equals("buffer_me_msg"))
                    body = "<b> " + last.nick + "</b> " + last.message;
                else
                    body = "<b>&lt;" + last.nick + "&gt;</b> " + last.message;
            } else {
                if (last.message_type.equals("buffer_me_msg"))
                    body = " " + last.nick + " " + last.message;
                else
                    body = last.message;
            }
            NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext())
                    .notify(lastbid, buildNotification(ticker, lastbid, eids, title, body, Html.fromHtml(text),
                            count, replyIntent, Html.fromHtml(weartext), last.network, auto_messages));
        }
    }
}

From source file:com.google.android.marvin.talkback.TalkBackService.java

/**
 * Registers listeners, sets service info, loads preferences. This should be
 * called from {@link #onServiceConnected} and when TalkBack resumes from a
 * suspended state.//  www  .ja  v a2s . co m
 */
private void suspendInfrastructure() {
    if (!isServiceActive()) {
        LogUtils.log(this, Log.ERROR, "Attempted to suspend while already suspended");
        return;
    }

    interruptAllFeedback();
    setServiceState(ServiceState.SUSPENDED);

    setServiceInfo(new AccessibilityServiceInfo());

    mPrefs.unregisterOnSharedPreferenceChangeListener(mSharedPreferenceChangeListener);

    unregisterReceiver(mActiveReceiver);

    if (mCallStateMonitor != null) {
        unregisterReceiver(mCallStateMonitor);
    }

    if (mRingerModeAndScreenMonitor != null) {
        unregisterReceiver(mRingerModeAndScreenMonitor);
    }

    if (mRadialMenuManager != null) {
        unregisterReceiver(mRadialMenuManager);
        mRadialMenuManager.clearCache();
    }

    if (mVolumeMonitor != null) {
        unregisterReceiver(mVolumeMonitor);
        mVolumeMonitor.releaseControl();
    }

    if (mPackageReceiver != null) {
        unregisterReceiver(mPackageReceiver);
    }

    if (mShakeDetector != null) {
        mShakeDetector.setEnabled(false);
    }

    if (SUPPORTS_TOUCH_PREF) {
        final ContentResolver resolver = getContentResolver();
        resolver.unregisterContentObserver(mTouchExploreObserver);
    }

    // Disable the proxy activity for long-press search.
    final PackageManager packageManager = getPackageManager();
    final ComponentName shortcutProxy = new ComponentName(this, ShortcutProxyActivity.class);
    packageManager.setComponentEnabledSetting(shortcutProxy, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP);

    // Remove any pending notifications that shouldn't persist.
    final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    nm.cancelAll();

    if (mTtsOverlay != null) {
        mTtsOverlay.hide();
    }
}

From source file:com.irccloud.android.NetworkConnection.java

public synchronized void connect(String sk) {
    Context ctx = IRCCloudApplication.getInstance().getApplicationContext();
    session = sk;/*w  w  w  .j  av  a 2s .co  m*/
    String host = null;
    int port = -1;

    if (sk == null || sk.length() == 0)
        return;

    if (ctx != null) {
        ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();

        if (ni == null || !ni.isConnected()) {
            cancel_idle_timer();
            state = STATE_DISCONNECTED;
            reconnect_timestamp = 0;
            notifyHandlers(EVENT_CONNECTIVITY, null);
            return;
        }
    }

    if (state == STATE_CONNECTING || state == STATE_CONNECTED) {
        Log.w(TAG, "Ignoring duplicate connect request");
        return;
    }
    state = STATE_CONNECTING;

    if (oobTasks.size() > 0) {
        Log.d("IRCCloud", "Clearing OOB tasks before connecting");
    }
    for (Integer bid : oobTasks.keySet()) {
        try {
            oobTasks.get(bid).cancel(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    oobTasks.clear();

    if (Build.VERSION.SDK_INT < 11) {
        if (ctx != null) {
            host = android.net.Proxy.getHost(ctx);
            port = android.net.Proxy.getPort(ctx);
        }
    } else {
        host = System.getProperty("http.proxyHost", null);
        try {
            port = Integer.parseInt(System.getProperty("http.proxyPort", "8080"));
        } catch (NumberFormatException e) {
            port = -1;
        }
    }

    if (!wifiLock.isHeld())
        wifiLock.acquire();

    List<BasicNameValuePair> extraHeaders = Arrays.asList(
            new BasicNameValuePair("Cookie", "session=" + session),
            new BasicNameValuePair("User-Agent", useragent));

    String url = "wss://" + IRCCLOUD_HOST + IRCCLOUD_PATH;
    if (mEvents.highest_eid > 0) {
        url += "?since_id=" + mEvents.highest_eid;
        if (streamId != null && streamId.length() > 0)
            url += "&stream_id=" + streamId;
    }

    if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost")
            && !host.equalsIgnoreCase("127.0.0.1") && port > 0) {
        Crashlytics.log(Log.DEBUG, TAG, "Connecting: " + url + " via proxy: " + host);
    } else {
        Crashlytics.log(Log.DEBUG, TAG, "Connecting: " + url);
    }

    Crashlytics.log(Log.DEBUG, TAG, "Attempt: " + failCount);

    client = new WebSocketClient(URI.create(url), new WebSocketClient.Listener() {
        @Override
        public void onConnect() {
            Crashlytics.log(Log.DEBUG, TAG, "WebSocket connected");
            state = STATE_CONNECTED;
            notifyHandlers(EVENT_CONNECTIVITY, null);
            fetchConfig();
        }

        @Override
        public void onMessage(String message) {
            if (client != null && client.getListener() == this && message.length() > 0) {
                try {
                    synchronized (parserLock) {
                        parse_object(new IRCCloudJSONObject(mapper.readValue(message, JsonNode.class)));
                    }
                } catch (Exception e) {
                    Log.e(TAG, "Unable to parse: " + message);
                    Crashlytics.logException(e);
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onMessage(byte[] data) {
            //Log.d(TAG, String.format("Got binary message! %s", toHexString(data));
        }

        @Override
        public void onDisconnect(int code, String reason) {
            Crashlytics.log(Log.DEBUG, TAG, "WebSocket disconnected");
            ConnectivityManager cm = (ConnectivityManager) IRCCloudApplication.getInstance()
                    .getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo ni = cm.getActiveNetworkInfo();
            if (state == STATE_DISCONNECTING || ni == null || !ni.isConnected())
                cancel_idle_timer();
            else {
                failCount++;
                if (failCount < 4)
                    idle_interval = failCount * 1000;
                else if (failCount < 10)
                    idle_interval = 10000;
                else
                    idle_interval = 30000;
                schedule_idle_timer();
                Crashlytics.log(Log.DEBUG, TAG, "Reconnecting in " + idle_interval / 1000 + " seconds");
            }

            state = STATE_DISCONNECTED;
            notifyHandlers(EVENT_CONNECTIVITY, null);

            if (reason != null && reason.equals("SSL")) {
                Crashlytics.log(Log.ERROR, TAG, "The socket was disconnected due to an SSL error");
                try {
                    JSONObject o = new JSONObject();
                    o.put("message", "Unable to establish a secure connection to the IRCCloud servers.");
                    notifyHandlers(EVENT_FAILURE_MSG, new IRCCloudJSONObject(o));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            client = null;
        }

        @Override
        public void onError(Exception error) {
            Crashlytics.log(Log.ERROR, TAG, "The WebSocket encountered an error: " + error.toString());
            if (state == STATE_DISCONNECTING)
                cancel_idle_timer();
            else {
                failCount++;
                if (failCount < 4)
                    idle_interval = failCount * 1000;
                else if (failCount < 10)
                    idle_interval = 10000;
                else
                    idle_interval = 30000;
                schedule_idle_timer();
                Crashlytics.log(Log.DEBUG, TAG, "Reconnecting in " + idle_interval / 1000 + " seconds");
            }

            state = STATE_DISCONNECTED;
            notifyHandlers(EVENT_CONNECTIVITY, null);
            client = null;
        }
    }, extraHeaders);

    Log.d("IRCCloud", "Creating websocket");
    reconnect_timestamp = 0;
    idle_interval = 0;
    accrued = 0;
    notifyHandlers(EVENT_CONNECTIVITY, null);
    if (client != null) {
        client.setSocketTag(WEBSOCKET_TAG);
        if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost")
                && !host.equalsIgnoreCase("127.0.0.1") && port > 0)
            client.setProxy(host, port);
        else
            client.setProxy(null, -1);
        client.connect();
    }
}