Example usage for android.os Process THREAD_PRIORITY_BACKGROUND

List of usage examples for android.os Process THREAD_PRIORITY_BACKGROUND

Introduction

In this page you can find the example usage for android.os Process THREAD_PRIORITY_BACKGROUND.

Prototype

int THREAD_PRIORITY_BACKGROUND

To view the source code for android.os Process THREAD_PRIORITY_BACKGROUND.

Click Source Link

Document

Standard priority background threads.

Usage

From source file:com.matthewmitchell.peercoin_android_wallet.ui.SendCoinsFragment.java

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

    setRetainInstance(true);/*from w  ww  . j a v  a2s.  c om*/
    setHasOptionsMenu(true);

    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    backgroundThread = new HandlerThread("backgroundThread", Process.THREAD_PRIORITY_BACKGROUND);
    backgroundThread.start();
    backgroundHandler = new Handler(backgroundThread.getLooper());

    if (savedInstanceState != null) {
        restoreInstanceState(savedInstanceState);
    } else {
        final Intent intent = activity.getIntent();
        final String action = intent.getAction();
        final Uri intentUri = intent.getData();
        final String scheme = intentUri != null ? intentUri.getScheme() : null;
        final String mimeType = intent.getType();

        if ((Intent.ACTION_VIEW.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))
                && intentUri != null && "ppcoin".equals(scheme)) {
            initStateFromPeercoinUri(intentUri);
        } else if ((NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))
                && PaymentProtocol.MIMETYPE_PAYMENTREQUEST.equals(mimeType)) {
            final NdefMessage ndefMessage = (NdefMessage) intent
                    .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)[0];
            final byte[] ndefMessagePayload = Nfc.extractMimePayload(PaymentProtocol.MIMETYPE_PAYMENTREQUEST,
                    ndefMessage);
            initStateFromPaymentRequest(mimeType, ndefMessagePayload);
        } else if ((Intent.ACTION_VIEW.equals(action))
                && PaymentProtocol.MIMETYPE_PAYMENTREQUEST.equals(mimeType)) {
            final byte[] paymentRequest = PeercoinIntegration.paymentRequestFromIntent(intent);

            if (intentUri != null)
                initStateFromIntentUri(mimeType, intentUri);
            else if (paymentRequest != null)
                initStateFromPaymentRequest(mimeType, paymentRequest);
            else
                throw new IllegalArgumentException();
        } else if (intent.hasExtra(SendCoinsActivity.INTENT_EXTRA_PAYMENT_INTENT)) {
            initStateFromIntentExtras(intent.getExtras());
        } else {
            updateStateFrom(PaymentIntent.blank());
        }
    }
}

From source file:com.hivewallet.androidclient.wallet.ui.send.SendCoinsFragment.java

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

    setRetainInstance(true);//from   ww w.j a v a 2 s . c  om
    setHasOptionsMenu(true);

    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    backgroundThread = new HandlerThread("backgroundThread", Process.THREAD_PRIORITY_BACKGROUND);
    backgroundThread.start();
    backgroundHandler = new Handler(backgroundThread.getLooper());

    if (savedInstanceState != null) {
        restoreInstanceState(savedInstanceState);
    } else {
        final Intent intent = activity.getIntent();
        final String action = intent.getAction();
        final Uri intentUri = intent.getData();
        final String scheme = intentUri != null ? intentUri.getScheme() : null;
        final String mimeType = intent.getType();

        if ((Intent.ACTION_VIEW.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))
                && intentUri != null && "bitcoin".equals(scheme)) {
            initStateFromBitcoinUri(intentUri);
        } else if ((NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))
                && PaymentProtocol.MIMETYPE_PAYMENTREQUEST.equals(mimeType)) {
            final NdefMessage ndefMessage = (NdefMessage) intent
                    .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)[0];
            final byte[] ndefMessagePayload = Nfc.extractMimePayload(PaymentProtocol.MIMETYPE_PAYMENTREQUEST,
                    ndefMessage);
            initStateFromPaymentRequest(mimeType, ndefMessagePayload);
        } else if ((Intent.ACTION_VIEW.equals(action))
                && PaymentProtocol.MIMETYPE_PAYMENTREQUEST.equals(mimeType)) {
            final byte[] paymentRequest = BitcoinIntegration.paymentRequestFromIntent(intent);

            if (intentUri != null)
                initStateFromIntentUri(mimeType, intentUri);
            else if (paymentRequest != null)
                initStateFromPaymentRequest(mimeType, paymentRequest);
            else
                throw new IllegalArgumentException();
        } else if (intent.hasExtra(SendCoinsActivity.INTENT_EXTRA_PAYMENT_INTENT)) {
            initStateFromIntentExtras(intent.getExtras());
        } else {
            updateStateFrom(PaymentIntent.blank());
        }
    }
}

From source file:com.android.email.activity.zx.MessageView.java

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

    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    setContentView(R.layout.message_view);

    mSubjectView = (TextView) findViewById(R.id.subject);
    mFromView = (TextView) findViewById(R.id.from);
    mToView = (TextView) findViewById(R.id.to);
    mCcView = (TextView) findViewById(R.id.cc);
    mCcContainerView = findViewById(R.id.cc_container);
    mDateView = (TextView) findViewById(R.id.date);
    mTimeView = (TextView) findViewById(R.id.time);
    mMessageContentView = (WebView) findViewById(R.id.message_content);
    mAttachments = (LinearLayout) findViewById(R.id.attachments);
    mAttachmentIcon = (ImageView) findViewById(R.id.attachment);
    mShowPicturesSection = findViewById(R.id.show_pictures_section);
    mSenderPresenceView = (ImageView) findViewById(R.id.presence);

    mMessageContentView.setVerticalScrollBarEnabled(false);
    mAttachments.setVisibility(View.GONE);
    mAttachmentIcon.setVisibility(View.GONE);

    mFromView.setOnClickListener(this);
    mSenderPresenceView.setOnClickListener(this);
    findViewById(R.id.reply).setOnClickListener(this);
    findViewById(R.id.reply_all).setOnClickListener(this);
    findViewById(R.id.delete).setOnClickListener(this);
    findViewById(R.id.show_pictures).setOnClickListener(this);

    mMessageContentView.getSettings().setBlockNetworkImage(true);
    mMessageContentView.getSettings().setSupportZoom(false);

    setTitle("");

    mDateFormat = android.text.format.DateFormat.getDateFormat(this); // short format
    mTimeFormat = android.text.format.DateFormat.getTimeFormat(this); // 12/24 date format

    Intent intent = getIntent();//from w ww . j a v a 2 s .co m
    mAccount = (Account) intent.getSerializableExtra(EXTRA_ACCOUNT);
    mFolder = intent.getStringExtra(EXTRA_FOLDER);
    mMessageUid = intent.getStringExtra(EXTRA_MESSAGE);
    mFolderUids = intent.getStringArrayListExtra(EXTRA_FOLDER_UIDS);

    View next = findViewById(R.id.next);
    View previous = findViewById(R.id.previous);
    /*
     * Next and Previous Message are not shown in landscape mode, so
     * we need to check before we use them.
     */
    if (next != null && previous != null) {
        next.setOnClickListener(this);
        previous.setOnClickListener(this);

        findSurroundingMessagesUid();

        previous.setVisibility(mPreviousMessageUid != null ? View.VISIBLE : View.GONE);
        next.setVisibility(mNextMessageUid != null ? View.VISIBLE : View.GONE);

        boolean goNext = intent.getBooleanExtra(EXTRA_NEXT, false);
        if (goNext) {
            next.requestFocus();
        }
    }

    MessagingController.getInstance(getApplication()).addListener(mListener);
    new Thread() {
        @Override
        public void run() {
            // TODO this is a spot that should be eventually handled by a MessagingController
            // thread pool. We want it in a thread but it can't be blocked by the normal
            // synchronization stuff in MC.
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            MessagingController.getInstance(getApplication()).loadMessageForView(mAccount, mFolder, mMessageUid,
                    mListener);
        }
    }.start();
}

From source file:com.example.alyshia.customsimplelauncher.MainActivity.java

public void setkioskReceiver() {
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(KioskMode.ACTION_ENABLE_KIOSK_MODE_RESULT);
    intentFilter.addAction(KioskMode.ACTION_DISABLE_KIOSK_MODE_RESULT);

    if (kioskReceiver == null) {
        kioskReceiver = new KioskReceiver(this, MainActivity.this);
        HandlerThread handlerThread = new HandlerThread("DifferentThread", Process.THREAD_PRIORITY_BACKGROUND);
        handlerThread.start();//from  w ww.  j ava2s.  c o  m
        Looper looper = handlerThread.getLooper();
        kioskHandler = new Handler(looper, this);
        registerReceiver(kioskReceiver, intentFilter, null, kioskHandler);
    }

}

From source file:com.kncwallet.wallet.ui.SendCoinsFragment.java

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

    setHasOptionsMenu(true);//from   ww w .ja  v  a 2  s .  c om

    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    backgroundThread = new HandlerThread("backgroundThread", Process.THREAD_PRIORITY_BACKGROUND);
    backgroundThread.start();
    backgroundHandler = new Handler(backgroundThread.getLooper());

    final String precision = prefs.getString(Constants.PREFS_KEY_BTC_PRECISION,
            Constants.PREFS_DEFAULT_BTC_PRECISION);
    btcPrecision = precision.charAt(0) - '0';
    btcShift = precision.length() == 3 ? precision.charAt(2) - '0' : 0;
}

From source file:org.kontalk.sync.Syncer.java

/**
 * The actual sync procedure.//from w ww.j  av a 2  s .co  m
 * This one uses the slowest method ever: it first checks for every phone
 * number in all contacts and it sends them to the server. Once a response
 * is received, it deletes all the raw contacts created by us and then
 * recreates only the ones the server has found a match for.
 */
public void performSync(Context context, Account account, String authority, ContentProviderClient provider,
        ContentProviderClient usersProvider, SyncResult syncResult) throws OperationCanceledException {

    final Map<String, RawPhoneNumberEntry> lookupNumbers = new HashMap<>();
    final List<String> jidList = new ArrayList<>();

    // resync users database
    Log.v(TAG, "resyncing users database");
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    // update users database
    Uri uri = Users.CONTENT_URI.buildUpon().appendQueryParameter(Users.RESYNC, "true").build();
    try {
        int count = usersProvider.update(uri, new ContentValues(), null, null);
        Log.d(TAG, "users database resynced (" + count + ")");
    } catch (Exception e) {
        Log.e(TAG, "error resyncing users database - aborting sync", e);
        syncResult.databaseError = true;
        return;
    }

    // query all contacts
    Cursor cursor;
    try {
        cursor = usersProvider.query(Users.CONTENT_URI_OFFLINE,
                new String[] { Users.JID, Users.NUMBER, Users.LOOKUP_KEY }, null, null, null);
    } catch (Exception e) {
        Log.e(TAG, "error querying users database - aborting sync", e);
        syncResult.databaseError = true;
        return;
    }

    while (cursor.moveToNext()) {
        if (mCanceled) {
            cursor.close();
            throw new OperationCanceledException();
        }

        String jid = cursor.getString(0);
        String number = cursor.getString(1);
        String lookupKey = cursor.getString(2);

        // avoid to send duplicates to the server
        if (lookupNumbers.put(XmppStringUtils.parseLocalpart(jid),
                new RawPhoneNumberEntry(lookupKey, number, jid)) == null)
            jidList.add(jid);
    }
    cursor.close();

    if (mCanceled)
        throw new OperationCanceledException();

    // empty contacts :-|
    if (jidList.size() == 0) {
        // delete all Kontalk raw contacts
        try {
            syncResult.stats.numDeletes += deleteAll(account, provider);
        } catch (Exception e) {
            Log.e(TAG, "contact delete error", e);
            syncResult.databaseError = true;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            try {
                syncResult.stats.numDeletes += deleteProfile(account, provider);
            } catch (Exception e) {
                Log.e(TAG, "profile delete error", e);
                syncResult.databaseError = true;
            }
        }

        commit(usersProvider, syncResult);
    }

    else {
        final LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(mContext);

        // register presence broadcast receiver
        PresenceBroadcastReceiver receiver = new PresenceBroadcastReceiver(jidList, this);
        IntentFilter f = new IntentFilter();
        f.addAction(MessageCenterService.ACTION_PRESENCE);
        f.addAction(MessageCenterService.ACTION_ROSTER_MATCH);
        f.addAction(MessageCenterService.ACTION_PUBLICKEY);
        f.addAction(MessageCenterService.ACTION_BLOCKLIST);
        f.addAction(MessageCenterService.ACTION_LAST_ACTIVITY);
        f.addAction(MessageCenterService.ACTION_CONNECTED);
        lbm.registerReceiver(receiver, f);

        // request current connection status
        MessageCenterService.requestConnectionStatus(mContext);

        // wait for the service to complete its job
        synchronized (this) {
            // wait for connection
            try {
                wait(MAX_WAIT_TIME);
            } catch (InterruptedException e) {
                // simulate canceled operation
                mCanceled = true;
            }
        }

        lbm.unregisterReceiver(receiver);

        // last chance to quit
        if (mCanceled)
            throw new OperationCanceledException();

        List<PresenceItem> res = receiver.getResponse();
        if (res != null) {
            ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
            // TODO operations.size() could be used instead (?)
            int op = 0;

            // this is the time - delete all Kontalk raw contacts
            try {
                syncResult.stats.numDeletes += deleteAll(account, provider);
            } catch (Exception e) {
                Log.e(TAG, "contact delete error", e);
                syncResult.databaseError = true;
                return;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                try {
                    syncResult.stats.numDeletes += deleteProfile(account, provider);
                } catch (Exception e) {
                    Log.e(TAG, "profile delete error", e);
                    syncResult.databaseError = true;
                }
            }

            ContentValues registeredValues = new ContentValues();
            registeredValues.put(Users.REGISTERED, 1);
            for (int i = 0; i < res.size(); i++) {
                PresenceItem entry = res.get(i);
                if (entry.discarded)
                    continue;

                final RawPhoneNumberEntry data = lookupNumbers.get(XmppStringUtils.parseLocalpart(entry.from));
                if (data != null && data.lookupKey != null) {
                    // add contact
                    addContact(account, getDisplayName(provider, data.lookupKey, data.number), data.number,
                            data.jid, operations, op++);
                } else {
                    syncResult.stats.numSkippedEntries++;
                }

                // update fields
                try {
                    String status = entry.status;

                    if (!TextUtils.isEmpty(status))
                        registeredValues.put(Users.STATUS, status);
                    else
                        registeredValues.putNull(Users.STATUS);

                    if (entry.timestamp >= 0)
                        registeredValues.put(Users.LAST_SEEN, entry.timestamp);
                    else
                        registeredValues.putNull(Users.LAST_SEEN);

                    if (entry.publicKey != null) {
                        try {
                            PGPPublicKey pubKey = PGP.getMasterKey(entry.publicKey);
                            // trust our own key blindly
                            int trustLevel = Authenticator.isSelfJID(mContext, entry.from)
                                    ? MyUsers.Keys.TRUST_VERIFIED
                                    : -1;
                            // update keys table immediately
                            Keyring.setKey(mContext, entry.from, entry.publicKey, trustLevel);

                            // no data from system contacts, use name from public key
                            if (data == null) {
                                PGPUserID uid = PGP.parseUserId(pubKey,
                                        XmppStringUtils.parseDomain(entry.from));
                                if (uid != null) {
                                    registeredValues.put(Users.DISPLAY_NAME, uid.getName());
                                }
                            }
                        } catch (Exception e) {
                            Log.w(TAG, "unable to parse public key", e);
                        }
                    } else {
                        // use roster name if no contact data available
                        if (data == null && entry.rosterName != null) {
                            registeredValues.put(Users.DISPLAY_NAME, entry.rosterName);
                        }
                    }

                    // blocked status
                    registeredValues.put(Users.BLOCKED, entry.blocked);
                    // user JID as reported by the server
                    registeredValues.put(Users.JID, entry.from);

                    /*
                     * Since UsersProvider.resync inserted the user row
                     * using our server name, it might have changed because
                     * of what the server reported. We already put into the
                     * values the new JID, but we need to use the old one
                     * in the where condition so we will have a match.
                     */
                    String origJid;
                    if (data != null)
                        origJid = XMPPUtils.createLocalJID(mContext,
                                XmppStringUtils.parseLocalpart(entry.from));
                    else
                        origJid = entry.from;
                    usersProvider.update(Users.CONTENT_URI_OFFLINE, registeredValues, Users.JID + " = ?",
                            new String[] { origJid });

                    // clear data
                    registeredValues.remove(Users.DISPLAY_NAME);

                    // if this is our own contact, trust our own key later
                    if (Authenticator.isSelfJID(mContext, entry.from)) {
                        // register our profile while we're at it
                        if (data != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                            // add contact
                            addProfile(account, Authenticator.getDefaultDisplayName(mContext), data.number,
                                    data.jid, operations, op++);
                        }
                    }
                } catch (Exception e) {
                    Log.e(TAG, "error updating users database", e);
                    // we shall continue here...
                }
            }

            try {
                if (operations.size() > 0)
                    provider.applyBatch(operations);
                syncResult.stats.numInserts += op;
                syncResult.stats.numEntries += op;
            } catch (Exception e) {
                Log.w(TAG, "contact write error", e);
                syncResult.stats.numSkippedEntries += op;
                /*
                 * We do not consider system contacts failure a fatal error.
                 * This is actually a workaround for systems with disabled permissions or
                 * exotic firmwares. It can also protect against security 3rd party apps or
                 * non-Android platforms, such as Jolla/Alien Dalvik.
                 */
            }

            commit(usersProvider, syncResult);
        }

        // timeout or error
        else {
            Log.w(TAG, "connection timeout - aborting sync");

            syncResult.stats.numIoExceptions++;
        }
    }
}

From source file:com.newsrob.EntryManager.java

private void switchStorageProvider() {

    Log.d(TAG, "Switch Storage Provider");

    if (isModelCurrentlyUpdated())
        return;/*from  ww w .  j  a v a  2 s .c o m*/

    final String newPrefValue = getSharedPreferences().getString(SETTINGS_STORAGE_PROVIDER_KEY, null);
    final String oldStorageProviderClass = fileContextAdapter.getClass().getName();

    final String newStorageProviderClass = STORAGE_PROVIDER_SD_CARD.equals(newPrefValue)
            ? SdCardStorageAdapter.class.getName()
            : PhoneMemoryStorageAdapter.class.getName();
    if (!oldStorageProviderClass.equals(newStorageProviderClass)) {

        runningThread = new Thread(new Runnable() {

            public void run() {
                final PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
                final PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
                Log.i(TAG, "Wake lock acquired at " + new Date().toString() + ".");
                wl.acquire();
                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                final Timing t = new Timing("Storage Provider Switch", ctx);
                ModelUpdateResult result = null;
                if (isModelCurrentlyUpdated())
                    return;
                try {
                    lockModel("EM.switchStorageProvider.run");
                } catch (final IllegalStateException ise) {
                    return;
                }
                try {

                    Log.i(TAG, "Switching storage providers started at " + new Date().toString() + ".");

                    fireModelUpdateStarted("Switching storage providers", false, true);
                    Log.d(TAG, "Change of storage provider detected.");

                    final List<Job> jobList = new LinkedList<Job>();

                    final Job clearOldStorageProvider = new Job("Clearing Old Storage Provider",
                            EntryManager.this) {

                        @Override
                        public void run() {
                            Log.d(TAG, "Clearing the old storage provider.");
                            doClearCache();
                            if (fileContextAdapter.canWrite())
                                WebPageDownloadDirector.removeAllAssets(fileContextAdapter);
                        }

                    };
                    jobList.add(clearOldStorageProvider);
                    final Job switchStorageProviders = new Job("Switching Storage Providers",
                            EntryManager.this) {

                        @Override
                        public void run() throws Exception {
                            Log.d(TAG, "Establishing new storage provider: " + newStorageProviderClass);
                            fileContextAdapter = newStorageProviderClass.equals(
                                    SdCardStorageAdapter.class.getName()) ? new SdCardStorageAdapter(ctx)
                                            : new PhoneMemoryStorageAdapter(ctx);

                            Log.d(TAG, "New storage provider established.");
                        }

                    };
                    jobList.add(switchStorageProviders);

                    final Job clearNewStorageProvider = new Job("Clearing New Storage Provider",
                            EntryManager.this) {

                        @Override
                        public void run() {
                            Log.d(TAG, "Clearing the new storage provider.");
                            doClearCache();
                            if (fileContextAdapter.canWrite())
                                WebPageDownloadDirector.removeAllAssets(fileContextAdapter);
                        }

                    };
                    jobList.add(clearNewStorageProvider);

                    runJobs(jobList);

                    result = new SwitchStorageProviderResult();

                } catch (final Throwable throwable) {
                    result = new SwitchStorageProviderFailed(throwable);
                    Log.d(TAG, "Problem during switching storage providers.", throwable);
                    t.stop();
                } finally {
                    unlockModel("EM.switchStorageProvider.run");
                    clearCancelState();
                    fireModelUpdateFinished(result);
                    fireStatusUpdated();
                    Log.i(TAG, "Switching storage providers finished at " + new Date().toString() + ".");

                    wl.release();
                    t.stop();
                }
            }

        }, "Storage Provider Switch Worker");
        runningThread.start();
    }
}

From source file:com.lazy.gank.logging.Logcat.java

/**
 * Log //from   ww w .j  a  v  a  2 s . c  om
 *
 * @param logLevel
 * @param msg
 * @param logFileName
 * @param tag
 */
private static void writeLog(@LockLevel final int logLevel, final Object msg,
        @Nullable final String logFileName, final String... tag) {
    if (OPERATION_BIT != (logLevel & m_cFileSaveLogType)) {
        //?
        final StackTraceElement stackTraceElement = getStackTraceElement(INDEX);
        mSingleExecutors.execute(new Runnable() {
            @Override
            public void run() {
                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                fileLog(stackTraceElement, logLevel, msg, logFileName, tag);
            }
        });
    }
}

From source file:com.syncedsynapse.kore2.jsonrpc.HostConnection.java

private Thread newListenerThread(final Socket socket) {
    // Launch a new thread to read from the socket
    return new Thread(new Runnable() {
        @Override/*  ww  w  .j av a  2  s  .  co  m*/
        public void run() {
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            try {
                LogUtils.LOGD(TAG, "Starting socket listener thread...");
                // We're going to read from the socket. This will be a blocking call and
                // it will keep on going until disconnect() is called on this object.
                // Note: Mind the objects used here: we use createParser because it doesn't
                // close the socket after ObjectMapper.readTree.
                JsonParser jsonParser = objectMapper.getFactory().createParser(socket.getInputStream());
                ObjectNode jsonResponse;
                while ((jsonResponse = objectMapper.readTree(jsonParser)) != null) {
                    LogUtils.LOGD(TAG, "Read from socket: " + jsonResponse.toString());
                    //                        LogUtils.LOGD_FULL(TAG, "Read from socket: " + jsonResponse.toString());
                    handleTcpResponse(jsonResponse);
                }
            } catch (JsonProcessingException e) {
                LogUtils.LOGW(TAG, "Got an exception while parsing JSON response.", e);
                callErrorCallback(null, new ApiException(ApiException.INVALID_JSON_RESPONSE_FROM_HOST, e));
            } catch (IOException e) {
                LogUtils.LOGW(TAG, "Error reading from socket.", e);
                disconnect();
                callErrorCallback(null, new ApiException(ApiException.IO_EXCEPTION_WHILE_READING_RESPONSE, e));
            }
        }
    });
}

From source file:org.kontalk.service.msgcenter.MessageCenterService.java

private void createIdleHandler() {
    HandlerThread thread = new HandlerThread("IdleThread", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();/*from w  ww  .  java 2  s. co  m*/
    int refCount = Kontalk.get(this).getReferenceCounter();
    mIdleHandler = new IdleConnectionHandler(this, refCount, thread.getLooper());
}