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.ternup.caddisfly.fragment.DetailsFragment.java

public void postResult(String folderName) {

    RequestParams params = new RequestParams();
    TimeZone tz = TimeZone.getTimeZone("UTC");
    final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
    df.setTimeZone(tz);//from   w ww.  j  a  v  a2 s . c  om

    final ArrayList<String> filePaths = FileUtils.getFilePaths(getActivity(), folderName, "/small/",
            mLocationId);
    File myFile = new File(filePaths.get(0));
    String date = df.format(DateUtils.getDateFromFilename(myFile.getName()));

    params.put("date", date);
    String deviceId = Build.MANUFACTURER + " " + Build.MODEL;
    if (deviceId.length() > 32) {
        deviceId = deviceId.substring(1, 32);
    }
    params.put("deviceId", deviceId);
    params.put("type", String.valueOf(mTestTypeId + 1));

    if (wakeLock == null || !wakeLock.isHeld()) {
        PowerManager pm = (PowerManager) getActivity().getApplicationContext()
                .getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP
                | PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
        wakeLock.acquire();
    }

    WebClient.post("tests", params, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String response = responseBody == null ? null : new String(responseBody);
            try {
                JSONObject json = new JSONObject(response);
                final int newId = json.getInt("id");
                if (filePaths.size() > 0) {
                    count = 0;
                    totalCount = filePaths.size();
                    postItem(newId, filePaths);
                }

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

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, final Throwable error) {
            Log.d(Globals.DEBUG_TAG, "fail: " + error.getMessage());

            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }

                    if (wakeLock != null && wakeLock.isHeld()) {
                        wakeLock.release();
                    }
                    AlertUtils.showAlert(getActivity(), R.string.error, error.getMessage(), R.string.ok, null,
                            null);
                }
            });
        }
    });
}

From source file:com.terminal.ide.TermService.java

@Override
public void onCreate() {
    compat = new ServiceForegroundCompat(this);
    mTermSessions = new ArrayList<TermSession>();

    /**/*from w w w.jav a  2  s .  c  o m*/
     * ??
     * @author wanghao
     * @date 2015-3-27
     * ???Activity
     */
    //?intent
    //warning??start.class
    //?mainActivity
    Intent openMainActivityIntent = new Intent(this, mainAvtivity.class);
    Intent openTerminalActivityIntent = new Intent(this, Term.class);
    openTerminalActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    openMainActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    Intent exitTerminalIntent = new Intent(this, ExitService.class);
    Notification sessionBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(getText(R.string.application_terminal))
            .setContentText(getText(R.string.service_notify_text))
            .setContentIntent(PendingIntent.getActivity(this, 0, openMainActivityIntent, 0))
            .setStyle(new NotificationCompat.BigTextStyle().bigText(getText(R.string.service_notify_text)))
            .addAction(R.drawable.ic_action_iconfont_terminal, getText(R.string.notification_open_termianl),
                    PendingIntent.getActivity(this, 0, openTerminalActivityIntent,
                            Intent.FLAG_ACTIVITY_CLEAR_TOP))
            .addAction(R.drawable.ic_action_iconfont_exit, getText(R.string.notification_exit_app),
                    PendingIntent.getService(this, 0, exitTerminalIntent, 0))
            .setOngoing(true).build();
    compat.startForeground(RUNNING_NOTIFICATION, sessionBuilder);

    mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    mPrefs.registerOnSharedPreferenceChangeListener(this);
    mHardKeys.setKeyMappings(mPrefs);

    //Setup the Hard Key Mappings..
    mSettings = new TermSettings(mPrefs);

    //Need to set the HOME Folder and Bash startup..
    //Sometime getfilesdir return NULL ?
    mSessionInit = false;
    File home = getFilesDir();
    if (home != null) {
        initSessions(home);
    }

    //Start a webserver for comms..
    //        mServer = new webserver(this);
    //        mServer.start();

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    //Get a wake lock
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TermDebug.LOG_TAG);
    mScreenLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TermDebug.LOG_TAG);
    mWifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL, TermDebug.LOG_TAG);

    //Get the Initial Values
    //        boolean cpulock     = getStringPref("cpulock","1") == 1 ? true : false;
    //        boolean wifilock    = getStringPref("wifilock","0") == 1 ? true : false;
    //        boolean screenlock  = getStringPref("screenlock","0") == 1 ? true : false;
    setupWakeLocks();

    Log.d(TermDebug.LOG_TAG, "TermService started");

    return;
}

From source file:cx.ring.fragments.CallFragment.java

@Override
public void onCreate(Bundle savedBundle) {
    Log.i(TAG, "onCreate");
    super.onCreate(savedBundle);

    audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);

    setHasOptionsMenu(true);//  w  ww.  jav  a  2  s . com
    PowerManager powerManager = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
    mScreenWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
            | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "cx.ring.onIncomingCall");
    mScreenWakeLock.setReferenceCounted(false);

    Log.d(TAG, "Acquire wake up lock");
    if (mScreenWakeLock != null && !mScreenWakeLock.isHeld()) {
        mScreenWakeLock.acquire();
    }
}

From source file:org.runnerup.gpstracker.GpsTracker.java

private void wakelock(boolean get) {
    if (mWakeLock != null) {
        if (mWakeLock.isHeld()) {
            mWakeLock.release();/*from   w w  w. ja  va  2s .c o m*/
        }
        mWakeLock = null;
    }
    if (get) {
        PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "RunnerUp");
        if (mWakeLock != null) {
            mWakeLock.acquire();
        }
    }
}

From source file:it.baywaylabs.jumpersumo.twitter.TwitterListener.java

/**
 * Method auto invoked pre execute the task.<br />
 * This method read the last mention id from Shared Preferences.
 *//*from w w w.  jav a 2s  .  com*/
@Override
protected void onPreExecute() {

    super.onPreExecute();

    // take CPU lock to prevent CPU from going off if the user
    // presses the power button during download
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
    mWakeLock.acquire();

    sharedPref = context.getSharedPreferences(Constants.MY_PREFERENCES, Context.MODE_PRIVATE);
    editor = sharedPref.edit();

    idLastTwit = sharedPref.getLong(Constants.LAST_ID_MENTIONED, 0);

}

From source file:org.wso2.emm.system.service.api.OTAServerManager.java

public OTAServerManager(Context context) throws MalformedURLException {
    serverConfig = new OTAServerConfig(Build.PRODUCT, context);
    PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "OTA Wakelock");
    this.context = context;
}

From source file:com.yi4all.rupics.ImageDetailActivity.java

public void startSlideShow() {
    Runnable slide = new Runnable() {

        @Override/*from   w w w  . j  a  v  a 2  s  .  c  om*/
        public void run() {
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, LOGTAG);
            wl.acquire();
            while (isSlideshow) {
                if (imageSequence < imgList.size() - 1) {
                    // back to the next image
                    imageSequence++;
                    setCurrentPage();
                } else {
                    // give a tip to user
                    Utils.toastMsg(ImageDetailActivity.this, R.string.alreadyLast);
                    isSlideshow = false;
                }
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    Log.e(LOGTAG, "startSlideShow:" + ((e != null) ? e.getMessage() : "exception is null"));
                }

                // if(ImageDetailActivity.this.)
            }
            if (wl.isHeld())
                wl.release();
        }
    };
    new Thread(slide).start();

}

From source file:pct.droid.base.torrent.TorrentService.java

public void streamTorrent(@NonNull final String torrentUrl) {
    Timber.d("streamTorrent");

    //attempt to initialize service
    initialize();//from   w  w  w . j a v a 2 s  .  c o  m

    if (mHandler == null || mIsStreaming)
        return;

    mIsCanceled = false;
    mReady = false;

    Timber.d("Starting streaming");

    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, THREAD_NAME);
    mWakeLock.acquire();

    SessionSettings sessionSettings = mTorrentSession.getSettings();
    sessionSettings.setActiveDHTLimit(PrefUtils.get(this, Prefs.LIBTORRENT_DHT_LIMIT, 200));
    sessionSettings.setConnectionsLimit(PrefUtils.get(this, Prefs.LIBTORRENT_CONNECTION_LIMIT, 200));
    sessionSettings.setDownloadRateLimit(PrefUtils.get(this, Prefs.LIBTORRENT_DOWNLOAD_LIMIT, 0));
    sessionSettings.setUploadRateLimit(PrefUtils.get(this, Prefs.LIBTORRENT_UPLOAD_LIMIT, 0));
    mTorrentSession.setSettings(sessionSettings);

    mHandler.post(new Runnable() {
        @Override
        public void run() {
            Timber.d("streaming runnable");
            mIsStreaming = true;
            mCurrentTorrentUrl = torrentUrl;

            File saveDirectory = new File(PopcornApplication.getStreamDir());
            saveDirectory.mkdirs();

            File torrentFileDir = new File(saveDirectory, "files");
            torrentFileDir.mkdirs();

            File torrentFile = new File(torrentFileDir, System.currentTimeMillis() + ".torrent");

            if (!torrentFile.exists()) {
                int fileCreationTries = 0;
                while (fileCreationTries < 4) {
                    try {
                        fileCreationTries++;
                        if (torrentFileDir.mkdirs() || torrentFileDir.isDirectory()) {
                            Timber.d("Creating torrent file");
                            torrentFile.createNewFile();
                        }
                    } catch (IOException e) {
                        Timber.e(e, "Error on file create");
                    }
                }

                if (!getTorrentFile(torrentUrl, torrentFile)) {
                    for (final Listener listener : mListener) {
                        ThreadUtils.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                listener.onStreamError(new IOException("Write error"));
                            }
                        });
                    }
                    return;
                } else if (!torrentFile.exists()) {
                    for (final Listener listener : mListener) {
                        ThreadUtils.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                listener.onStreamError(new IOException("Write error"));
                            }
                        });
                    }
                    return;
                }
            }

            if (!mCurrentTorrentUrl.equals(torrentUrl) || mIsCanceled) {
                return;
            }

            mCurrentTorrent = mTorrentSession.addTorrent(torrentFile, saveDirectory);
            mCurrentListener = new TorrentAlertAdapter(mCurrentTorrent);
            mTorrentSession.addListener(mCurrentListener);

            TorrentInfo torrentInfo = mCurrentTorrent.getTorrentInfo();
            FileStorage fileStorage = torrentInfo.getFiles();
            long highestFileSize = 0;
            int selectedFile = -1;
            for (int i = 0; i < fileStorage.geNumFiles(); i++) {
                long fileSize = fileStorage.getFileSize(i);
                if (highestFileSize < fileSize) {
                    highestFileSize = fileSize;
                    selectedFile = i;
                }
            }

            mCurrentVideoLocation = new File(saveDirectory, torrentInfo.getFileAt(selectedFile).getPath());

            Timber.d("Video location: %s", mCurrentVideoLocation);

            //post a new runnable which will potentially take along time.
            //this is the runnable which actually starts the streaming.
            //posting this as a runnable will allow other runnables that have been posted
            //execute before this potentially blocking runnable
            mHandler.post(new Runnable() {
                @Override
                public void run() {

                    //blocking call.
                    mDHT.waitNodes(30);
                    mCurrentTorrent.setSequentialDownload(true);
                    mCurrentTorrent.resume();
                    for (final Listener listener : mListener) {
                        ThreadUtils.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                listener.onStreamStarted();
                            }
                        });
                    }
                }
            });
        }
    });
}

From source file:eu.chainfire.geolog.service.BackgroundService.java

@SuppressLint("NewApi")
@Override//  w w w  .  j  a v a 2s.c om
public void onCreate() {
    super.onCreate();
    Debug.log("Service created");

    if (thread == null) {
        Debug.log("Launching thread");
        thread = new ServiceThread();
        thread.setContext(getApplicationContext());
        thread.start();
    }

    PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
    wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "GeoLog Wakelock");

    Intent i = new Intent();
    i.setAction(Intent.ACTION_MAIN);
    i.addCategory(Intent.CATEGORY_LAUNCHER);
    i.setClass(this, MainActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_NEW_TASK);
    notificationIntent = PendingIntent.getActivity(this, 0, i, 0);

    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationBuilder = (new Notification.Builder(this)).setSmallIcon(R.drawable.ic_stat_service)
            .setContentIntent(notificationIntent).setWhen(System.currentTimeMillis()).setAutoCancel(false)
            .setOngoing(true).setContentTitle(getString(R.string.service_title))
            .setContentText(getString(R.string.service_waiting));

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        notificationBuilder.setShowWhen(false);
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        /* quick turn off, maybe ? if added, make sure to add a button to preferences to disable these buttons
        notificationBuilder.
           setPriority(Notification.PRIORITY_MAX).
           addAction(0, "A", notificationIntent).
           addAction(0, "B", notificationIntent).
           addAction(0, "C", notificationIntent);
        */
    }

    updateNotification();
}

From source file:at.aec.solutions.checkmkagent.AgentService.java

@Override
public void onCreate() {
    super.onCreate();
    Log.v(TAG, "onCreate");

    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    m_wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
    m_wakeLock.acquire();/*from w ww .  j  ava  2  s  .  co m*/

    //Copy busybox binary to app directory
    if (!PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean("bbinstalled",
            false)) {
        PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit()
                .putBoolean("bbinstalled", true).commit();

        // There is also String[] Build.SUPPORTED_ABIS from API 21 on and
        // before String Build.CPU_ABI String Build.CPU_ABI2, maybe i should investigate there
        String arch = System.getProperty("os.arch");
        Log.v(TAG, arch);
        if (arch.equals("armv7l")) {
            copyAsset(getAssets(), "bbb/busybox", getApplicationInfo().dataDir + "/busybox");
        }
        if (arch.equals("i686")) {
            copyAsset(getAssets(), "bbb/busybox-i686", getApplicationInfo().dataDir + "/busybox");
        }

        //         copyAsset(getAssets(), "bbb/busybox-x86_64", getApplicationInfo().dataDir+"/busybox-x86_64");
        changeBusyboxPermission();
    }

    socketServerThread = new Thread(new SocketServerThread());
    socketServerThread.setName("CheckMK-Agent ServerThread");
    socketServerThread.start();

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher).setContentTitle("CheckMK Agent started.")
            .setContentText("Listening on Port " + SERVERPORT + ". Tap to configure.");

    Intent resultIntent = new Intent(this, ConfigureActivity.class);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(ConfigureActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    // mId allows you to update the notification later on.
    Notification notify = mBuilder.build();
    notify.flags |= Notification.FLAG_NO_CLEAR;

    mNotificationManager.notify(mId, notify);
}