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:com.uob.achohan.hdr.HDR.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mWL = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.FULL_WAKE_LOCK,
            "WakeLock");
    mWL.acquire();/*  w  ww .  j a  v a 2 s  .c  o m*/
    setContentView(R.layout.main);

    Display display = getWindowManager().getDefaultDisplay();
    Point displayDim = new Point();
    display.getSize(displayDim);

    final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    final ListView navList = (ListView) findViewById(R.id.drawer);
    List<DrawerItem> dataList = new ArrayList<DrawerItem>();

    dataList.add(new DrawerItem("HDR", new String[] { "On", "Off" }));

    CustomDrawerAdapter adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item, dataList);
    navList.setAdapter(adapter);
    navList.setOnItemClickListener(new ListView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int pos, long id) {
            drawer.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
                @Override
                public void onDrawerClosed(View drawerView) {
                    super.onDrawerClosed(drawerView);
                }
            });
            drawer.closeDrawer(navList);
        }
    });

    mView = (MyGLSurfaceView) findViewById(R.id.surfaceviewclass);
    mView.setDisplayDim(displayDim);
}

From source file:org.microg.tools.selfcheck.SystemChecks.java

private void isBatterySavingDisabled(final Context context, ResultCollector collector) {
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    collector.addResult(context.getString(R.string.self_check_name_battery_optimizations),
            pm.isIgnoringBatteryOptimizations(context.getPackageName()) ? Positive : Negative,
            context.getString(R.string.self_check_resolution_battery_optimizations), this);
}

From source file:ca.mcgill.hs.uploader.UploadThread.java

/**
 * Executes the upload in a separate thread
 *//*from  w  w w. j  ava 2s.c o m*/

@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    int finalStatus = Constants.STATUS_UNKNOWN_ERROR;
    boolean countRetry = false;
    int retryAfter = 0;
    AndroidHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    String filename = null;

    http_request_loop: while (true) {
        try {
            final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
            wakeLock.acquire();

            filename = mInfo.mFileName;
            final File file = new File(filename);
            if (!file.exists()) {
                Log.e(Constants.TAG, "file" + filename + " is to be uploaded, but cannot be found.");
                finalStatus = Constants.STATUS_FILE_ERROR;
                break http_request_loop;
            }
            client = AndroidHttpClient.newInstance(Constants.DEFAULT_USER_AGENT, mContext);
            Log.v(Constants.TAG, "initiating upload for " + mInfo.mUri);
            final HttpPost request = new HttpPost(Constants.UPLOAD_URL);
            request.addHeader("MAC", NetworkHelper.getMacAddress(mContext));

            final MultipartEntity mpEntity = new MultipartEntity();
            mpEntity.addPart("uploadedfile", new FileBody(file, "binary/octet-stream"));
            request.setEntity(mpEntity);

            HttpResponse response;
            try {
                response = client.execute(request);
                final HttpEntity resEntity = response.getEntity();

                String responseMsg = null;
                if (resEntity != null) {
                    responseMsg = EntityUtils.toString(resEntity);
                    Log.i(Constants.TAG, "Server Response: " + responseMsg);
                }
                if (resEntity != null) {
                    resEntity.consumeContent();
                }

                if (!responseMsg.contains("SUCCESS 0x64asv65")) {
                    Log.i(Constants.TAG, "Server Response: " + responseMsg);
                }
            } catch (final IllegalArgumentException e) {
                finalStatus = Constants.STATUS_BAD_REQUEST;
                request.abort();
                break http_request_loop;
            } catch (final IOException e) {
                if (!NetworkHelper.isNetworkAvailable(mContext)) {
                    finalStatus = Constants.STATUS_RUNNING_PAUSED;
                } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) {
                    finalStatus = Constants.STATUS_RUNNING_PAUSED;
                    countRetry = true;
                } else {
                    Log.d(Constants.TAG, "IOException trying to excute request for " + mInfo.mUri + " : " + e);
                    finalStatus = Constants.STATUS_HTTP_DATA_ERROR;
                }
                request.abort();
                break http_request_loop;
            }

            final int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 503 && mInfo.mNumFailed < Constants.MAX_RETRIES) {
                Log.v(Constants.TAG, "got HTTP response code 503");
                finalStatus = Constants.STATUS_RUNNING_PAUSED;
                countRetry = true;

                retryAfter = Constants.MIN_RETRY_AFTER;
                retryAfter += NetworkHelper.sRandom.nextInt(Constants.MIN_RETRY_AFTER + 1);
                retryAfter *= 1000;
                request.abort();
                break http_request_loop;
            } else {
                finalStatus = Constants.STATUS_SUCCESS;
            }
            break;
        } catch (final RuntimeException e) {
            finalStatus = Constants.STATUS_UNKNOWN_ERROR;
        } finally {
            mInfo.mHasActiveThread = false;
            if (wakeLock != null) {
                wakeLock.release();
                wakeLock = null;
            }
            if (client != null) {
                client.close();
                client = null;
            }
            if (finalStatus == Constants.STATUS_SUCCESS) {
                // TODO: Move the file.
            }
        }
    }

}

From source file:org.apache.cordova.plugin.powermanagement.PowerManagement.java

/**
 * Fetch a reference to the power-service when the plugin is initialized
 *///w ww.  j a v a2s.  co m
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
    super.initialize(cordova, webView);

    this.powerManager = (PowerManager) cordova.getActivity().getSystemService(Context.POWER_SERVICE);
}

From source file:me.postar.postarv2.LocalService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Functions.getParcels(parcels, this);

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Postar");

    if (Functions.isConnectedToInternet(LocalService.this)) {
        Ion.with(this).load("GET", "https://e-racuni.postacg.me/PracenjePosiljaka/").asString().withResponse()
                .setCallback(new FutureCallback<Response<String>>() {
                    @Override/* ww  w . j a  v a  2 s  .c  o m*/
                    public void onCompleted(Exception e, Response<String> result) {
                        Document html = Jsoup.parse(result.getResult());
                        Element viewState = html.getElementById("__VIEWSTATE");
                        Element eventValidation = html.getElementById("__EVENTVALIDATION");
                        Element btnPronadji = html.getElementById("btnPronadji");

                        for (final PostParcel parcel : parcels) {
                            if (parcel.isAlarmOn()) {
                                Ion.with(LocalService.this)
                                        .load("POST", "https://e-racuni.postacg.me/PracenjePosiljaka/")
                                        .setBodyParameter("__VIEWSTATE", viewState.val())
                                        .setBodyParameter("__EVENTVALIDATION", eventValidation.val())
                                        .setBodyParameter("btnPronadji", btnPronadji.val())
                                        .setBodyParameter("txtPrijemniBroj", parcel.getParcelNo()).asString()
                                        .withResponse().setCallback(new FutureCallback<Response<String>>() {
                                            @Override
                                            public void onCompleted(Exception e,
                                                    final Response<String> result) {
                                                Document html = Jsoup.parse(result.getResult());
                                                Element table = html.getElementById("dgInfo");

                                                if (table != null) {
                                                    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                                                            LocalService.this)
                                                                    .setSmallIcon(R.drawable.ic_mail_outline)
                                                                    .setLargeIcon(BitmapFactory.decodeResource(
                                                                            getResources(),
                                                                            R.drawable.ic_mail_outline))
                                                                    .setAutoCancel(true);
                                                    mBuilder.setContentTitle(getString(R.string.message_title));
                                                    mBuilder.setContentText(
                                                            getString(R.string.message_content));
                                                    Intent activityIntent = new Intent(LocalService.this,
                                                            StatusActivity.class);
                                                    activityIntent.putExtra("parcel", parcel);
                                                    PendingIntent resultPendingIntent = PendingIntent
                                                            .getActivity(LocalService.this, 0, activityIntent,
                                                                    PendingIntent.FLAG_UPDATE_CURRENT);
                                                    mBuilder.setContentIntent(resultPendingIntent);
                                                    NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                                                            Context.NOTIFICATION_SERVICE);

                                                    mNotificationManager.notify(12, mBuilder.build());

                                                    stopSelf();

                                                    wl.release();
                                                }
                                            }
                                        });
                            }
                        }
                    }
                });
    }

    return START_NOT_STICKY;
}

From source file:at.bitfire.davdroid.ui.StartupDialogFragment.java

public static StartupDialogFragment[] getStartupDialogs(Context context) {
    List<StartupDialogFragment> dialogs = new LinkedList<>();

    @Cleanup//  www . jav  a  2 s . c o  m
    ServiceDB.OpenHelper dbHelper = new ServiceDB.OpenHelper(context);
    Settings settings = new Settings(dbHelper.getReadableDatabase());

    if (BuildConfig.VERSION_NAME.contains("-alpha") || BuildConfig.VERSION_NAME.contains("-beta")
            || BuildConfig.VERSION_NAME.contains("-rc"))
        dialogs.add(StartupDialogFragment.instantiate(Mode.DEVELOPMENT_VERSION));
    else
        dialogs.add(StartupDialogFragment.instantiate(Mode.FDROID_DONATE));

    // battery optimization whitelisting
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
            && settings.getBoolean(HINT_BATTERY_OPTIMIZATIONS, true)) {
        PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (!powerManager.isIgnoringBatteryOptimizations(BuildConfig.APPLICATION_ID))
            dialogs.add(StartupDialogFragment.instantiate(Mode.BATTERY_OPTIMIZATIONS));
    }

    // OpenTasks information
    if (!LocalTaskList.tasksProviderAvailable(context)
            && settings.getBoolean(HINT_OPENTASKS_NOT_INSTALLED, true))
        dialogs.add(StartupDialogFragment.instantiate(Mode.OPENTASKS_NOT_INSTALLED));

    Collections.reverse(dialogs);
    return dialogs.toArray(new StartupDialogFragment[dialogs.size()]);
}

From source file:nodomain.freeyourgadget.gadgetbridge.externalevents.PebbleReceiver.java

@Override
public void onReceive(Context context, Intent intent) {

    Prefs prefs = GBApplication.getPrefs();
    if ("never".equals(prefs.getString("notification_mode_pebblemsg", "when_screen_off"))) {
        return;/*from   w ww.  j a  va  2  s  .co m*/
    }
    if ("when_screen_off".equals(prefs.getString("notification_mode_pebblemsg", "when_screen_off"))) {
        PowerManager powermanager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (powermanager.isScreenOn()) {
            return;
        }
    }

    String messageType = intent.getStringExtra("messageType");
    if (!messageType.equals("PEBBLE_ALERT")) {
        LOG.info("non PEBBLE_ALERT message type not supported");
        return;
    }

    if (!intent.hasExtra("notificationData")) {
        LOG.info("missing notificationData extra");
        return;
    }

    NotificationSpec notificationSpec = new NotificationSpec();
    notificationSpec.id = -1;

    String notificationData = intent.getStringExtra("notificationData");
    try {
        JSONArray notificationJSON = new JSONArray(notificationData);
        notificationSpec.title = notificationJSON.getJSONObject(0).getString("title");
        notificationSpec.body = notificationJSON.getJSONObject(0).getString("body");
    } catch (JSONException e) {
        e.printStackTrace();
        return;
    }

    if (notificationSpec.title != null) {
        notificationSpec.type = NotificationType.UNKNOWN;
        String sender = intent.getStringExtra("sender");
        if ("Conversations".equals(sender)) {
            notificationSpec.type = NotificationType.CONVERSATIONS;
        } else if ("OsmAnd".equals(sender)) {
            notificationSpec.type = NotificationType.GENERIC_NAVIGATION;
        }
        GBApplication.deviceService().onNotification(notificationSpec);
    }
}

From source file:org.apache.cordova.plugin.PowerManagement.java

/**
 * Sets the application context for this plugin
 * Used to obtain a reference to the powermanager
 *//*from  w ww. ja v  a 2  s.  c om*/
@Override
public void setContext(CordovaInterface ctx) {
    super.setContext(ctx);

    this.powerManager = (PowerManager) ctx.getActivity().getSystemService(Context.POWER_SERVICE);
}

From source file:com.cpd.receivers.LibraryRenewAlarmBroadcastReceiver.java

@Override
public void onReceive(Context context, Intent intent) {

    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, AppTags.UFRGS_MOBILE);
    //Acquire the lock
    wl.acquire();/*from   w w  w  .j  a  v a2s .  c o m*/

    prefs = context.getSharedPreferences(AppTags.LIBRARY_LOGIN_PREF, Context.MODE_PRIVATE);
    editor = prefs.edit();
    int value = prefs.getInt(AppTags.ALARM_COUNTER, 0);
    value = value + 1;
    editor.putInt(AppTags.ALARM_COUNTER, value);
    editor.commit();

    LibraryLoader loader = new LibraryLoader(context);
    loader.renewBooks(null, true);

    if (value == DAILY_RETRIES) {
        launchNotification(context, context.getString(R.string.we_tried_to_renew_your_items_notification_title),
                context.getString(R.string.verify_return_date_notification_message));
        editor.putInt(AppTags.ALARM_COUNTER, 0);
        editor.commit();
    }

    wl.release();

}

From source file:com.ilearnrw.reader.tasks.AddToLibraryTask.java

public void run(String... params) {

    wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "wifiLock");
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "wakeLock");

    wifiLock.acquire();//from w ww. j  a  va  2 s .  co  m
    wakeLock.acquire();
    this.execute(params);
}