Java Code Examples for android.os.PowerManager#isIgnoringBatteryOptimizations()

The following examples show how to use android.os.PowerManager#isIgnoringBatteryOptimizations() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MainActivity.java    From PresencePublisher with MIT License 6 votes vote down vote up
private void checkBatteryOptimizationAndStartWorker() {
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && powerManager != null
            && !powerManager.isIgnoringBatteryOptimizations(getPackageName())) {
        HyperLog.d(TAG, "Battery optimization not yet disabled, asking user ...");
        FragmentManager fm = getSupportFragmentManager();

        // this app should fall under "task automation app" in
        // https://developer.android.com/training/monitoring-device-state/doze-standby.html#whitelisting-cases
        @SuppressLint("BatteryLife")
        ConfirmationDialogFragment fragment = ConfirmationDialogFragment.getInstance(ok -> {
            if (ok) {
                Uri packageUri = Uri.fromParts("package", getPackageName(), null);
                startActivityForResult(
                        new Intent(ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, packageUri), BATTERY_OPTIMIZATION_REQUEST_CODE);
            }
        }, R.string.battery_optimization_dialog_title, R.string.battery_optimization_dialog_message);
        fragment.show(fm, null);
    } else {
        new Publisher(this).scheduleNow();
    }
}
 
Example 2
Source File: MainActivity.java    From com.ruuvi.station with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void requestIgnoreBatteryOptimization(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        try {
            Intent intent = new Intent();
            String packageName = context.getPackageName();
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            if (pm.isIgnoringBatteryOptimizations(packageName))
                intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
            else {
                intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setData(Uri.parse("package:" + packageName));
            }
            context.startActivity(intent);
        } catch (Exception e) {
            Log.d(TAG, "Could not set ignoring battery optimization");
        }
    }
}
 
Example 3
Source File: BackgroundModeExt.java    From cordova-plugin-background-mode with Apache License 2.0 6 votes vote down vote up
/**
 * Disables battery optimizations for the app.
 * Requires permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS to function.
 */
@SuppressLint("BatteryLife")
private void disableBatteryOptimizations()
{
    Activity activity = cordova.getActivity();
    Intent intent     = new Intent();
    String pkgName    = activity.getPackageName();
    PowerManager pm   = (PowerManager)getService(POWER_SERVICE);

    if (SDK_INT < M)
        return;

    if (pm.isIgnoringBatteryOptimizations(pkgName))
        return;

    intent.setAction(ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
    intent.setData(Uri.parse("package:" + pkgName));

    cordova.getActivity().startActivity(intent);
}
 
Example 4
Source File: TrackingPresenter.java    From ridesharing-android with MIT License 6 votes vote down vote up
@SuppressLint({"BatteryLife", "InlinedApi"})
@SuppressWarnings("ConstantConditions")
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    if (requestCode == PERMISSIONS_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) {
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            PowerManager pm = (PowerManager) mContext.getSystemService(Activity.POWER_SERVICE);
            String packageName = mContext.getPackageName();
            if (!pm.isIgnoringBatteryOptimizations(packageName)) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                Uri uri = Uri.parse("package:" + packageName);
                intent.setData(uri);
                mView.startActivityForResult(intent, PERMISSIONS_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            }
        }
    }
}
 
Example 5
Source File: XmppActivity.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
protected boolean isOptimizingBattery() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        return pm != null && !pm.isIgnoringBatteryOptimizations(getPackageName());
    } else {
        return false;
    }
}
 
Example 6
Source File: StaticUtils.java    From Status with Apache License 2.0 5 votes vote down vote up
public static boolean isIgnoringOptimizations(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (powerManager != null)
            return powerManager.isIgnoringBatteryOptimizations(context.getPackageName());
    }

    return true;
}
 
Example 7
Source File: MainSettingsActivity.java    From an2linuxclient with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onResume() {
    super.onResume();
    /*
    This is required if the user left the app but it's still running and the user uses the
    tile to change the setting and then reopens the app. Without this the checked state will
    be wrong. Without this it's required to unregister the listener below in onDestroy
    instead of onPause.
     */
    updateAn2linuxEnabled(PreferenceManager.getDefaultSharedPreferences(getActivity()));

    /*
    The listener: Preference.OnPreferenceChangeListener in onCreate does not notify updates
    from the quicksettings tile. For that this listener is required, if this is not used
    the state in the app will not be updated if the user changes the tile while the app
    is still running. It will only be updated after onDestroy / onCreate cycle.
     */
    PreferenceManager.getDefaultSharedPreferences(getActivity()).registerOnSharedPreferenceChangeListener(this);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        Preference ignoreDozePref = findPreference(getString(R.string.open_ignore_battery_optimization_settings_key));
        final PowerManager powerManager = (PowerManager) getContext().getSystemService(POWER_SERVICE);
        if (powerManager.isIgnoringBatteryOptimizations(getContext().getPackageName())) {
            ignoreDozePref.setSummary(getString(R.string.main_ignore_battery_optimization_summary_already_ignored));
        } else {
            ignoreDozePref.setSummary(getString(R.string.main_ignore_battery_optimization_summary));
        }
    }
}
 
Example 8
Source File: SetupActivity.java    From SightRemote with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onResume() {
    super.onResume();
    if (viewPager.getCurrentItem() == 2) startBluetoothScan();
    else if (viewPager.getCurrentItem() == 1 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        if (powerManager.isIgnoringBatteryOptimizations(getPackageName())) {
            viewPager.setCurrentItem(2);
            startBluetoothScan();
        } else {
            finish();
        }
    }
}
 
Example 9
Source File: TrackingPresenter.java    From ridesharing-android with MIT License 5 votes vote down vote up
@SuppressWarnings("ConstantConditions")
public void requestIgnoreBatteryOptimizations() {
    PowerManager pm = (PowerManager) mContext.getSystemService(Activity.POWER_SERVICE);
    String packageName = mContext.getPackageName();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
            && !pm.isIgnoringBatteryOptimizations(packageName)
            && !InstantApps.isInstantApp(mContext)) {
        mView.requestPermissions(new String[]{Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS},
                PERMISSIONS_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
    }
}
 
Example 10
Source File: SystemUtils.java    From NetCloud_android with GNU General Public License v2.0 5 votes vote down vote up
public static boolean batteryOptimizing() {
    Context context = ContextMgr.getApplicationContext();
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        return !pm.isIgnoringBatteryOptimizations(context.getPackageName());
    }

    return false;
}
 
Example 11
Source File: MainActivity.java    From Locate-driver with GNU General Public License v3.0 5 votes vote down vote up
@RequiresApi(23)
private void enableAppInUltraPowerSavingMode() {
    Intent intent = new Intent();
    String packageName = getPackageName();
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    if (pm.isIgnoringBatteryOptimizations(packageName))
        intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
    else {
        intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
        intent.setData(Uri.parse("package:" + packageName));
    }
    startActivity(intent);
}
 
Example 12
Source File: MainSettingsActivity.java    From an2linuxclient with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onResume() {
    super.onResume();
    /*
    This is required if the user left the app but it's still running and the user uses the
    tile to change the setting and then reopens the app. Without this the checked state will
    be wrong. Without this it's required to unregister the listener below in onDestroy
    instead of onPause.
     */
    updateAn2linuxEnabled(PreferenceManager.getDefaultSharedPreferences(getActivity()));

    /*
    The listener: Preference.OnPreferenceChangeListener in onCreate does not notify updates
    from the quicksettings tile. For that this listener is required, if this is not used
    the state in the app will not be updated if the user changes the tile while the app
    is still running. It will only be updated after onDestroy / onCreate cycle.
     */
    PreferenceManager.getDefaultSharedPreferences(getActivity()).registerOnSharedPreferenceChangeListener(this);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        Preference ignoreDozePref = findPreference(getString(R.string.open_ignore_battery_optimization_settings_key));
        final PowerManager powerManager = (PowerManager) getContext().getSystemService(POWER_SERVICE);
        if (powerManager.isIgnoringBatteryOptimizations(getContext().getPackageName())) {
            ignoreDozePref.setSummary(getString(R.string.main_ignore_battery_optimization_summary_already_ignored));
        } else {
            ignoreDozePref.setSummary(getString(R.string.main_ignore_battery_optimization_summary));
        }
    }
}
 
Example 13
Source File: Util.java    From BackPackTrackII with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isOptimizingBattery(Context context) {
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        return !pm.isIgnoringBatteryOptimizations(context.getPackageName());
    else
        return false;
}
 
Example 14
Source File: Helper.java    From FairEmail with GNU General Public License v3.0 5 votes vote down vote up
static Boolean isIgnoringOptimizations(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (pm == null)
            return null;
        return pm.isIgnoringBatteryOptimizations(BuildConfig.APPLICATION_ID);
    }
    return null;
}
 
Example 15
Source File: PushServiceAccessibility.java    From MiPushFramework with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Check this app is in system doze whitelist.
 *
 * @param context Context param
 * @return is in whitelist, always true when pre-marshmallow
 */
@TargetApi(Build.VERSION_CODES.M)
public static boolean isInDozeWhiteList(Context context) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return true;
    }
    PowerManager powerManager = context.getSystemService(PowerManager.class);
    return powerManager.isIgnoringBatteryOptimizations(Constants.SERVICE_APP_NAME);
}
 
Example 16
Source File: Home.java    From NightWatch with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Fabric.with(this, new Crashlytics());
    prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    checkEula();
    new IdempotentMigrations(getApplicationContext()).performAll();

    startService(new Intent(getApplicationContext(), DataCollectionService.class));
    PreferenceManager.setDefaultValues(this, R.xml.pref_general, false);
    PreferenceManager.setDefaultValues(this, R.xml.pref_bg_notification, false);

    preferenceChangeListener = new OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            invalidateOptionsMenu();
        }
    };

    prefs.registerOnSharedPreferenceChangeListener(preferenceChangeListener);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        Intent intent = new Intent();
        String packageName = getPackageName();
        Log.d(this.getClass().getName(), "Maybe ignoring battery optimization");
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (!pm.isIgnoringBatteryOptimizations(packageName) &&
                !prefs.getBoolean("requested_ignore_battery_optimizations", false)) {
            Log.d(this.getClass().getName(), "Requesting ignore battery optimization");

            prefs.edit().putBoolean("requested_ignore_battery_optimizations", true).apply();
            intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + packageName));
            startActivity(intent);
        }
    }
}
 
Example 17
Source File: Log.java    From FairEmail with GNU General Public License v3.0 4 votes vote down vote up
private static StringBuilder getAppInfo(Context context) {
    StringBuilder sb = new StringBuilder();

    // Get version info
    String installer = context.getPackageManager().getInstallerPackageName(BuildConfig.APPLICATION_ID);
    sb.append(String.format("%s: %s/%s %s/%s%s%s%s\r\n",
            context.getString(R.string.app_name),
            BuildConfig.APPLICATION_ID,
            installer,
            BuildConfig.VERSION_NAME,
            Helper.hasValidFingerprint(context) ? "1" : "3",
            BuildConfig.PLAY_STORE_RELEASE ? "p" : "",
            BuildConfig.DEBUG ? "d" : "",
            ActivityBilling.isPro(context) ? "+" : ""));
    sb.append(String.format("Android: %s (SDK %d)\r\n", Build.VERSION.RELEASE, Build.VERSION.SDK_INT));
    sb.append("\r\n");

    // Get device info
    sb.append(String.format("uid: %s\r\n", android.os.Process.myUid()));
    sb.append(String.format("Brand: %s\r\n", Build.BRAND));
    sb.append(String.format("Manufacturer: %s\r\n", Build.MANUFACTURER));
    sb.append(String.format("Model: %s\r\n", Build.MODEL));
    sb.append(String.format("Product: %s\r\n", Build.PRODUCT));
    sb.append(String.format("Device: %s\r\n", Build.DEVICE));
    sb.append(String.format("Host: %s\r\n", Build.HOST));
    sb.append(String.format("Display: %s\r\n", Build.DISPLAY));
    sb.append(String.format("Id: %s\r\n", Build.ID));
    sb.append("\r\n");

    sb.append(String.format("Processors: %d\r\n", Runtime.getRuntime().availableProcessors()));

    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    sb.append(String.format("Memory class: %d\r\n", am.getMemoryClass()));

    sb.append(String.format("Storage space: %s/%s\r\n",
            Helper.humanReadableByteCount(Helper.getAvailableStorageSpace(), true),
            Helper.humanReadableByteCount(Helper.getTotalStorageSpace(), true)));

    Runtime rt = Runtime.getRuntime();
    long hused = (rt.totalMemory() - rt.freeMemory()) / 1024L;
    long hmax = rt.maxMemory() / 1024L;
    long nheap = Debug.getNativeHeapAllocatedSize() / 1024L;
    sb.append(String.format("Heap usage: %s/%s KiB native: %s KiB\r\n", hused, hmax, nheap));

    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    float density = context.getResources().getDisplayMetrics().density;
    sb.append(String.format("Density %f resolution: %.2f x %.2f dp %b\r\n",
            density,
            size.x / density, size.y / density,
            context.getResources().getConfiguration().isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_NORMAL)));

    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    boolean ignoring = true;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        ignoring = pm.isIgnoringBatteryOptimizations(BuildConfig.APPLICATION_ID);
    sb.append(String.format("Battery optimizations: %b\r\n", !ignoring));

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        UsageStatsManager usm = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
        int bucket = usm.getAppStandbyBucket();
        sb.append(String.format("Standby bucket: %d\r\n", bucket));
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        boolean saving = (cm.getRestrictBackgroundStatus() == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED);
        sb.append(String.format("Data saving: %b\r\n", saving));
    }

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean reporting = prefs.getBoolean("crash_reports", false);
    if (reporting) {
        String uuid = prefs.getString("uuid", null);
        sb.append(String.format("UUID: %s\r\n", uuid == null ? "-" : uuid));
    }

    sb.append("\r\n");

    sb.append(new Date(Helper.getInstallTime(context))).append("\r\n");
    sb.append(new Date()).append("\r\n");

    sb.append("\r\n");

    return sb;
}
 
Example 18
Source File: Util.java    From NetGuard with GNU General Public License v3.0 4 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
public static boolean batteryOptimizing(Context context) {
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    return !pm.isIgnoringBatteryOptimizations(context.getPackageName());
}
 
Example 19
Source File: ForegroundServiceContext.java    From android_packages_apps_GmsCore with Apache License 2.0 4 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.M)
private boolean isIgnoringBatteryOptimizations() {
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    return powerManager.isIgnoringBatteryOptimizations(getPackageName());
}
 
Example 20
Source File: Util.java    From kcanotify with GNU General Public License v3.0 4 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
public static boolean batteryOptimizing(Context context) {
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    return !pm.isIgnoringBatteryOptimizations(context.getPackageName());
}