Example usage for android.content Context POWER_SERVICE

List of usage examples for android.content Context POWER_SERVICE

Introduction

In this page you can find the example usage for android.content Context POWER_SERVICE.

Prototype

String POWER_SERVICE

To view the source code for android.content Context POWER_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.os.PowerManager for controlling power management, including "wake locks," which let you keep the device on while you're running long tasks.

Usage

From source file:net.kseek.camtest.ui.CamtestActivity.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mApplication = (CamtestApplication) getApplication();

    setContentView(R.layout.camtest);//from  www .  j av a2s  .co  m

    if (findViewById(R.id.handset_pager) != null) {

        // Handset detected !
        mAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.handset_pager);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        mSurfaceView = (SurfaceView) findViewById(R.id.handset_camera_view);
        SessionBuilder.getInstance().setSurfaceView(mSurfaceView);
        SessionBuilder.getInstance().setPreviewOrientation(90);

    } else {

        // Tablet detected !
        device = TABLET;
        mAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.tablet_pager);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        SessionBuilder.getInstance().setPreviewOrientation(0);

    }

    mViewPager.setAdapter(mAdapter);

    // Prevents the phone from going to sleep mode
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "net.kseek.camtest.wakelock");

    // Starts the service of the HTTP server
    this.startService(new Intent(this, CustomHttpServer.class));

    // Starts the service of the RTSP server
    this.startService(new Intent(this, CustomRtspServer.class));

}

From source file:net.frygo.findmybuddy.GCMIntentService.java

private static void generateNotification(Context context, String message) {

    Random rand = new Random();
    int x = rand.nextInt();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    String title = context.getString(R.string.app_name);
    Intent notificationIntent = new Intent(context, customlistview.class);
    notificationIntent.putExtra("alert", message);
    message = message + " would like to add you as friend";
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_CANCEL_CURRENT);

    Notification notification = new Notification(R.drawable.logo, message, System.currentTimeMillis());
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(x, notification);

    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    final PowerManager.WakeLock mWakelock = pm
            .newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, title);
    mWakelock.acquire();//from   ww w .ja v  a2 s.  co m

    // Timer before putting Android Device to sleep mode.
    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        public void run() {
            mWakelock.release();
        }
    };
    timer.schedule(task, 5000);

}

From source file:org.android.gcm.client.GcmIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    final SharedPreferences prefs = getSharedPreferences("gcmclient", Context.MODE_PRIVATE);
    pushpak = prefs.getString("push_pak", "");
    pushact = prefs.getString("push_act", "");
    final boolean pushon = prefs.getBoolean("push_on", true);
    final boolean pushnotif = prefs.getBoolean("push_notification", true);

    if (pushnotif) {
        final String notifact = prefs.getString("notification_act", "");
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        // The getMessageType() intent parameter must be the intent you received
        // in your BroadcastReceiver.
        String messageType = gcm.getMessageType(intent);

        // Send a notification.
        if (!extras.isEmpty()) { // has effect of unparcelling Bundle
            /*//from  ww  w .ja  v  a2  s.  c  om
             * Filter messages based on message type. Since it is likely that GCM will be
             * extended in the future with new message types, just ignore any message types you're
             * not interested in, or that you don't recognize.
             */
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
                sendNotification(getString(R.string.send_error) + ": " + extras.toString(), notifact);
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
                sendNotification(getString(R.string.deleted) + ": " + extras.toString(), notifact);
                // If it's a regular GCM message, do some work.
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                // Post notification of received message.
                sendNotification(
                        getString(R.string.received, extras.getString("name"), extras.getString("num")),
                        notifact);
                Log.i(TAG, "Received: " + extras.toString());
            }
        }
    }

    // End if push is not enabled.
    if (!pushon) {
        // Release the wake lock provided by the WakefulBroadcastReceiver.
        GcmBroadcastReceiver.completeWakefulIntent(intent);
        return;
    }

    final boolean fullwake = prefs.getBoolean("full_wake", false);
    final boolean endoff = prefs.getBoolean("end_off", true);

    // Manage the screen.
    PowerManager mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock mWakeLock = mPowerManager
            .newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, TAG);
    boolean misScreenOn = mPowerManager.isScreenOn();
    int mScreenTimeout = 0;
    if (!misScreenOn) {
        if (endoff) {
            // Change the screen timeout setting.
            mScreenTimeout = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT,
                    0);
            if (mScreenTimeout != 0) {
                Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 3000);
            }
        }
        // Full wake lock
        if (fullwake) {
            mWakeLock.acquire();
        }
    }

    // Start the activity.
    try {
        startActivity(getPushactIntent(Intent.FLAG_ACTIVITY_NO_USER_ACTION | Intent.FLAG_ACTIVITY_NO_ANIMATION
                | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS));
        // Wait to register.
        Thread.sleep(REGISTER_DURATION);
    } catch (android.content.ActivityNotFoundException e) {
        RING_DURATION = 0;
        Log.i(TAG, "Activity not started");
    } catch (InterruptedException e) {
    }

    // Release the wake lock.
    if (!misScreenOn && fullwake) {
        mWakeLock.release();
    }
    GcmBroadcastReceiver.completeWakefulIntent(intent);

    // Restore the screen timeout setting.
    if (endoff && mScreenTimeout != 0) {
        try {
            Thread.sleep(RING_DURATION);
        } catch (InterruptedException e) {
        }
        Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, mScreenTimeout);
    }
}

From source file:net.majorkernelpanic.spydroid.SpydroidActivity.java

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);//from   w w w.  ja  v  a2 s.co  m

    camera = (SurfaceView) findViewById(R.id.smallcameraview);
    context = this.getApplicationContext();
    line1 = (TextView) findViewById(R.id.line1);
    line2 = (TextView) findViewById(R.id.line2);
    version = (TextView) findViewById(R.id.version);
    buttonSettings = (ImageView) findViewById(R.id.button_settings);
    buttonClient = (ImageView) findViewById(R.id.button_client);
    buttonAbout = (ImageView) findViewById(R.id.button_about);
    signWifi = (TextView) findViewById(R.id.advice);
    signStreaming = (TextView) findViewById(R.id.streaming);
    signInformation = (LinearLayout) findViewById(R.id.information);
    pulseAnimation = AnimationUtils.loadAnimation(this, R.anim.pulse);

    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    H264Stream.setPreferences(settings);

    settings.registerOnSharedPreferenceChangeListener(this);

    camera.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    holder = camera.getHolder();

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "net.majorkernelpanic.spydroid.wakelock");

    // Print version number
    try {
        version.setText("v" + this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName);
    } catch (Exception e) {
        version.setText("v???");
    }

    Session.setSurfaceHolder(holder);
    Session.setHandler(handler);
    Session.setDefaultAudioEncoder(settings.getBoolean("stream_audio", false)
            ? Integer.parseInt(settings.getString("audio_encoder", "3"))
            : 0);
    Session.setDefaultVideoEncoder(settings.getBoolean("stream_video", true)
            ? Integer.parseInt(settings.getString("video_encoder", "2"))
            : 0);
    Session.setDefaultVideoQuality(new VideoQuality(settings.getInt("video_resX", 0),
            settings.getInt("video_resY", 0), Integer.parseInt(settings.getString("video_framerate", "0")),
            Integer.parseInt(settings.getString("video_bitrate", "0")) * 1000));

    rtspServer = new RtspServer(8086, handler);
    httpServer = new CustomHttpServer(8080, this.getApplicationContext(), handler);

    buttonSettings.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            // Starts QualityListActivity where user can change the quality of the stream
            Intent intent = new Intent(context, OptionsActivity.class);
            startActivityForResult(intent, 0);
        }
    });
    buttonClient.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            // Starts ClientActivity, the user can then capture the stream from another phone running Spydroid
            Intent intent = new Intent(context, ClientActivity.class);
            startActivityForResult(intent, 0);
        }
    });
    buttonAbout.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            // Display some information
            Intent intent = new Intent(context, AboutActivity.class);
            startActivityForResult(intent, 0);
        }
    });

}

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

/**
 * Executes the download in a separate thread
 *//*  w w  w.j a  va2s . co  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 . co m*/
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: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   ww w  .j  av a2 s  .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:javax.microedition.lcdui.Display.java

public static boolean flashBacklight(int duration) {
    try {//from  ww w  .jav  a  2s.  c o  m
        if (powermanager == null) {
            powermanager = (PowerManager) ContextHolder.getContext().getSystemService(Context.POWER_SERVICE);
            wakelock = powermanager.newWakeLock(
                    PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
                    "Display.flashBacklight");
        }

        if (wakelock.isHeld()) {
            wakelock.release();
        }

        if (duration > 0) {
            wakelock.acquire(duration);
        } else if (duration < 0) {
            wakelock.acquire();
        }

        return true;
    } catch (Throwable t) {
        return false;
    }
}

From source file:com.android.browser.BrowserActivity.java

private boolean shouldIgnoreIntents() {
    // Only process intents if the screen is on and the device is unlocked
    // aka, if we will be user-visible
    if (mKeyguardManager == null) {
        mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
    }/* www  . ja v  a 2s .  c  o m*/
    if (mPowerManager == null) {
        mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    }
    boolean ignore = !mPowerManager.isScreenOn();
    ignore |= mKeyguardManager.inKeyguardRestrictedInputMode();
    if (LOGV_ENABLED) {
        Log.v(LOGTAG, "ignore intents: " + ignore);
    }
    return ignore;
}

From source file:fr.bmartel.android.tictactoe.gcm.MyGcmListenerService.java

/**
 * Called when message is received.//from ww  w.  j a va 2  s. c  o  m
 *
 * @param from SenderID of the sender.
 * @param data Data bundle containing message data as key/value pairs.
 *             For Set of keys use data.keySet().
 */
// [START receive_message]
@Override
public void onMessageReceived(String from, Bundle data) {

    String message = data.getString("message");

    if (from.startsWith("/topics/" + GameSingleton.DEVICE_ID)) {
        Log.d(TAG, "Message: " + message);

        try {

            JSONObject object = new JSONObject(message);

            ArrayList<String> eventItem = new ArrayList<>();
            eventItem.add(object.toString());

            broadcastUpdateStringList(BroadcastFilters.EVENT_MESSAGE, eventItem);

            if (!GameSingleton.activityForeground) {

                if (object.has(RequestConstants.DEVICE_MESSAGE_TOPIC)
                        && object.has(RequestConstants.DEVICE_MESSAGE_CHALLENGER_ID)
                        && object.has(RequestConstants.DEVICE_MESSAGE_CHALLENGER_NAME)) {

                    GameMessageTopic topic = GameMessageTopic
                            .getTopic(object.getInt(RequestConstants.DEVICE_MESSAGE_TOPIC));

                    ChallengeMessage challengeMessage = new ChallengeMessage(topic,
                            object.getString(RequestConstants.DEVICE_MESSAGE_CHALLENGER_ID),
                            object.getString(RequestConstants.DEVICE_MESSAGE_CHALLENGER_NAME));

                    Log.i(TAG, "challenged by " + challengeMessage.getChallengerName() + " : "
                            + challengeMessage.getChallengerId());

                    Intent intent2 = new Intent(this, DeviceListActivity.class);
                    intent2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent2,
                            PendingIntent.FLAG_ONE_SHOT);
                    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                            .setSmallIcon(R.mipmap.ic_launcher).setContentTitle("Fight!")
                            .setContentText("challenged by " + challengeMessage.getChallengerName())
                            .setAutoCancel(true).setSound(defaultSoundUri).setContentIntent(pendingIntent);
                    NotificationManager notificationManager = (NotificationManager) getSystemService(
                            Context.NOTIFICATION_SERVICE);
                    notificationManager.notify(new Random().nextInt(9999), notificationBuilder.build());

                    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
                    boolean isScreenOn = pm.isScreenOn();
                    if (isScreenOn == false) {
                        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
                                | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "MyLock");
                        wl.acquire(10000);
                        PowerManager.WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                                "MyCpuLock");
                        wl_cpu.acquire(10000);
                    }

                    GameSingleton.pendingChallengeMessage = challengeMessage;
                    GameSingleton.pendingChallenge = true;
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();

        }
    }
}