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:org.peterbaldwin.vlcremote.sweep.PortSweeper.java

public PortSweeper(int port, String file, int threadCount, Callback callback, Looper looper) {
    mPort = port;/*from ww w .  j  a va 2 s . c o  m*/
    mPath = file;
    mWorkerCount = threadCount;
    mCallback = callback;

    mAddressQueue = new ConcurrentLinkedQueue<byte[]>();

    mWorkerManager = new MyWorkerManager();

    mWorkerCallback = new MyWorkerCallback();

    mScanThread = new HandlerThread("Scanner", Process.THREAD_PRIORITY_BACKGROUND);
    mScanThread.start();

    Handler.Callback callbackHandlerCallback = new MyCallbackHandlerCallback();
    mCallbackHandler = new Handler(looper, callbackHandlerCallback);

    Handler.Callback scanHandlerCallback = new MyScanHandlerCallback();
    mScanHandler = new Handler(mScanThread.getLooper(), scanHandlerCallback);
}

From source file:com.tgx.tina.android.plugin.downloader.DownloadThread.java

/**
 * Executes the download in a separate thread
 *//*from   w w  w. ja v  a  2  s.c o m*/
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    int finalStatus = GlobalDownload.STATUS_UNKNOWN_ERROR;
    boolean countRetry = false;
    int retryAfter = 0;
    int redirectCount = mInfo.mRedirectCount;
    String newUri = null;
    boolean gotData = false;
    String filename = null;
    String mimeType = sanitizeMimeType(mInfo.mMimeType);
    FileOutputStream stream = null;
    DefaultHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    Uri contentUri = Uri.parse(GlobalDownload.CONTENT_URI + "/" + mInfo.mId);

    try {
        boolean continuingDownload = false;
        String headerAcceptRanges = null;
        String headerContentDisposition = null;
        String headerContentLength = null;
        String headerContentLocation = null;
        String headerETag = null;
        String headerTransferEncoding = null;

        byte data[] = new byte[Constants.BUFFER_SIZE];

        int bytesSoFar = 0;

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

        filename = mInfo.mFileName;
        if (filename != null) {
            if (!Helpers.isFilenameValid(filename)) {
                finalStatus = GlobalDownload.STATUS_FILE_ERROR;
                notifyDownloadCompleted(finalStatus, false, 0, 0, false, filename, null, mInfo.mMimeType);
                return;
            }
            // We're resuming a download that got interrupted
            File f = new File(filename);
            if (f.exists()) {
                long fileLength = f.length();
                if (fileLength == 0) {
                    // The download hadn't actually started, we can restart from scratch
                    f.delete();
                    filename = null;
                } else if (mInfo.mETag == null && !mInfo.mNoIntegrity) {
                    // Tough luck, that's not a resumable download
                    //#debug
                    base.tina.core.log.LogPrinter.d(Constants.TAG,
                            "can't resume interrupted non-resumable download");
                    f.delete();
                    finalStatus = GlobalDownload.STATUS_PRECONDITION_FAILED;
                    notifyDownloadCompleted(finalStatus, false, 0, 0, false, filename, null, mInfo.mMimeType);
                    return;
                } else {
                    // All right, we'll be able to resume this download
                    stream = new FileOutputStream(filename, true);
                    bytesSoFar = (int) fileLength;
                    if (mInfo.mTotalBytes != -1) {
                        headerContentLength = Integer.toString(mInfo.mTotalBytes);
                    }
                    headerETag = mInfo.mETag;
                    continuingDownload = true;
                }
            }
        }

        int bytesNotified = bytesSoFar;
        // starting with MIN_VALUE means that the first write will commit
        //     progress to the database
        long timeLastNotification = 0;

        client = newHttpClient(userAgent());
        /*
         * This loop is run once for every individual HTTP request that gets
         * sent. The very first HTTP request is a "virgin" request, while
         * every subsequent request is done with the original ETag and a
         * byte-range.
         */
        http_request_loop: while (true) {
            // Prepares the request and fires it.
            HttpGet request = new HttpGet(mInfo.mUri);

            //#debug verbose
            base.tina.core.log.LogPrinter.v(Constants.TAG, "initiating download for " + mInfo.mUri);

            if (mInfo.mCookies != null) {
                request.addHeader("Cookie", mInfo.mCookies);
            }
            if (mInfo.mReferer != null) {
                request.addHeader("Referer", mInfo.mReferer);
            }
            if (continuingDownload) {
                if (headerETag != null) {
                    request.addHeader("If-Match", headerETag);
                }
                request.addHeader("Range", "bytes=" + bytesSoFar + "-");
            }

            HttpResponse response;
            try {
                response = client.execute(request);
            } catch (IllegalArgumentException ex) {
                //#debug
                base.tina.core.log.LogPrinter.d(Constants.TAG,
                        "Arg exception trying to execute request for " + mInfo.mId + " : " + ex);
                finalStatus = GlobalDownload.STATUS_BAD_REQUEST;
                request.abort();
                break http_request_loop;
            } catch (IOException ex) {
                //#ifdef debug
                //#if debug<=2
                if (Helpers.isNetworkAvailable(mContext)) {
                    base.tina.core.log.LogPrinter.i(Constants.TAG, "Execute Failed " + mInfo.mId + ", Net Up");
                } else {
                    base.tina.core.log.LogPrinter.i(Constants.TAG,
                            "Execute Failed " + mInfo.mId + ", Net Down");
                }
                //#endif
                //#endif

                if (!Helpers.isNetworkAvailable(mContext)) {
                    finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED;
                } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) {
                    finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED;
                    countRetry = true;
                } else {
                    //#debug
                    base.tina.core.log.LogPrinter.d(Constants.TAG,
                            "IOException trying to execute request for " + mInfo.mId + " : " + ex);
                    finalStatus = GlobalDownload.STATUS_HTTP_DATA_ERROR;
                }
                request.abort();
                break http_request_loop;
            }

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 503 && mInfo.mNumFailed < Constants.MAX_RETRIES) {
                //#debug verbose
                base.tina.core.log.LogPrinter.v(Constants.TAG, "got HTTP response code 503");
                finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED;
                countRetry = true;
                Header header = response.getFirstHeader("Retry-After");
                if (header != null) {
                    try {
                        //#debug verbose
                        base.tina.core.log.LogPrinter.v(Constants.TAG, "Retry-After :" + header.getValue());
                        retryAfter = Integer.parseInt(header.getValue());
                        if (retryAfter < 0) {
                            retryAfter = 0;
                        } else {
                            if (retryAfter < Constants.MIN_RETRY_AFTER) {
                                retryAfter = Constants.MIN_RETRY_AFTER;
                            } else if (retryAfter > Constants.MAX_RETRY_AFTER) {
                                retryAfter = Constants.MAX_RETRY_AFTER;
                            }
                            retryAfter += Helpers.sRandom.nextInt(Constants.MIN_RETRY_AFTER + 1);
                            retryAfter *= 1000;
                        }
                    } catch (NumberFormatException ex) {
                        // ignored - retryAfter stays 0 in this case.
                    }
                }
                request.abort();
                break http_request_loop;
            }
            if (statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 307) {
                //#debug verbose
                base.tina.core.log.LogPrinter.v(Constants.TAG, "got HTTP redirect " + statusCode);
                if (redirectCount >= Constants.MAX_REDIRECTS) {
                    //#debug
                    base.tina.core.log.LogPrinter.d(Constants.TAG,
                            "too many redirects for download " + mInfo.mId);
                    finalStatus = GlobalDownload.STATUS_TOO_MANY_REDIRECTS;
                    request.abort();
                    break http_request_loop;
                }
                Header header = response.getFirstHeader("Location");
                if (header != null) {
                    //#debug verbose
                    base.tina.core.log.LogPrinter.v(Constants.TAG, "Location :" + header.getValue());
                    try {
                        newUri = new URI(mInfo.mUri).resolve(new URI(header.getValue())).toString();
                    } catch (URISyntaxException ex) {
                        //#debug
                        base.tina.core.log.LogPrinter.d(Constants.TAG,
                                "Couldn't resolve redirect URI for download " + mInfo.mId);
                        finalStatus = GlobalDownload.STATUS_BAD_REQUEST;
                        request.abort();
                        break http_request_loop;
                    }
                    ++redirectCount;
                    finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED;
                    request.abort();
                    break http_request_loop;
                }
            }
            if ((!continuingDownload && statusCode != GlobalDownload.STATUS_SUCCESS)
                    || (continuingDownload && statusCode != 206)) {
                //#debug
                base.tina.core.log.LogPrinter.d(Constants.TAG,
                        "http error " + statusCode + " for download " + mInfo.mId);
                if (GlobalDownload.isStatusError(statusCode)) {
                    finalStatus = statusCode;
                } else if (statusCode >= 300 && statusCode < 400) {
                    finalStatus = GlobalDownload.STATUS_UNHANDLED_REDIRECT;
                } else if (continuingDownload && statusCode == GlobalDownload.STATUS_SUCCESS) {
                    finalStatus = GlobalDownload.STATUS_PRECONDITION_FAILED;
                } else {
                    finalStatus = GlobalDownload.STATUS_UNHANDLED_HTTP_CODE;
                }
                request.abort();
                break http_request_loop;
            } else {
                // Handles the response, saves the file
                //#debug verbose
                base.tina.core.log.LogPrinter.v(Constants.TAG, "received response for " + mInfo.mUri);

                if (!continuingDownload) {
                    Header header = response.getFirstHeader("Accept-Ranges");
                    if (header != null) {
                        headerAcceptRanges = header.getValue();
                    }
                    header = response.getFirstHeader("Content-Disposition");
                    if (header != null) {
                        headerContentDisposition = header.getValue();
                    }
                    header = response.getFirstHeader("Content-Location");
                    if (header != null) {
                        headerContentLocation = header.getValue();
                    }
                    if (mimeType == null) {
                        header = response.getFirstHeader("Content-Type");
                        if (header != null) {
                            mimeType = sanitizeMimeType(header.getValue());
                        }
                    }
                    header = response.getFirstHeader("ETag");
                    if (header != null) {
                        headerETag = header.getValue();
                    }
                    header = response.getFirstHeader("Transfer-Encoding");
                    if (header != null) {
                        headerTransferEncoding = header.getValue();
                    }
                    if (headerTransferEncoding == null) {
                        header = response.getFirstHeader("Content-Length");
                        if (header != null) {
                            headerContentLength = header.getValue();
                        }
                    } else {
                        // Ignore content-length with transfer-encoding - 2616 4.4 3
                        //#debug verbose
                        base.tina.core.log.LogPrinter.v(Constants.TAG,
                                "ignoring content-length because of xfer-encoding");
                    }
                    //#ifdef debug
                    //#if debug<=2
                    base.tina.core.log.LogPrinter.v(Constants.TAG, "Accept-Ranges: " + headerAcceptRanges);
                    base.tina.core.log.LogPrinter.v(Constants.TAG,
                            "Content-Disposition: " + headerContentDisposition);
                    base.tina.core.log.LogPrinter.v(Constants.TAG, "Content-Length: " + headerContentLength);
                    base.tina.core.log.LogPrinter.v(Constants.TAG,
                            "Content-Location: " + headerContentLocation);
                    base.tina.core.log.LogPrinter.v(Constants.TAG, "Content-Type: " + mimeType);
                    base.tina.core.log.LogPrinter.v(Constants.TAG, "ETag: " + headerETag);
                    base.tina.core.log.LogPrinter.v(Constants.TAG,
                            "Transfer-Encoding: " + headerTransferEncoding);
                    //#endif
                    //#endif

                    if (!mInfo.mNoIntegrity && headerContentLength == null && (headerTransferEncoding == null
                            || !headerTransferEncoding.equalsIgnoreCase("chunked"))) {
                        //#debug
                        base.tina.core.log.LogPrinter.d(Constants.TAG,
                                "can't know size of download, giving up");
                        finalStatus = GlobalDownload.STATUS_LENGTH_REQUIRED;
                        request.abort();
                        break http_request_loop;
                    }

                    DownloadFileInfo fileInfo = Helpers.generateSaveFile(mContext, mInfo.mUri, mInfo.mHint,
                            headerContentDisposition, headerContentLocation, mimeType, mInfo.mDestination,
                            (headerContentLength != null) ? Integer.parseInt(headerContentLength) : 0);
                    if (fileInfo.mFileName == null) {
                        finalStatus = fileInfo.mStatus;
                        request.abort();
                        break http_request_loop;
                    }
                    filename = fileInfo.mFileName;
                    stream = fileInfo.mStream;
                    //#debug verbose
                    base.tina.core.log.LogPrinter.v(Constants.TAG, "writing " + mInfo.mUri + " to " + filename);

                    ContentValues values = new ContentValues();
                    values.put(GlobalDownload._DATA, filename);
                    if (headerETag != null) {
                        values.put(Constants.ETAG, headerETag);
                    }
                    if (mimeType != null) {
                        values.put(GlobalDownload.COLUMN_MIME_TYPE, mimeType);
                    }
                    int contentLength = -1;
                    if (headerContentLength != null) {
                        contentLength = Integer.parseInt(headerContentLength);
                    }
                    values.put(GlobalDownload.COLUMN_TOTAL_BYTES, contentLength);
                    mContext.getContentResolver().update(contentUri, values, null, null);
                }

                InputStream entityStream;
                try {
                    entityStream = response.getEntity().getContent();
                } catch (IOException ex) {
                    //#ifdef debug
                    //#if debug<=2
                    if (Helpers.isNetworkAvailable(mContext)) {
                        base.tina.core.log.LogPrinter.i(Constants.TAG, "Get Failed " + mInfo.mId + ", Net Up");
                    } else {
                        base.tina.core.log.LogPrinter.i(Constants.TAG,
                                "Get Failed " + mInfo.mId + ", Net Down");
                    }
                    //#endif
                    //#endif
                    if (!Helpers.isNetworkAvailable(mContext)) {
                        finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED;
                    } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) {
                        finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED;
                        countRetry = true;
                    } else {
                        //#debug
                        base.tina.core.log.LogPrinter.d(Constants.TAG,
                                "IOException getting entity for download " + mInfo.mId + " : " + ex);
                        finalStatus = GlobalDownload.STATUS_HTTP_DATA_ERROR;
                    }
                    request.abort();
                    break http_request_loop;
                }
                for (;;) {
                    int bytesRead;
                    try {
                        bytesRead = entityStream.read(data);
                    } catch (IOException ex) {
                        //#ifdef debug
                        //#if debug<=2
                        if (Helpers.isNetworkAvailable(mContext)) {
                            base.tina.core.log.LogPrinter.i(Constants.TAG,
                                    "Read Failed " + mInfo.mId + ", Net Up");
                        } else {
                            base.tina.core.log.LogPrinter.i(Constants.TAG,
                                    "Read Failed " + mInfo.mId + ", Net Down");
                        }
                        //#endif
                        //#endif

                        ContentValues values = new ContentValues();
                        values.put(GlobalDownload.COLUMN_CURRENT_BYTES, bytesSoFar);
                        mContext.getContentResolver().update(contentUri, values, null, null);
                        if (!mInfo.mNoIntegrity && headerETag == null) {
                            //#debug
                            base.tina.core.log.LogPrinter.d(Constants.TAG,
                                    "download IOException for download " + mInfo.mId + " : " + ex);
                            finalStatus = GlobalDownload.STATUS_PRECONDITION_FAILED;
                        } else if (!Helpers.isNetworkAvailable(mContext)) {
                            finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED;
                        } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) {
                            finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED;
                            countRetry = true;
                        } else {
                            //#debug
                            base.tina.core.log.LogPrinter.d(Constants.TAG,
                                    "download IOException for download " + mInfo.mId + " : " + ex);
                            finalStatus = GlobalDownload.STATUS_HTTP_DATA_ERROR;
                        }
                        request.abort();
                        break http_request_loop;
                    }
                    if (bytesRead == -1) { // success
                        ContentValues values = new ContentValues();
                        values.put(GlobalDownload.COLUMN_CURRENT_BYTES, bytesSoFar);
                        if (headerContentLength == null) {
                            values.put(GlobalDownload.COLUMN_TOTAL_BYTES, bytesSoFar);
                        }
                        mContext.getContentResolver().update(contentUri, values, null, null);
                        if ((headerContentLength != null)
                                && (bytesSoFar != Integer.parseInt(headerContentLength))) {
                            if (!mInfo.mNoIntegrity && headerETag == null) {
                                //#debug
                                base.tina.core.log.LogPrinter.d(Constants.TAG,
                                        "mismatched content length for " + mInfo.mId);

                                finalStatus = GlobalDownload.STATUS_LENGTH_REQUIRED;
                            } else if (!Helpers.isNetworkAvailable(mContext)) {
                                finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED;
                            } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) {
                                finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED;
                                countRetry = true;
                            } else {
                                //#debug
                                base.tina.core.log.LogPrinter.d(Constants.TAG,
                                        "closed socket for download " + mInfo.mId);

                                finalStatus = GlobalDownload.STATUS_HTTP_DATA_ERROR;
                            }
                            break http_request_loop;
                        }
                        break;
                    }
                    gotData = true;
                    for (;;) {
                        try {
                            if (stream == null) {
                                stream = new FileOutputStream(filename, true);
                            }
                            stream.write(data, 0, bytesRead);
                            break;
                        } catch (IOException ex) {
                            finalStatus = GlobalDownload.STATUS_FILE_ERROR;
                            break http_request_loop;
                        }
                    }
                    bytesSoFar += bytesRead;
                    long now = System.currentTimeMillis();
                    if (bytesSoFar - bytesNotified > Constants.MIN_PROGRESS_STEP
                            && now - timeLastNotification > Constants.MIN_PROGRESS_TIME) {
                        ContentValues values = new ContentValues();
                        values.put(GlobalDownload.COLUMN_CURRENT_BYTES, bytesSoFar);
                        mContext.getContentResolver().update(contentUri, values, null, null);
                        bytesNotified = bytesSoFar;
                        timeLastNotification = now;
                    }

                    //#debug verbose
                    base.tina.core.log.LogPrinter.v(Constants.TAG,
                            "downloaded " + bytesSoFar + " for " + mInfo.mUri);

                    synchronized (mInfo) {
                        if (mInfo.mControl == GlobalDownload.CONTROL_PAUSED) {
                            //#debug verbose
                            base.tina.core.log.LogPrinter.v(Constants.TAG, "paused " + mInfo.mUri);

                            finalStatus = GlobalDownload.STATUS_RUNNING_PAUSED;
                            request.abort();
                            break http_request_loop;
                        }
                    }
                    if (mInfo.mStatus == GlobalDownload.STATUS_CANCELED) {
                        //#debug
                        base.tina.core.log.LogPrinter.d(Constants.TAG, "canceled id " + mInfo.mId);

                        finalStatus = GlobalDownload.STATUS_CANCELED;
                        break http_request_loop;
                    }
                }
                //#debug verbose
                base.tina.core.log.LogPrinter.v(Constants.TAG, "download completed for " + mInfo.mUri);

                finalStatus = GlobalDownload.STATUS_SUCCESS;
            }
            break;
        }
    } catch (FileNotFoundException ex) {
        //#debug
        base.tina.core.log.LogPrinter.d(Constants.TAG, "FileNotFoundException for " + filename + " : " + ex);

        finalStatus = GlobalDownload.STATUS_FILE_ERROR;
        // falls through to the code that reports an error
    } catch (RuntimeException ex) {
        //sometimes the socket code throws unchecked exceptions
        //#debug
        base.tina.core.log.LogPrinter.d(Constants.TAG, "Exception for id " + mInfo.mId, ex);

        finalStatus = GlobalDownload.STATUS_UNKNOWN_ERROR;
        // falls through to the code that reports an error
    } finally {
        mInfo.mHasActiveThread = false;
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        if (client != null) {
            client.getConnectionManager().shutdown();//???
            client = null;
        }
        try {
            // close the file
            if (stream != null) {
                stream.close();
            }
        } catch (IOException ex) {
            //#debug verbose
            base.tina.core.log.LogPrinter.v(Constants.TAG,
                    "exception when closing the file after download : " + ex);

            // nothing can really be done if the file can't be closed
        }
        if (filename != null) {
            // if the download wasn't successful, delete the file
            if (GlobalDownload.isStatusError(finalStatus)) {
                new File(filename).delete();
                filename = null;
            } else if (GlobalDownload.isStatusSuccess(finalStatus)) {
                // make sure the file is readable
                //                    FileUtils.setPermissions(filename, 0644, -1, -1);//

                // Sync to storage after completion
                try {
                    new FileOutputStream(filename, true).getFD().sync();
                } catch (FileNotFoundException ex) {
                    //#debug warn
                    base.tina.core.log.LogPrinter.w(Constants.TAG, "file " + filename + " not found: " + ex);
                } catch (SyncFailedException ex) {
                    //#debug warn
                    base.tina.core.log.LogPrinter.w(Constants.TAG, "file " + filename + " sync failed: " + ex);
                } catch (IOException ex) {
                    //#debug warn
                    base.tina.core.log.LogPrinter.w(Constants.TAG,
                            "IOException trying to sync " + filename + ": " + ex);
                } catch (RuntimeException ex) {
                    //#debug warn
                    base.tina.core.log.LogPrinter.w(Constants.TAG, "exception while syncing file: ", ex);
                }
            }
        }
        notifyDownloadCompleted(finalStatus, countRetry, retryAfter, redirectCount, gotData, filename, newUri,
                mimeType);
    }
}

From source file:org.dvbviewer.controller.service.SyncService.java

@Override
public void onCreate() {
    Log.i(SyncService.class.getSimpleName(), "onCreate");
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    DVBViewerPreferences dvbPrefs = new DVBViewerPreferences(getApplication());
    prefs = dvbPrefs.getPrefs();/*from ww w  . j  a v a 2  s  . c o  m*/
    HandlerThread thread = new HandlerThread(SyncService.class.getName(), Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
}

From source file:org.devtcg.five.util.streaming.LocalHttpServer.java

public void run() {
    if (mReqHandler == null)
        throw new IllegalStateException("Request handler not set.");

    if (mSocket == null)
        throw new IllegalStateException("Not bound.");

    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    while (Thread.interrupted() == false) {
        try {//ww w  .  j  a v a2  s.  c om
            Socket sock = mSocket.accept();
            DefaultHttpServerConnection conn = new DefaultHttpServerConnection();

            conn.bind(sock, mParams);

            BasicHttpProcessor proc = new BasicHttpProcessor();
            proc.addInterceptor(new ResponseContent());
            proc.addInterceptor(new ResponseConnControl());

            HttpRequestHandlerRegistry reg = new HttpRequestHandlerRegistry();
            reg.register("*", mReqHandler);

            HttpService svc = new HttpService(proc, new DefaultConnectionReuseStrategy(),
                    new DefaultHttpResponseFactory());

            svc.setParams(mParams);
            svc.setHandlerResolver(reg);

            WorkerThread t;

            synchronized (mWorkers) {
                t = new WorkerThread(svc, conn);
                mWorkers.add(t);
            }

            t.setDaemon(true);
            t.start();
        } catch (IOException e) {
            Log.e(TAG, "I/O error initializing connection thread: " + e.getMessage());
            break;
        }
    }
}

From source file:org.aschyiel.nextboat.Downloader.java

/**
  * @override Thread#run//from  ww  w  . j  a v  a  2  s  . com
  */
  public void run() {
      Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
      while (!_isStopped) {
          try {
              _download();
              Thread.sleep(1000);
              _isStopped = true;
          } catch (InterruptedException e) {
              // Ignore
          }
      }
  }

From source file:de.schildbach.wallet.ui.send.MaintenanceDialogFragment.java

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

    backgroundThread = new HandlerThread("backgroundThread", Process.THREAD_PRIORITY_BACKGROUND);
    backgroundThread.start();//from w  w  w. ja  v  a  2 s. c o  m
    backgroundHandler = new Handler(backgroundThread.getLooper());
}

From source file:com.fillerino.wallet.ui.ScanActivity.java

@Override
protected void onResume() {
    super.onResume();

    cameraThread = new HandlerThread("cameraThread", Process.THREAD_PRIORITY_BACKGROUND);
    cameraThread.start();/*from  w  w  w.j  av a  2 s.  c  om*/
    cameraHandler = new Handler(cameraThread.getLooper());

    final SurfaceView surfaceView = (SurfaceView) findViewById(com.fillerino.wallet.R.id.scan_activity_preview);
    surfaceHolder = surfaceView.getHolder();
    surfaceHolder.addCallback(this);
    surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    if (!hasCameraPermission()) {
        askCameraPermission();
    } else {
        openCamera();
    }

}

From source file:com.coinomi.wallet.ui.ScanActivity.java

@Override
protected void onResume() {
    super.onResume();

    cameraThread = new HandlerThread("cameraThread", Process.THREAD_PRIORITY_BACKGROUND);
    cameraThread.start();/*from  w  w w  . ja va  2 s  .  c o m*/
    cameraHandler = new Handler(cameraThread.getLooper());

    final SurfaceView surfaceView = (SurfaceView) findViewById(R.id.scan_activity_preview);
    surfaceHolder = surfaceView.getHolder();
    surfaceHolder.addCallback(this);
    surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    if (!hasCameraPermission()) {
        askCameraPermission();
    } else {
        openCamera();
    }

}

From source file:net.xisberto.phonetodesktop.GoogleTasksActivity.java

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

    // Configure a background thread
    HandlerThread thread = new HandlerThread("PhoneToDesktopThread", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();//from www  . ja v a  2s.  com
    looper = thread.getLooper();
    handler = new Handler(looper);

    // Configure app's preferences
    settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    accountManager = new GoogleAccountManager(getApplicationContext());

    // Configure GoogleCredential. loadAuthToken can return null
    credential = new GoogleCredential();
    log("Current saved token: " + loadAuthToken());

    // Configure and build the Tasks object
    tasksService = new Tasks.Builder(transport, jsonFactory, credential).setApplicationName("PhoneToDesktop")
            .setJsonHttpRequestInitializer(new GoogleKeyInitializer(my_credentials.getAPIKey())).build();

    if (getIntent().getAction().equals(ACTION_AUTHENTICATE)) {
        broadcastUpdatingStatus(ACTION_AUTHENTICATE, true);
        authorize();
    } else if (getIntent().getAction().equals(Intent.ACTION_SEND)) {
        addTask(loadWhatToSend(), getIntent().getStringExtra(Intent.EXTRA_TEXT));
    } else if (getIntent().getAction().equals(ACTION_LIST_TASKS)) {
        broadcastUpdatingStatus(ACTION_LIST_TASKS, true);
        getTaskList();
    } else if (getIntent().getAction().equals(ACTION_REMOVE_TASKS)) {
        removeTask(getIntent().getStringExtra("task_id"));
    }

}

From source file:de.schildbach.wallet.ui.ScanActivity.java

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

    vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

    setContentView(R.layout.scan_activity);
    scannerView = (ScannerView) findViewById(R.id.scan_activity_mask);
    previewView = (TextureView) findViewById(R.id.scan_activity_preview);
    previewView.setSurfaceTextureListener(this);

    cameraThread = new HandlerThread("cameraThread", Process.THREAD_PRIORITY_BACKGROUND);
    cameraThread.start();/*from w w  w .  ja  v  a  2  s .  c o m*/
    cameraHandler = new Handler(cameraThread.getLooper());

    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA }, 0);
}