Example usage for android.os PowerManager newWakeLock

List of usage examples for android.os PowerManager newWakeLock

Introduction

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

Prototype

public WakeLock newWakeLock(int levelAndFlags, String tag) 

Source Link

Document

Creates a new wake lock with the specified level and flags.

Usage

From source file:com.example.administrator.testscreenrecording.control.StreamingCamera2Fragment.java

@Override
public void onResume() {
    super.onResume();
    startBackgroundThread();//  w  w w  . j  av  a 2 s.  c o  m

    // When the screen is turned off and turned back on, the SurfaceTexture is already
    // available, and "onSurfaceTextureAvailable" will not be called. In that case, we can open
    // a camera and start preview from here (otherwise, we wait until the surface is ready in
    // the SurfaceTextureListener).
    if (mTextureView.isAvailable()) {
        openCamera(mTextureView.getWidth(), mTextureView.getHeight());
    } else {
        mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
    }

    if (mWakeLock == null) {
        PowerManager pm = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, LOG_TAG);
        mWakeLock.acquire();
    }
}

From source file:ca.nehil.rter.streamingapp2.StreamingActivity.java

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

    // Orientation listenever implementation
    myOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL) {
        @Override/*from   w  ww .  j  ava  2 s .  co m*/
        public void onOrientationChanged(int orientation) {
            int rotation = getWindowManager().getDefaultDisplay().getRotation();
            if (rotation == Surface.ROTATION_270) {
                flipVideo = true;
            } else {
                flipVideo = false;
            }
        }
    };
    myOrientationEventListener.enable();

    // stopService(new Intent(StreamingActivity.this,
    // BackgroundService.class));

    Log.e(TAG, "onCreate");

    AndroidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
    frameInfo = new FrameInfo();
    // openGL overlay
    overlay = new OverlayController(this);
    // orientation
    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    mAcc = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mMag = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

    //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    setContentView(R.layout.activity_streaming);

    // Find the total number of cameras available
    numberOfCameras = Camera.getNumberOfCameras();

    cookies = getSharedPreferences("RterUserCreds", MODE_PRIVATE);
    prefEditor = cookies.edit();
    setUsername = cookies.getString("Username", "not-set");
    setRterCredentials = cookies.getString("RterCreds", "not-set");
    if (setRterCredentials.equalsIgnoreCase("not-set") || setRterCredentials == null) {
        Log.e("PREFS", "Login Not successful, please restart");
    }
    Log.d("PREFS", "Prefs ==> rter_Creds:" + setRterCredentials);

    // Get the location manager
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    // Define the criteria how to select the location provider -> use
    // default

    if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        Log.e(TAG, "GPS not available");
    }
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, true);
    Log.d(TAG, "Requesting location");
    locationManager.requestLocationUpdates(provider, 0, 1, this);
    // register the overlay control for location updates as well, so we get
    // the geomagnetic field
    locationManager.requestLocationUpdates(provider, 0, 1000, overlay);
    if (provider != null) {
        Location location = locationManager.getLastKnownLocation(provider);
        // Initialize the location fields
        if (location != null) {
            System.out.println("Provider " + provider + " has been selected. and location " + location);
            onLocationChanged(location);
        } else {
            Toast toast = Toast.makeText(this, "Location not available", Toast.LENGTH_LONG);
            toast.setGravity(Gravity.TOP, 0, 0);
            toast.show();
            lati = (float) (45.505958f);
            longi = (float) (-73.576254f);
            Log.d(TAG, "Location not available");
        }
    }

    // power manager
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, CLASS_LABEL);
    mWakeLock.acquire();

    // test, set desired orienation to north
    overlay.letFreeRoam(false);
    overlay.setDesiredOrientation(0.0f);
    // CharSequence text = "Tap to start..";
    // int duration = Toast.LENGTH_SHORT;
    //
    // Toast toast = Toast.makeText(this, text, duration);
    // toast.setGravity(Gravity.TOP|Gravity.RIGHT, 0, 0);
    // toast.show();

}

From source file:im.neon.services.EventStreamService.java

/**
 * Display a permanent notification when there is an incoming call.
 * @param session the session/*from ww w . java  2  s.  co m*/
 * @param room the room
 * @param event the event
 * @param callId the callId
 * @param bingRule the bing rule.
 */
private void displayIncomingCallNotification(MXSession session, Room room, Event event, String callId,
        BingRule bingRule) {
    Log.d(LOG_TAG, "displayIncomingCallNotification : " + callId + " in " + room.getRoomId());

    // the incoming call in progress is already displayed
    if (!TextUtils.isEmpty(mIncomingCallId)) {
        Log.d(LOG_TAG, "displayIncomingCallNotification : the incoming call in progress is already displayed");
    } else if (!TextUtils.isEmpty(mCallIdInProgress)) {
        Log.d(LOG_TAG, "displayIncomingCallNotification : a 'call in progress' notification is displayed");
    }
    // test if there is no active call
    else if (null == VectorCallViewActivity.getActiveCall()) {
        Log.d(LOG_TAG, "displayIncomingCallNotification : display the dedicated notification");

        if ((null != bingRule) && bingRule.isCallRingNotificationSound(bingRule.notificationSound())) {
            VectorCallSoundManager.startRinging();
        }

        Notification notification = NotificationUtils.buildIncomingCallNotification(EventStreamService.this,
                getRoomName(session, room, event), session.getMyUserId(), callId);

        if ((null != bingRule) && bingRule.isDefaultNotificationSound(bingRule.notificationSound())) {
            notification.defaults |= Notification.DEFAULT_SOUND;
        }

        startForeground(NOTIF_ID_FOREGROUND_SERVICE, notification);
        mForegroundServiceIdentifier = FOREGROUND_ID_INCOMING_CALL;

        mIncomingCallId = callId;

        // turn the screen on for 3 seconds
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(
                PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "MXEventListener");
        wl.acquire(3000);
        wl.release();

    } else {
        Log.d(LOG_TAG,
                "displayIncomingCallNotification : do not display the incoming call notification because there is a pending call");
    }
}

From source file:im.neon.services.EventStreamService.java

/**
 * Trigger the latest prepared notification
 * @param checkNotification true to check if the prepared notification still makes sense.
 *///from   w ww.  j  a va 2s  . c  o m
public void triggerPreparedNotification(boolean checkNotification) {
    if (null != mLatestNotification) {
        if (checkNotification) {
            // check first if the message has not been read
            checkNotification();
        }

        // if it is still defined.
        if (null != mLatestNotification) {
            try {
                NotificationManager nm = (NotificationManager) EventStreamService.this
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                nm.cancelAll();
                nm.notify(NOTIF_ID_MESSAGE, mLatestNotification);

                // turn the screen on
                if (mGcmRegistrationManager.isScreenTurnedOn()) {
                    // turn the screen on for 3 seconds
                    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
                    PowerManager.WakeLock wl = pm.newWakeLock(
                            PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
                            "MXEventListener");
                    wl.acquire(3000);
                    wl.release();
                }

            } catch (Exception e) {
                Log.e(LOG_TAG, "onLiveEventsChunkProcessed crashed " + e.getLocalizedMessage());
            }

            mLatestNotification = null;
        }
    }
}

From source file:org.runbuddy.tomahawk.services.PlaybackService.java

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

    EventBus.getDefault().register(this);

    PipeLine.get();/*from   w ww  . java 2s. co  m*/

    mMediaBrowserHelper = new MediaBrowserHelper(this);

    mMediaPlayers.put(AndroidMediaPlayer.class, new AndroidMediaPlayer());
    mMediaPlayers.put(VLCMediaPlayer.class, new VLCMediaPlayer());
    mMediaPlayers.put(DeezerMediaPlayer.class, new DeezerMediaPlayer());
    mMediaPlayers.put(SpotifyMediaPlayer.class, new SpotifyMediaPlayer());

    startService(new Intent(this, MicroService.class));

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        mRemoteControllerConnection = new RemoteControllerConnection();
        bindService(new Intent(this, RemoteControllerService.class), mRemoteControllerConnection,
                Context.BIND_AUTO_CREATE);
    }

    // Initialize WakeLock
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    mPlaybackManager = PlaybackManager.get(IdGenerator.getSessionUniqueStringId());
    mPlaybackManager.setCallback(mPlaybackManagerCallback);

    initMediaSession();

    try {
        mNotification = new MediaNotification(this);
    } catch (RemoteException e) {
        Log.e(TAG, "Could not connect to media controller: ", e);
    }

    Log.d(TAG, "PlaybackService has been created");
}

From source file:ca.nehil.rter.streamingapp.StreamingActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_streaming);

    poilist = new ArrayList<POI>();

    /* Retrieve server URL from stored app values */
    storedValues = getSharedPreferences(getString(R.string.sharedPreferences_filename), MODE_PRIVATE);
    server_url = storedValues.getString("server_url", "not-set");

    /* Orientation listenever implementation to orient video */
    myOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL) {
        @Override//from ww  w  . ja v a2 s  . c om
        public void onOrientationChanged(int orientation) {
            int rotation = getWindowManager().getDefaultDisplay().getRotation();
            if (rotation == Surface.ROTATION_270) {
                flipVideo = true;
            } else {
                flipVideo = false;
            }
        }
    };
    myOrientationEventListener.enable();

    /* Retrieve user auth data from cookie */
    cookies = getSharedPreferences("RterUserCreds", MODE_PRIVATE);
    cookieEditor = cookies.edit();
    setUsername = cookies.getString("Username", "not-set");
    setRterCredentials = cookies.getString("RterCreds", "not-set");
    if (setRterCredentials.equalsIgnoreCase("not-set") || setRterCredentials == null) {
        Log.e("PREFS", "Login Not successful, please restart");
    }
    Log.d("PREFS", "Prefs ==> rter_Creds:" + setRterCredentials);

    URL serverURL = null;
    try {
        serverURL = new URL(server_url);
        CookieStore myCookieStore = new BasicCookieStore();
        client.setCookieStore(myCookieStore);
        String[] credentials = setRterCredentials.split("=", 2);
        BasicClientCookie newCookie = new BasicClientCookie(credentials[0], credentials[1]);
        newCookie.setDomain(serverURL.getHost());
        newCookie.setPath("/");
        myCookieStore.addCookie(newCookie);
        mSensorSource = SensorSource.getInstance(this, GET_LOCATION_FROM_SERVER, serverURL, setRterCredentials,
                setUsername);
        POIs = new POIList(this, serverURL, setRterCredentials, mSensorSource);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    overlay = new OverlayController(this, POIs, mSensorSource); // OpenGL overlay 

    /* Get location */

    Location location = mSensorSource.getLocation();
    if (location != null) {
        lati = (float) (location.getLatitude());
        longi = (float) (location.getLongitude());
    } else {
        Toast toast = Toast.makeText(this, "Location not available", Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP, 0, 0);
        toast.show();
        lati = (float) (45.505958f); // Hard coded location for testing purposes.
        longi = (float) (-73.576254f);
    }

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, CLASS_LABEL);
    mWakeLock.acquire();

    /* Test, set desired orienation to north */
    overlay.setDesiredOrientation(0.0f);
}

From source file:org.eclipse.paho.android.service.MqttConnection.java

/**
 * Acquires a partial wake lock for this client
 *///from w ww .  j  ava2 s.  com
private void acquireWakeLock() {
    if (wakelock == null) {
        PowerManager pm = (PowerManager) service.getSystemService(Service.POWER_SERVICE);
        wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, wakeLockTag);
    }
    wakelock.acquire();

}

From source file:com.yamin.kk.service.AudioService.java

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

    // Get libVLC instance
    try {/*from   w  w  w.j  av  a2  s.c o m*/
        mLibVLC = Util.getLibVlcInstance();
    } catch (LibVlcException e) {
        e.printStackTrace();
    }

    mCallback = new HashMap<IAudioServiceCallback, Integer>();
    mCurrentIndex = -1;
    mPrevious = new Stack<Integer>();
    mEventHandler = EventHandler.getInstance();
    mRemoteControlClientReceiverComponent = new ComponentName(getPackageName(),
            RemoteControlClientReceiver.class.getName());

    // Make sure the audio player will acquire a wake-lock while playing. If we don't do
    // that, the CPU might go to sleep while the song is playing, causing playback to stop.
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

    IntentFilter filter = new IntentFilter();
    filter.setPriority(Integer.MAX_VALUE);
    filter.addAction(ACTION_REMOTE_BACKWARD);
    filter.addAction(ACTION_REMOTE_PLAYPAUSE);
    filter.addAction(ACTION_REMOTE_PLAY);
    filter.addAction(ACTION_REMOTE_PAUSE);
    filter.addAction(ACTION_REMOTE_STOP);
    filter.addAction(ACTION_REMOTE_FORWARD);
    filter.addAction(ACTION_REMOTE_LAST_PLAYLIST);
    filter.addAction(ACTION_WIDGET_INIT);
    filter.addAction(Intent.ACTION_HEADSET_PLUG);
    filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    filter.addAction(VLCApplication.SLEEP_INTENT);
    registerReceiver(serviceReceiver, filter);

    final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    boolean stealRemoteControl = pref.getBoolean("enable_steal_remote_control", false);

    if (!Util.isFroyoOrLater() || stealRemoteControl) {
        /* Backward compatibility for API 7 */
        filter = new IntentFilter();
        if (stealRemoteControl)
            filter.setPriority(Integer.MAX_VALUE);
        filter.addAction(Intent.ACTION_MEDIA_BUTTON);
        mRemoteControlClientReceiver = new RemoteControlClientReceiver();
        registerReceiver(mRemoteControlClientReceiver, filter);
    }
}

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

/**
 * Executes the download in a separate thread
 *//*from w w  w  .  j  a v  a  2 s.com*/
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:nl.sogeti.android.gpstracker.viewer.LoggerMap.java

private void updateBlankingBehavior() {
    boolean disableblanking = mSharedPreferences.getBoolean(Constants.DISABLEBLANKING, false);
    boolean disabledimming = mSharedPreferences.getBoolean(Constants.DISABLEDIMMING, false);
    if (disableblanking) {
        if (mWakeLock == null) {
            PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
            if (disabledimming) {
                mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, WAKELOCK_TAG);
            } else {
                mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, WAKELOCK_TAG);
            }/*from w  w w .j  av a 2 s  . c  o  m*/
        }
        if (mLoggerServiceManager.getLoggingState() == ExternalConstants.STATE_LOGGING && !mWakeLock.isHeld()) {
            mWakeLock.acquire();
            Log.w(this, "Acquired lock to keep screen on!");
        }
    }
}