Example usage for android.os PowerManager PARTIAL_WAKE_LOCK

List of usage examples for android.os PowerManager PARTIAL_WAKE_LOCK

Introduction

In this page you can find the example usage for android.os PowerManager PARTIAL_WAKE_LOCK.

Prototype

int PARTIAL_WAKE_LOCK

To view the source code for android.os PowerManager PARTIAL_WAKE_LOCK.

Click Source Link

Document

Wake lock level: Ensures that the CPU is running; the screen and keyboard backlight will be allowed to go off.

Usage

From source file:com.ecoplayer.beta.MusicService.java

private boolean initMediaPlayer() {
    startForeground(NOTIFICATION_ID, notiBuilder.getNotification());
    AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
    int result = audioManager.requestAudioFocus(audioFocusChangeList, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);
    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        mMediaPlayer = new MediaPlayer(); // initialize it here
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnCompletionListener(onCompletion);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        // prevent CPU from going to sleep
        mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        return true;
    } else {//from   w  w  w . j  a v a2s. c om
        Log.w(LOG_TAG, "The service hasn't got the audio focus");
    }
    return false;
}

From source file:com.android.camera.processing.ProcessingService.java

@Override
public void onCreate() {
    mProcessingServiceManager = ProcessingServiceManager.instance();
    mSessionManager = getServices().getCaptureSessionManager();

    // Keep CPU awake while allowing screen and keyboard to switch off.
    PowerManager powerManager = AndroidServices.instance().providePowerManager();
    mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG.toString());
    mWakeLock.acquire();//from w  ww.j a v a2s  . c  o m

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ACTION_PAUSE_PROCESSING_SERVICE);
    intentFilter.addAction(ACTION_RESUME_PROCESSING_SERVICE);
    LocalBroadcastManager.getInstance(this).registerReceiver(mServiceController, intentFilter);
    mNotificationBuilder = createInProgressNotificationBuilder();
    mNotificationManager = AndroidServices.instance().provideNotificationManager();
}

From source file:com.mylovemhz.simplay.MusicService.java

private void initialize() {
    trackQueue = new ArrayList<>();

    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setOnPreparedListener(this);
    mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
    wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL,
            "music lock");

    ComponentName receiver = new ComponentName(getPackageName(), MediaButtonEventReceiver.class.getName());
    mediaSession = new MediaSessionCompat(this, TAG_MUSIC_SERVICE, receiver, null);
    mediaSession.setFlags(/*  w  ww  .  jav a2  s .  c om*/
            MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mediaSession.setCallback(new SimpleSessionCallback(this));

    currentState = State.IDLE;
    mediaSession.setActive(true);

    isInitialized = true;
    Log.d(TAG_MUSIC_SERVICE, "Initialized...");
}

From source file:net.impjq.providers.downloads.DownloadThread.java

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

    int finalStatus = Downloads.Impl.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;
    AndroidHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    Uri contentUri = Uri.parse(Downloads.Impl.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 = Downloads.Impl.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
                    if (Config.LOGD) {
                        Log.d(Constants.TAG, "can't resume interrupted non-resumable download");
                    }
                    f.delete();
                    finalStatus = Downloads.Impl.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 = AndroidHttpClient.newInstance(userAgent(), mContext);

        if (stream != null && mInfo.mDestination == Downloads.Impl.DESTINATION_EXTERNAL) {
            try {
                stream.close();
                stream = null;
            } catch (IOException ex) {
                if (Constants.LOGV) {
                    Log.v(Constants.TAG, "exception when closing the file before download : " + ex);
                }
                // nothing can really be done if the file can't be closed
            }
        }

        /*
         * 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) {
            // Set or unset proxy, which may have changed since last GET request.
            // setDefaultProxy() supports null as proxy parameter.
            //Comment it,pjq,20110220,start
            //ConnRouteParams.setDefaultProxy(client.getParams(),
            //         Proxy.getPreferredHttpHost(mContext, mInfo.mUri));
            // Prepares the request and fires it.
            HttpGet request = new HttpGet(mInfo.mUri);

            if (Constants.LOGV) {
                Log.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) {
                if (Constants.LOGV) {
                    Log.d(Constants.TAG,
                            "Arg exception trying to execute request for " + mInfo.mUri + " : " + ex);
                } else if (Config.LOGD) {
                    Log.d(Constants.TAG,
                            "Arg exception trying to execute request for " + mInfo.mId + " : " + ex);
                }
                finalStatus = Downloads.Impl.STATUS_BAD_REQUEST;
                request.abort();
                break http_request_loop;
            } catch (IOException ex) {
                ex.printStackTrace();
                if (Constants.LOGX) {
                    if (Helpers.isNetworkAvailable(mContext)) {
                        Log.i(Constants.TAG, "Execute Failed " + mInfo.mId + ", Net Up");
                    } else {
                        Log.i(Constants.TAG, "Execute Failed " + mInfo.mId + ", Net Down");
                    }
                }
                if (!Helpers.isNetworkAvailable(mContext)) {
                    finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) {
                    finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                    countRetry = true;
                } else {
                    if (Constants.LOGV) {
                        Log.d(Constants.TAG,
                                "IOException trying to execute request for " + mInfo.mUri + " : " + ex);
                    } else if (Config.LOGD) {
                        Log.d(Constants.TAG,
                                "IOException trying to execute request for " + mInfo.mId + " : " + ex);
                    }
                    finalStatus = Downloads.Impl.STATUS_HTTP_DATA_ERROR;
                }
                request.abort();
                break http_request_loop;
            }

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 503 && mInfo.mNumFailed < Constants.MAX_RETRIES) {
                if (Constants.LOGVV) {
                    Log.v(Constants.TAG, "got HTTP response code 503");
                }
                finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                countRetry = true;
                Header header = response.getFirstHeader("Retry-After");
                if (header != null) {
                    try {
                        if (Constants.LOGVV) {
                            Log.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) {
                if (Constants.LOGVV) {
                    Log.v(Constants.TAG, "got HTTP redirect " + statusCode);
                }
                if (redirectCount >= Constants.MAX_REDIRECTS) {
                    if (Constants.LOGV) {
                        Log.d(Constants.TAG,
                                "too many redirects for download " + mInfo.mId + " at " + mInfo.mUri);
                    } else if (Config.LOGD) {
                        Log.d(Constants.TAG, "too many redirects for download " + mInfo.mId);
                    }
                    finalStatus = Downloads.Impl.STATUS_TOO_MANY_REDIRECTS;
                    request.abort();
                    break http_request_loop;
                }
                Header header = response.getFirstHeader("Location");
                if (header != null) {
                    if (Constants.LOGVV) {
                        Log.v(Constants.TAG, "Location :" + header.getValue());
                    }
                    try {
                        newUri = new URI(mInfo.mUri).resolve(new URI(header.getValue())).toString();
                    } catch (URISyntaxException ex) {
                        if (Constants.LOGV) {
                            Log.d(Constants.TAG, "Couldn't resolve redirect URI " + header.getValue() + " for "
                                    + mInfo.mUri);
                        } else if (Config.LOGD) {
                            Log.d(Constants.TAG, "Couldn't resolve redirect URI for download " + mInfo.mId);
                        }
                        finalStatus = Downloads.Impl.STATUS_BAD_REQUEST;
                        request.abort();
                        break http_request_loop;
                    }
                    ++redirectCount;
                    finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                    request.abort();
                    break http_request_loop;
                }
            }
            if ((!continuingDownload && statusCode != Downloads.Impl.STATUS_SUCCESS)
                    || (continuingDownload && statusCode != 206)) {
                if (Constants.LOGV) {
                    Log.d(Constants.TAG, "http error " + statusCode + " for " + mInfo.mUri);
                } else if (Config.LOGD) {
                    Log.d(Constants.TAG, "http error " + statusCode + " for download " + mInfo.mId);
                }
                if (Downloads.Impl.isStatusError(statusCode)) {
                    finalStatus = statusCode;
                } else if (statusCode >= 300 && statusCode < 400) {
                    finalStatus = Downloads.Impl.STATUS_UNHANDLED_REDIRECT;
                } else if (continuingDownload && statusCode == Downloads.Impl.STATUS_SUCCESS) {
                    finalStatus = Downloads.Impl.STATUS_PRECONDITION_FAILED;
                } else {
                    finalStatus = Downloads.Impl.STATUS_UNHANDLED_HTTP_CODE;
                }
                request.abort();
                break http_request_loop;
            } else {
                // Handles the response, saves the file
                if (Constants.LOGV) {
                    Log.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
                        if (Constants.LOGVV) {
                            Log.v(Constants.TAG, "ignoring content-length because of xfer-encoding");
                        }
                    }
                    if (Constants.LOGVV) {
                        Log.v(Constants.TAG, "Accept-Ranges: " + headerAcceptRanges);
                        Log.v(Constants.TAG, "Content-Disposition: " + headerContentDisposition);
                        Log.v(Constants.TAG, "Content-Length: " + headerContentLength);
                        Log.v(Constants.TAG, "Content-Location: " + headerContentLocation);
                        Log.v(Constants.TAG, "Content-Type: " + mimeType);
                        Log.v(Constants.TAG, "ETag: " + headerETag);
                        Log.v(Constants.TAG, "Transfer-Encoding: " + headerTransferEncoding);
                    }

                    if (!mInfo.mNoIntegrity && headerContentLength == null && (headerTransferEncoding == null
                            || !headerTransferEncoding.equalsIgnoreCase("chunked"))) {
                        if (Config.LOGD) {
                            Log.d(Constants.TAG, "can't know size of download, giving up");
                        }
                        finalStatus = Downloads.Impl.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;
                    if (Constants.LOGV) {
                        Log.v(Constants.TAG, "writing " + mInfo.mUri + " to " + filename);
                    }

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

                InputStream entityStream;
                try {
                    entityStream = response.getEntity().getContent();
                } catch (IOException ex) {
                    if (Constants.LOGX) {
                        if (Helpers.isNetworkAvailable(mContext)) {
                            Log.i(Constants.TAG, "Get Failed " + mInfo.mId + ", Net Up");
                        } else {
                            Log.i(Constants.TAG, "Get Failed " + mInfo.mId + ", Net Down");
                        }
                    }
                    if (!Helpers.isNetworkAvailable(mContext)) {
                        finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                    } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) {
                        finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                        countRetry = true;
                    } else {
                        if (Constants.LOGV) {
                            Log.d(Constants.TAG, "IOException getting entity for " + mInfo.mUri + " : " + ex);
                        } else if (Config.LOGD) {
                            Log.d(Constants.TAG,
                                    "IOException getting entity for download " + mInfo.mId + " : " + ex);
                        }
                        finalStatus = Downloads.Impl.STATUS_HTTP_DATA_ERROR;
                    }
                    request.abort();
                    break http_request_loop;
                }
                for (;;) {
                    int bytesRead;
                    try {
                        bytesRead = entityStream.read(data);
                    } catch (IOException ex) {
                        if (Constants.LOGX) {
                            if (Helpers.isNetworkAvailable(mContext)) {
                                Log.i(Constants.TAG, "Read Failed " + mInfo.mId + ", Net Up");
                            } else {
                                Log.i(Constants.TAG, "Read Failed " + mInfo.mId + ", Net Down");
                            }
                        }
                        ContentValues values = new ContentValues();
                        values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, bytesSoFar);
                        mContext.getContentResolver().update(contentUri, values, null, null);
                        if (!mInfo.mNoIntegrity && headerETag == null) {
                            if (Constants.LOGV) {
                                Log.v(Constants.TAG, "download IOException for " + mInfo.mUri + " : " + ex);
                            } else if (Config.LOGD) {
                                Log.d(Constants.TAG,
                                        "download IOException for download " + mInfo.mId + " : " + ex);
                            }
                            if (Config.LOGD) {
                                Log.d(Constants.TAG, "can't resume interrupted download with no ETag");
                            }
                            finalStatus = Downloads.Impl.STATUS_PRECONDITION_FAILED;
                        } else if (!Helpers.isNetworkAvailable(mContext)) {
                            finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                        } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) {
                            finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                            countRetry = true;
                        } else {
                            if (Constants.LOGV) {
                                Log.v(Constants.TAG, "download IOException for " + mInfo.mUri + " : " + ex);
                            } else if (Config.LOGD) {
                                Log.d(Constants.TAG,
                                        "download IOException for download " + mInfo.mId + " : " + ex);
                            }
                            finalStatus = Downloads.Impl.STATUS_HTTP_DATA_ERROR;
                        }
                        request.abort();
                        break http_request_loop;
                    }
                    if (bytesRead == -1) { // success
                        ContentValues values = new ContentValues();
                        values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, bytesSoFar);
                        if (headerContentLength == null) {
                            values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, bytesSoFar);
                        }
                        mContext.getContentResolver().update(contentUri, values, null, null);
                        if ((headerContentLength != null)
                                && (bytesSoFar != Integer.parseInt(headerContentLength))) {
                            if (!mInfo.mNoIntegrity && headerETag == null) {
                                if (Constants.LOGV) {
                                    Log.d(Constants.TAG, "mismatched content length " + mInfo.mUri);
                                } else if (Config.LOGD) {
                                    Log.d(Constants.TAG, "mismatched content length for " + mInfo.mId);
                                }
                                finalStatus = Downloads.Impl.STATUS_LENGTH_REQUIRED;
                            } else if (!Helpers.isNetworkAvailable(mContext)) {
                                finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                            } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) {
                                finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                                countRetry = true;
                            } else {
                                if (Constants.LOGV) {
                                    Log.v(Constants.TAG, "closed socket for " + mInfo.mUri);
                                } else if (Config.LOGD) {
                                    Log.d(Constants.TAG, "closed socket for download " + mInfo.mId);
                                }
                                finalStatus = Downloads.Impl.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);
                            if (mInfo.mDestination == Downloads.Impl.DESTINATION_EXTERNAL) {
                                try {
                                    stream.close();
                                    stream = null;
                                } catch (IOException ex) {
                                    if (Constants.LOGV) {
                                        Log.v(Constants.TAG,
                                                "exception when closing the file " + "during download : " + ex);
                                    }
                                    // nothing can really be done if the file can't be closed
                                }
                            }
                            break;
                        } catch (IOException ex) {
                            if (!Helpers.discardPurgeableFiles(mContext, Constants.BUFFER_SIZE)) {
                                finalStatus = Downloads.Impl.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(Downloads.Impl.COLUMN_CURRENT_BYTES, bytesSoFar);
                        mContext.getContentResolver().update(contentUri, values, null, null);
                        bytesNotified = bytesSoFar;
                        timeLastNotification = now;
                    }

                    if (Constants.LOGVV) {
                        Log.v(Constants.TAG, "downloaded " + bytesSoFar + " for " + mInfo.mUri);
                    }
                    synchronized (mInfo) {
                        if (mInfo.mControl == Downloads.Impl.CONTROL_PAUSED) {
                            if (Constants.LOGV) {
                                Log.v(Constants.TAG, "paused " + mInfo.mUri);
                            }
                            finalStatus = Downloads.Impl.STATUS_RUNNING_PAUSED;
                            request.abort();
                            break http_request_loop;
                        }
                    }
                    if (mInfo.mStatus == Downloads.Impl.STATUS_CANCELED) {
                        if (Constants.LOGV) {
                            Log.d(Constants.TAG, "canceled " + mInfo.mUri);
                        } else if (Config.LOGD) {
                            // Log.d(Constants.TAG, "canceled id " + mInfo.mId);
                        }
                        finalStatus = Downloads.Impl.STATUS_CANCELED;
                        break http_request_loop;
                    }
                }
                if (Constants.LOGV) {
                    Log.v(Constants.TAG, "download completed for " + mInfo.mUri);
                }
                finalStatus = Downloads.Impl.STATUS_SUCCESS;
            }
            break;
        }
    } catch (FileNotFoundException ex) {
        if (Config.LOGD) {
            Log.d(Constants.TAG, "FileNotFoundException for " + filename + " : " + ex);
        }
        finalStatus = Downloads.Impl.STATUS_FILE_ERROR;
        // falls through to the code that reports an error
    } catch (RuntimeException ex) { //sometimes the socket code throws unchecked exceptions
        if (Constants.LOGV) {
            Log.d(Constants.TAG, "Exception for " + mInfo.mUri, ex);
        } else if (Config.LOGD) {
            Log.d(Constants.TAG, "Exception for id " + mInfo.mId, ex);
        }
        finalStatus = Downloads.Impl.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.close();
            client = null;
        }
        try {
            // close the file
            if (stream != null) {
                stream.close();
            }
        } catch (IOException ex) {
            if (Constants.LOGV) {
                Log.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 (Downloads.Impl.isStatusError(finalStatus)) {
                new File(filename).delete();
                filename = null;
            } else if (Downloads.Impl.isStatusSuccess(finalStatus)) {
                //Comment it,pjq,20110220,start
                // transfer the file to the DRM content provider 
                // File file = new File(filename);
                // Intent item =
                // DrmStore.addDrmFile(mContext.getContentResolver(), file,
                // null);
                // if (item == null) {
                // Log.w(Constants.TAG, "unable to add file " + filename +
                // " to DrmProvider");
                // finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;
                // } else {
                // filename = item.getDataString();
                // mimeType = item.getType();
                // }
                //                    
                // file.delete();
            } else if (Downloads.Impl.isStatusSuccess(finalStatus)) {
                // make sure the file is readable
                //Comment it,pjq,20110220,start
                //FileUtils.setPermissions(filename, 0644, -1, -1);

                // Sync to storage after completion
                FileOutputStream downloadedFileStream = null;
                try {
                    downloadedFileStream = new FileOutputStream(filename, true);
                    downloadedFileStream.getFD().sync();
                } catch (FileNotFoundException ex) {
                    Log.w(Constants.TAG, "file " + filename + " not found: " + ex);
                } catch (SyncFailedException ex) {
                    Log.w(Constants.TAG, "file " + filename + " sync failed: " + ex);
                } catch (IOException ex) {
                    Log.w(Constants.TAG, "IOException trying to sync " + filename + ": " + ex);
                } catch (RuntimeException ex) {
                    Log.w(Constants.TAG, "exception while syncing file: ", ex);
                } finally {
                    if (downloadedFileStream != null) {
                        try {
                            downloadedFileStream.close();
                        } catch (IOException ex) {
                            Log.w(Constants.TAG, "IOException while closing synced file: ", ex);
                        } catch (RuntimeException ex) {
                            Log.w(Constants.TAG, "exception while closing file: ", ex);
                        }
                    }
                }
            }
        }
        notifyDownloadCompleted(finalStatus, countRetry, retryAfter, redirectCount, gotData, filename, newUri,
                mimeType);
    }
}

From source file:com.allthingsgeek.celljoust.MainActivity.java

/** Called when the activity is first created. */
@Override//from  w w w .ja  v a 2  s . c  om
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ServoOn");
    // wl.acquire();
    // wl.release();

    wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();

    noise = PulseGenerator.getInstance();
    mover = Movement.getInstance();

    loadPrefs();

    mTorchMode = false;

    out = new ByteArrayOutputStream();

    setContentView(R.layout.main);

    if (sensorManager == null) {
        sensorManager = (SensorManager) this.getSystemService(Context.SENSOR_SERVICE);
    }

    startListening();

    mPreview = (SurfaceView) findViewById(R.id.preview);
    mHolder = mPreview.getHolder();
    mHolder.addCallback(this);
    mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    noise.pause();

}

From source file:com.example.android.camera2video.CameraActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera);
    if (null == savedInstanceState) {
        getFragmentManager().beginTransaction().replace(R.id.container, Camera2VideoFragment.newInstance())
                .commit();//from   www . jav  a2s  .c  o  m
    }

    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                TAG_PERMISSION_FINE_LOCATION);
    } else {
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0f, this);
    }

    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

    mAccSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mSensorManager.registerListener(this, mAccSensor, SensorManager.SENSOR_DELAY_GAME);
    //        mGraSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
    //        mSensorManager.registerListener(this, mGraSensor, SensorManager.SENSOR_DELAY_GAME);
    //        mLinSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
    //        mSensorManager.registerListener(this, mLinSensor, SensorManager.SENSOR_DELAY_GAME);
    //        mGyrSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
    //        mSensorManager.registerListener(this, mGyrSensor, SensorManager.SENSOR_DELAY_GAME);
    mUgySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE_UNCALIBRATED);
    mSensorManager.registerListener(this, mUgySensor, SensorManager.SENSOR_DELAY_GAME);
    //        mMagSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    //        mSensorManager.registerListener(this, mMagSensor, SensorManager.SENSOR_DELAY_GAME);

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
    mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
    mWakeLock.acquire();
}

From source file:com.lithiumli.fiction.PlaybackService.java

public void onPrepared(MediaPlayer player) {
    if (mMediaPlayer == null) {
        mMediaPlayer = player;//from  w ww .  j  ava 2  s  .  com
    } else {
        mMediaPlayer.setNextMediaPlayer(player);
        if (mMediaPlayer.isPlaying()) {
            Log.d("fiction", "Was playing");
            mMediaPlayer.stop();
        }
        Log.d("fiction", "Starting music");
        mMediaPlayer.release();
        mMediaPlayer = null;
        mMediaPlayer = player;
    }

    if (acquireAudioFocus()) {
        player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        player.start();
        prepareNext();

        mPaused = false;

        showNotification();
    }
}

From source file:de.ub0r.android.smsdroid.SmsReceiver.java

static void handleOnReceive(final BroadcastReceiver receiver, final Context context, final Intent intent) {
    final String action = intent.getAction();
    Log.d(TAG, "onReceive(context, ", action, ")");
    final PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    final PowerManager.WakeLock wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    wakelock.acquire();/*from   w  w w . j a  va2s  .  c  o  m*/
    Log.i(TAG, "got wakelock");
    Log.d(TAG, "got intent: ", action);
    try {
        Log.d(TAG, "sleep(", SLEEP, ")");
        Thread.sleep(SLEEP);
    } catch (InterruptedException e) {
        Log.d(TAG, "interrupted in spinlock", e);
        e.printStackTrace();
    }
    String text;
    if (SenderActivity.MESSAGE_SENT_ACTION.equals(action)) {
        handleSent(context, intent, receiver.getResultCode());
    } else {
        boolean silent = false;

        if (shouldHandleSmsAction(context, action)) {
            Bundle b = intent.getExtras();
            assert b != null;
            Object[] messages = (Object[]) b.get("pdus");
            SmsMessage[] smsMessage = new SmsMessage[messages.length];
            int l = messages.length;
            for (int i = 0; i < l; i++) {
                smsMessage[i] = SmsMessage.createFromPdu((byte[]) messages[i]);
            }
            text = null;
            if (l > 0) {
                // concatenate multipart SMS body
                StringBuilder sbt = new StringBuilder();
                for (int i = 0; i < l; i++) {
                    sbt.append(smsMessage[i].getMessageBody());
                }
                text = sbt.toString();

                // ! Check in blacklist db - filter spam
                String s = smsMessage[0].getDisplayOriginatingAddress();

                // this code is used to strip a forwarding agent and display the orginated number as sender
                final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
                if (prefs.getBoolean(PreferencesActivity.PREFS_FORWARD_SMS_CLEAN, false)
                        && text.contains(":")) {
                    Pattern smsPattern = Pattern.compile("([0-9a-zA-Z+]+):");
                    Matcher m = smsPattern.matcher(text);
                    if (m.find()) {
                        s = m.group(1);
                        Log.d(TAG, "found forwarding sms number: (", s, ")");
                        // now strip the sender from the message
                        Pattern textPattern = Pattern.compile("^[0-9a-zA-Z+]+: (.*)");
                        Matcher m2 = textPattern.matcher(text);
                        if (text.contains(":") && m2.find()) {
                            text = m2.group(1);
                            Log.d(TAG, "stripped the message");
                        }
                    }
                }

                final SpamDB db = new SpamDB(context);
                db.open();
                if (db.isInDB(smsMessage[0].getOriginatingAddress())) {
                    Log.d(TAG, "Message from ", s, " filtered.");
                    silent = true;
                } else {
                    Log.d(TAG, "Message from ", s, " NOT filtered.");
                }
                db.close();

                if (action.equals(ACTION_SMS_NEW)) {
                    // API19+: save message to the database
                    ContentValues values = new ContentValues();
                    values.put("address", s);
                    values.put("body", text);
                    context.getContentResolver().insert(Uri.parse("content://sms/inbox"), values);
                    Log.d(TAG, "Insert SMS into database: ", s, ", ", text);
                }
            }
            updateNotificationsWithNewText(context, text, silent);
        } else if (ACTION_MMS_OLD.equals(action) || ACTION_MMS_MEW.equals(action)) {
            text = MMS_BODY;
            // TODO API19+ MMS code
            updateNotificationsWithNewText(context, text, silent);
        }
    }
    wakelock.release();
    Log.i(TAG, "wakelock released");
}

From source file:org.secu3.android.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    setTheme(PreferenceManager.getDefaultSharedPreferences(this)
            .getBoolean(getString(R.string.pref_night_mode_key), false) ? R.style.AppBaseTheme
                    : R.style.AppBaseTheme_Light);
    setContentView(R.layout.activity_main);

    packetUtils = new PacketUtils(this);

    sensorsFormat = getString(R.string.sensors_format);
    speedFormat = getString(R.string.speed_format);
    sensorsRawFormat = getString(R.string.sensors_raw_format);
    textViewData = (TextView) findViewById(R.id.textViewData);
    textViewDataExt = (TextView) findViewById(R.id.textViewDataExt);
    textViewStatus = (TextView) findViewById(R.id.mainTextViewStatus);
    textFWInfo = (TextView) findViewById(R.id.mainTextFWInfo);

    receiver = new ReceiveMessages();

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Secu3Droid wakelock");

    if (savedInstanceState != null) {
        textViewData.setText(savedInstanceState.getString(DATA));
        textViewStatus.setText(savedInstanceState.getString(STATUS));
        rawSensors = savedInstanceState.getBoolean(RAW_SENSORS);
    }/*from w  w  w  .ja v a2 s .c om*/

    setRawMode(rawSensors);

    logButtonLayout = (LinearLayout) findViewById(R.id.mainLogButtonLayout);

    View.OnClickListener logButtonListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.mainLogButton1:
                startService(new Intent(Secu3Service.ACTION_SECU3_SERVICE_SET_TASK, Uri.EMPTY, v.getContext(),
                        Secu3Service.class).putExtra(Secu3Service.ACTION_SECU3_SERVICE_SET_TASK_PARAM,
                                SECU3_TASK.SECU3_SET_LOG_MARKER_1.ordinal()));
                break;
            case R.id.mainLogButton2:
                startService(new Intent(Secu3Service.ACTION_SECU3_SERVICE_SET_TASK, Uri.EMPTY, v.getContext(),
                        Secu3Service.class).putExtra(Secu3Service.ACTION_SECU3_SERVICE_SET_TASK_PARAM,
                                SECU3_TASK.SECU3_SET_LOG_MARKER_2.ordinal()));
                break;
            case R.id.mainLogButton3:
                startService(new Intent(Secu3Service.ACTION_SECU3_SERVICE_SET_TASK, Uri.EMPTY, v.getContext(),
                        Secu3Service.class).putExtra(Secu3Service.ACTION_SECU3_SERVICE_SET_TASK_PARAM,
                                SECU3_TASK.SECU3_SET_LOG_MARKER_3.ordinal()));
                break;
            default:
                break;
            }

        }
    };

    Button b = (Button) findViewById(R.id.mainLogButton1);
    b.setOnClickListener(logButtonListener);
    b = (Button) findViewById(R.id.mainLogButton2);
    b.setOnClickListener(logButtonListener);
    b = (Button) findViewById(R.id.mainLogButton3);
    b.setOnClickListener(logButtonListener);

    super.onCreate(savedInstanceState);
}

From source file:org.durka.hallmonitor.CoreStateManager.java

CoreStateManager(Context context) {
    mAppContext = context;//from w  ww .jav  a 2s .com
    mPowerManager = (PowerManager) mAppContext.getSystemService(Context.POWER_SERVICE);
    daPartialWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "CoreStateManager");
    daPartialWakeLock.setReferenceCounted(false);
    globalPartialWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "CoreReceiver");
    globalPartialWakeLock.setReferenceCounted(true);

    preference_all = PreferenceManager.getDefaultSharedPreferences(mAppContext);

    // Enable access to sleep mode
    systemApp = (mAppContext.getApplicationInfo().flags
            & (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
    if (systemApp) {
        Log.d(LOG_TAG, "We are a system app.");
    } else {
        Log.d(LOG_TAG, "We are not a system app.");
        preference_all.edit().putBoolean("pref_internal_power_management", false).commit();
    }

    refreshAdminApp();
    refreshRootApp();

    refreshLockMode();
    refreshOsPowerManagement();
    refreshInternalPowerManagement();

    refreshInternalService();

    if (preference_all.getBoolean("pref_proximity", false)) {
        forceCheckCoverState = true;
    }

    hmAppWidgetManager = new HMAppWidgetManager(this);

    if (preference_all.getBoolean("pref_default_widget", false)) {
        int widgetId = preference_all.getInt("default_widget_id", -1);
        if (widgetId == -1) {
            registerWidget("default");
        } else {
            createWidget("default");
        }
    }

    if (preference_all.getBoolean("pref_media_widget", false)) {
        audioManager = (AudioManager) mAppContext.getSystemService(Context.AUDIO_SERVICE);

        int widgetId = preference_all.getInt("media_widget_id", -1);
        if (widgetId == -1) {
            registerWidget("media");
        } else {
            createWidget("media");
        }
    }

    this.hardwareAccelerated = preference_all.getBoolean("pref_hardwareAccelerated", false);

    // we might have missed a phone-state revelation
    phone_ringing = ((TelephonyManager) mAppContext.getSystemService(Context.TELEPHONY_SERVICE))
            .getCallState() == TelephonyManager.CALL_STATE_RINGING;
    // we might have missed an alarm alert
    // TODO: find a way
    // alarm_firing =
    // ((TelephonyManager)
    // mAppContext.getSystemService(Context.TELEPHONY_SERVICE)).getCallState()
    // == TelephonyManager.CALL_STATE_RINGING;
    Intent stateIntent = mAppContext.registerReceiver(null, new IntentFilter(CoreReceiver.TORCH_STATE_CHANGED));
    torch_on = stateIntent != null && stateIntent.getIntExtra("state", 0) != 0;

    init = true;
}