Example usage for android.os Process setThreadPriority

List of usage examples for android.os Process setThreadPriority

Introduction

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

Prototype

public static final native void setThreadPriority(int priority)
        throws IllegalArgumentException, SecurityException;

Source Link

Document

Set the priority of the calling thread, based on Linux priorities.

Usage

From source file:com.nextgis.maplibui.service.LayerFillService.java

protected void startNextTask() {
    if (mQueue.isEmpty()) {
        mNotifyManager.cancel(FILL_NOTIFICATION_ID);
        stopSelf();//w w w .ja v  a 2  s .co m
        return;
    }

    mIsCanceled = false;
    final IProgressor progressor = this;
    new Thread(new Runnable() {
        @Override
        public void run() {
            mIsRunning = true;
            LayerFillTask task = mQueue.remove(0);
            String notifyTitle = task.getDescription();

            mBuilder.setWhen(System.currentTimeMillis()).setContentTitle(notifyTitle).setTicker(notifyTitle);
            mNotifyManager.notify(FILL_NOTIFICATION_ID, mBuilder.build());

            if (mProgressIntent.getExtras() != null)
                mProgressIntent.getExtras().clear();

            mProgressIntent.putExtra(KEY_STATUS, STATUS_START).putExtra(KEY_TITLE, notifyTitle);
            sendBroadcast(mProgressIntent);

            Process.setThreadPriority(Constants.DEFAULT_DOWNLOAD_THREAD_PRIORITY);
            progressor.setValue(0);
            boolean result = task.execute(progressor);

            if (!(task instanceof UnzipForm))
                mProgressIntent.putExtra(KEY_MESSAGE, mProgressMessage);

            mProgressIntent.putExtra(KEY_STATUS, STATUS_STOP);
            mProgressIntent.putExtra(KEY_CANCELLED, mIsCanceled);
            mProgressIntent.putExtra(KEY_RESULT, result);
            mProgressIntent.putExtra(KEY_TOTAL, mQueue.size());

            if (result) {
                mLayerGroup.addLayer(task.getLayer());
                mLayerGroup.save();
            } else
                task.cancel();

            if (task instanceof NGWVectorLayerFillTask && ((NGWVectorLayerFillTask) task).showSyncDialog()) {
                mProgressIntent.putExtra(KEY_SYNC, true);
                mProgressIntent.putExtra(KEY_ACCOUNT, ((NGWVectorLayerFillTask) task).getAccountName());
                mProgressIntent.putExtra(KEY_REMOTE_ID, (task.getLayer().getId()));
            }

            sendBroadcast(mProgressIntent);
            mIsRunning = false;
            startNextTask();
        }
    }).start();
}

From source file:edu.stanford.mobisocial.dungbeetle.MessagingManagerThread.java

@Override
public void run() {
    ProfileScanningObjHandler profileScanningObjHandler = new ProfileScanningObjHandler();
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Set<Long> notSendingObjects = new HashSet<Long>();
    if (DBG)//  www .j ava  2  s . co  m
        Log.i(TAG, "Running...");
    mMessenger.init();
    long max_sent = -1;
    while (!interrupted()) {
        mOco.waitForChange();
        mOco.clearChanged();
        Cursor objs = mHelper.queryUnsentObjects(max_sent);
        try {
            Log.i(TAG, "Sending " + objs.getCount() + " objects...");
            if (objs.moveToFirst())
                do {
                    Long objId = objs.getLong(objs.getColumnIndexOrThrow(DbObject._ID));
                    String jsonSrc = objs.getString(objs.getColumnIndexOrThrow(DbObject.JSON));

                    max_sent = objId.longValue();
                    JSONObject json = null;
                    if (jsonSrc != null) {
                        try {
                            json = new JSONObject(jsonSrc);
                        } catch (JSONException e) {
                            Log.e(TAG, "bad json", e);
                        }
                    } else {
                        json = new JSONObject();
                    }

                    if (json != null) {
                        /*
                         * if you update latest feed here then there is a
                         * race condition between when you put a message
                         * into your db, when you actually have a connection
                         * to send the message (which is here) when other
                         * people send you messages the processing gets all
                         * out of order, so instead we update latest
                         * immediately when you add messages into your db
                         * inside DBHelper.java addToFeed();
                         */
                        // mFeedModifiedObjHandler.handleObj(mContext,
                        // feedUri, objId);

                        // TODO: Don't be fooled! This is not truly an
                        // EncodedObj
                        // and does not yet have a hash.
                        DbObj signedObj = App.instance().getMusubi().objForId(objId);
                        if (signedObj == null) {
                            Log.e(TAG, "Error, object " + objId + " not found in database");
                            notSendingObjects.add(objId);
                            continue;
                        }
                        DbEntryHandler h = DbObjects.getObjHandler(json);
                        h.afterDbInsertion(mContext, signedObj);

                        // TODO: Constraint error thrown for now b/c local
                        // user not in contacts
                        profileScanningObjHandler.handleObj(mContext, h, signedObj);
                    }

                    OutgoingMessage m = new OutgoingMsg(objs);
                    if (m.contents().getRecipients().isEmpty()) {
                        Log.w(TAG, "No addressees for direct message " + objId);
                        notSendingObjects.add(objId);
                    } else {
                        mMessenger.sendMessage(m);
                    }
                } while (objs.moveToNext());
            if (notSendingObjects.size() > 0) {
                if (DBG)
                    Log.d(TAG, "Marking " + notSendingObjects.size() + " objects sent");
                mHelper.markObjectsAsSent(notSendingObjects);
                notSendingObjects.clear();
            }
        } catch (Exception e) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
                Log.wtf(TAG, "error running notify loop", e);
            } else {
                Log.e(TAG, "error running notify loop", e);
            }
        } finally {
            objs.close();
        }
    }
    mHelper.close();
}

From source file:com.inrista.loggliest.Loggly.java

private static synchronized void start() {
    if (mThread != null && mThread.isAlive())
        return;/*from w  w w .j  a  va2  s  .  c  o m*/

    mThread = new Thread(new Runnable() {
        @Override
        public void run() {
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            mThread.setName(THREAD_NAME);

            List<JSONObject> logBatch = new ArrayList<JSONObject>();
            while (true) {
                try {
                    JSONObject msg = mLogQueue.poll(10, TimeUnit.SECONDS);
                    if (msg != null) {
                        logBatch.add(msg);
                        while ((msg = mLogQueue.poll()) != null)
                            logBatch.add(msg);
                    }

                    long now = SystemClock.elapsedRealtime() / 1000;

                    if (!logBatch.isEmpty()) {
                        mLastLog = now;
                        mLogCounter += logBatch.size();
                        logToFile(logBatch);
                        logBatch.clear();
                    }

                    if ((now - mLastUpload) >= mUploadIntervalSecs || mLogCounter >= mUploadIntervalLogCount) {
                        postLogs();
                    }

                    if (((now - mLastLog) >= mIdleSecs) && mIdleSecs > 0 && mLastLog > 0) {
                        mThread.interrupt();
                    }

                } catch (InterruptedException e) {
                    mLogQueue.drainTo(logBatch);
                    logToFile(logBatch);
                    postLogs();
                    return;
                }
            }
        }
    });

    mThread.start();
}

From source file:com.blue.leaves.util.task.SugarTask.java

private Runnable buildRunnable(@NonNull final Integer id) {
    return new Runnable() {
        @Override/* ww  w  .  j av a  2 s.c  om*/
        public void run() {
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

            /*
             * TODO:
             *
             * Thread safety problem.
             *
             * 
             */
            if (taskMap.containsKey(id)) {
                Message message = Message.obtain();

                try {
                    message.what = MESSAGE_FINISH;
                    message.obj = new Holder(id, taskMap.get(id).onBackground());
                } catch (Exception e) {
                    message.what = MESSAGE_BROKEN;
                    message.obj = new Holder(id, e);
                }

                post(message);
            }
        }
    };
}

From source file:org.fdroid.fdroid.UpdateService.java

@Override
protected void onHandleIntent(Intent intent) {
    Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);

    final long startTime = System.currentTimeMillis();
    String address = intent.getStringExtra(EXTRA_ADDRESS);
    boolean manualUpdate = intent.getBooleanExtra(EXTRA_MANUAL_UPDATE, false);

    try {//from w w w .  j a  v  a 2s.  c o m
        // See if it's time to actually do anything yet...
        if (manualUpdate) {
            Utils.debugLog(TAG, "Unscheduled (manually requested) update");
        } else if (!verifyIsTimeForScheduledRun()) {
            return;
        }

        // Grab some preliminary information, then we can release the
        // database while we do all the downloading, etc...
        List<Repo> repos = RepoProvider.Helper.all(this);

        //List<Repo> swapRepos = new ArrayList<>();
        int unchangedRepos = 0;
        int updatedRepos = 0;
        int errorRepos = 0;
        ArrayList<CharSequence> repoErrors = new ArrayList<>();
        boolean changes = false;
        boolean singleRepoUpdate = !TextUtils.isEmpty(address);
        final Preferences fdroidPrefs = Preferences.get();
        for (final Repo repo : repos) {
            if (!repo.inuse) {
                continue;
            }
            if (singleRepoUpdate && !repo.address.equals(address)) {
                unchangedRepos++;
                continue;
            }
            if (!singleRepoUpdate && repo.isSwap) {
                //swapRepos.add(repo);
                continue;
            }

            sendStatus(this, STATUS_INFO, getString(R.string.status_connecting_to_repo, repo.address));
            RepoUpdater updater = new RepoUpdater(getBaseContext(), repo);
            localBroadcastManager.registerReceiver(downloadProgressReceiver,
                    DownloaderService.getIntentFilter(updater.indexUrl, Downloader.ACTION_PROGRESS));
            updater.setProgressListener(this);
            try {
                updater.update();
                if (updater.hasChanged()) {
                    updatedRepos++;
                    changes = true;
                } else {
                    unchangedRepos++;
                }
            } catch (RepoUpdater.UpdateException e) {
                errorRepos++;
                repoErrors.add(e.getMessage());
                Log.e(TAG, "Error updating repository " + repo.address, e);
            }
            localBroadcastManager.unregisterReceiver(downloadProgressReceiver);

            // now that downloading the index is done, start downloading updates
            if (changes && fdroidPrefs.isAutoDownloadEnabled()) {
                autoDownloadUpdates(repo.address);
            }
        }

        if (!changes) {
            Utils.debugLog(TAG,
                    "Not checking app details or compatibility, because all repos were up to date.");
        } else {
            notifyContentProviders();

            if (fdroidPrefs.isUpdateNotificationEnabled() && !fdroidPrefs.isAutoDownloadEnabled()) {
                performUpdateNotification();
            }
        }

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        SharedPreferences.Editor e = prefs.edit();
        e.putLong(STATE_LAST_UPDATED, System.currentTimeMillis());
        PreferencesCompat.apply(e);

        if (errorRepos == 0) {
            if (changes) {
                sendStatus(this, STATUS_COMPLETE_WITH_CHANGES);
            } else {
                sendStatus(this, STATUS_COMPLETE_AND_SAME);
            }
        } else {
            if (updatedRepos + unchangedRepos == 0) {
                sendRepoErrorStatus(STATUS_ERROR_LOCAL, repoErrors);
            } else {
                sendRepoErrorStatus(STATUS_ERROR_LOCAL_SMALL, repoErrors);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Exception during update processing", e);
        sendStatus(this, STATUS_ERROR_GLOBAL, e.getMessage());
    }

    long time = System.currentTimeMillis() - startTime;
    Log.i(TAG, "Updating repo(s) complete, took " + time / 1000 + " seconds to complete.");
}

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 ww w.j av a  2 s  . com
    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:org.kontalk.sync.Syncer.java

/**
 * The actual sync procedure.//from  w  w  w.  j  a  v  a 2s  .c  o  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 av a2  s  .  c  om

    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 w  w w. j  a v  a2s . c  o m*/
 *
 * @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//from ww w.j  a  v  a  2 s .c  o 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));
            }
        }
    });
}