Skip to content

Commit

Permalink
CW-572-Disable-battery-optimization (#1285)
Browse files Browse the repository at this point in the history
* feat: Disable battery optimization on android

* fix: Add permission to androidmanifestbase file

* Increase the frequency of app running in background on aggressive mode

* Revert the sync mode frequency [skip ci]

* Fix translation

* increase frequency to 1 hour

---------

Co-authored-by: OmarHatem <[email protected]>
  • Loading branch information
Blazebrain and OmarHatem28 authored Feb 8, 2024
1 parent 0832e62 commit d6e10bd
Show file tree
Hide file tree
Showing 33 changed files with 200 additions and 8 deletions.
1 change: 1 addition & 0 deletions android/app/src/main/AndroidManifestBase.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>

<application
android:name=".Application"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
import android.os.Handler;
import android.os.Looper;
import android.view.WindowManager;
import android.content.Intent;
import android.net.Uri;
import android.os.PowerManager;
import android.provider.Settings;

import com.unstoppabledomains.resolution.DomainResolution;
import com.unstoppabledomains.resolution.Resolution;
Expand Down Expand Up @@ -65,6 +69,14 @@ private void handle(@NonNull MethodCall call, @NonNull MethodChannel.Result resu
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
}
break;
case "disableBatteryOptimization":
disableBatteryOptimization();
handler.post(() -> result.success(null));
break;
case "isBatteryOptimizationDisabled":
boolean isDisabled = isBatteryOptimizationDisabled();
handler.post(() -> result.success(isDisabled));
break;
default:
handler.post(() -> result.notImplemented());
}
Expand All @@ -89,4 +101,22 @@ private void getUnstoppableDomainAddress(@NonNull MethodCall call, @NonNull Meth
}
});
}

private void disableBatteryOptimization() {
String packageName = getPackageName();
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
startActivity(intent);
}
}

private boolean isBatteryOptimizationDisabled() {
String packageName = getPackageName();
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
return pm.isIgnoringBatteryOptimizations(packageName);
}

}
30 changes: 30 additions & 0 deletions android/app/src/main/java/com/cakewallet/haven/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@
import android.os.Handler;
import android.os.Looper;
import android.view.WindowManager;
import android.content.Intent;
import android.net.Uri;
import android.os.PowerManager;
import android.provider.Settings;

import com.unstoppabledomains.resolution.DomainResolution;
import com.unstoppabledomains.resolution.Resolution;
Expand Down Expand Up @@ -55,6 +59,14 @@ private void handle(@NonNull MethodCall call, @NonNull MethodChannel.Result resu
handler.post(() -> result.success(""));
}
break;
case "disableBatteryOptimization":
disableBatteryOptimization();
handler.post(() -> result.success(null));
break;
case "isBatteryOptimizationDisabled":
boolean isDisabled = isBatteryOptimizationDisabled();
handler.post(() -> result.success(isDisabled));
break;
default:
handler.post(() -> result.notImplemented());
}
Expand All @@ -79,4 +91,22 @@ private void getUnstoppableDomainAddress(@NonNull MethodCall call, @NonNull Meth
}
});
}

private void disableBatteryOptimization() {
String packageName = getPackageName();
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
startActivity(intent);
}
}

private boolean isBatteryOptimizationDisabled() {
String packageName = getPackageName();
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
return pm.isIgnoringBatteryOptimizations(packageName);
}

}
30 changes: 30 additions & 0 deletions android/app/src/main/java/com/monero/app/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@
import android.os.Handler;
import android.os.Looper;
import android.view.WindowManager;
import android.content.Intent;
import android.net.Uri;
import android.os.PowerManager;
import android.provider.Settings;

import com.unstoppabledomains.resolution.DomainResolution;
import com.unstoppabledomains.resolution.Resolution;
Expand Down Expand Up @@ -64,6 +68,14 @@ private void handle(@NonNull MethodCall call, @NonNull MethodChannel.Result resu
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
}
break;
case "disableBatteryOptimization":
disableBatteryOptimization();
handler.post(() -> result.success(null));
break;
case "isBatteryOptimizationDisabled":
boolean isDisabled = isBatteryOptimizationDisabled();
handler.post(() -> result.success(isDisabled));
break;
default:
handler.post(() -> result.notImplemented());
}
Expand All @@ -88,4 +100,22 @@ private void getUnstoppableDomainAddress(@NonNull MethodCall call, @NonNull Meth
}
});
}

private void disableBatteryOptimization() {
String packageName = getPackageName();
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
startActivity(intent);
}
}

private boolean isBatteryOptimizationDisabled() {
String packageName = getPackageName();
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
return pm.isIgnoringBatteryOptimizations(packageName);
}

}
22 changes: 22 additions & 0 deletions cw_core/lib/battery_optimization_native.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import 'package:flutter/services.dart';

const MethodChannel _channel = MethodChannel('com.cake_wallet/native_utils');

Future<void> requestDisableBatteryOptimization() async {
try {
await _channel.invokeMethod('disableBatteryOptimization');
} on PlatformException catch (e) {
print("Failed to disable battery optimization: '${e.message}'.");
}
}

Future<bool> isBatteryOptimizationDisabled() async {
try {
final bool isDisabled = await _channel.invokeMethod('isBatteryOptimizationDisabled') as bool;
print('It\'s actually disabled? $isDisabled');
return isDisabled;
} on PlatformException catch (e) {
print("Failed to check battery optimization status: '${e.message}'.");
return false;
}
}
41 changes: 34 additions & 7 deletions lib/src/screens/settings/connection_sync_page.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:io';

import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/src/screens/settings/widgets/settings_cell_with_arrow.dart';
import 'package:cake_wallet/src/screens/settings/widgets/settings_picker_cell.dart';
Expand All @@ -8,6 +10,7 @@ import 'package:cake_wallet/utils/feature_flag.dart';
import 'package:cake_wallet/utils/show_pop_up.dart';
import 'package:cake_wallet/view_model/dashboard/dashboard_view_model.dart';
import 'package:cake_wallet/view_model/settings/sync_mode.dart';
import 'package:cw_core/battery_optimization_native.dart';
import 'package:flutter/material.dart';
import 'package:cake_wallet/routes.dart';
import 'package:cake_wallet/generated/i18n.dart';
Expand Down Expand Up @@ -45,12 +48,37 @@ class ConnectionSyncPage extends BasePage {
if (DeviceInfo.instance.isMobile) ...[
Observer(builder: (context) {
return SettingsPickerCell<SyncMode>(
title: S.current.background_sync_mode,
items: SyncMode.all,
displayItem: (SyncMode syncMode) => syncMode.name,
selectedItem: dashboardViewModel.syncMode,
onItemSelected: dashboardViewModel.setSyncMode,
);
title: S.current.background_sync_mode,
items: SyncMode.all,
displayItem: (SyncMode syncMode) => syncMode.name,
selectedItem: dashboardViewModel.syncMode,
onItemSelected: (syncMode) async {
dashboardViewModel.setSyncMode(syncMode);

if (syncMode.type != SyncType.disabled) {
final isDisabled = await isBatteryOptimizationDisabled();

if (isDisabled || Platform.isIOS) return;

await showPopUp<void>(
context: context,
builder: (BuildContext dialogContext) {
return AlertWithTwoActions(
alertTitle: S.current.disableBatteryOptimization,
alertContent: S.current.disableBatteryOptimizationDescription,
leftButtonText: S.of(context).cancel,
rightButtonText: S.of(context).ok,
actionLeftButton: () => Navigator.of(dialogContext).pop(),
actionRightButton: () async {
await requestDisableBatteryOptimization();

Navigator.of(dialogContext).pop();
},
);
},
);
}
});
}),
const StandardListSeparator(padding: EdgeInsets.symmetric(horizontal: 24)),
Observer(builder: (context) {
Expand Down Expand Up @@ -99,7 +127,6 @@ class ConnectionSyncPage extends BasePage {
);
}


Future<void> _presentReconnectAlert(BuildContext context) async {
await showPopUp<void>(
context: context,
Expand Down
2 changes: 1 addition & 1 deletion lib/view_model/settings/sync_mode.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ class SyncMode {
static final all = [
SyncMode("Disabled", SyncType.disabled, Duration.zero),
SyncMode("Unobtrusive", SyncType.unobtrusive, Duration(days: 1)),
SyncMode("Aggressive", SyncType.aggressive, Duration(hours: 6)),
SyncMode("Aggressive", SyncType.aggressive, Duration(hours: 1)),
];
}
2 changes: 2 additions & 0 deletions res/values/strings_ar.arb
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@
"disable_exchange": "تعطيل التبادل",
"disable_fiat": "تعطيل fiat",
"disable_sell": "قم بتعطيل إجراء البيع",
"disableBatteryOptimization": "تعطيل تحسين البطارية",
"disableBatteryOptimizationDescription": "هل تريد تعطيل تحسين البطارية من أجل جعل الخلفية مزامنة تعمل بحرية وسلاسة؟",
"disabled": "معطلة",
"discount": "وفر ${value}٪",
"display_settings": "اعدادات العرض",
Expand Down
2 changes: 2 additions & 0 deletions res/values/strings_bg.arb
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@
"disable_exchange": "Деактивиране на борса",
"disable_fiat": "Деактивиране на fiat",
"disable_sell": "Деактивирайте действието за продажба",
"disableBatteryOptimization": "Деактивирайте оптимизацията на батерията",
"disableBatteryOptimizationDescription": "Искате ли да деактивирате оптимизацията на батерията, за да направите синхронизирането на фона да работи по -свободно и гладко?",
"disabled": "Деактивирано",
"discount": "Спестете ${value}%",
"display_settings": "Настройки на екрана",
Expand Down
2 changes: 2 additions & 0 deletions res/values/strings_cs.arb
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@
"disable_exchange": "Zakázat směnárny",
"disable_fiat": "Zakázat fiat",
"disable_sell": "Zakázat akci prodeje",
"disableBatteryOptimization": "Zakázat optimalizaci baterie",
"disableBatteryOptimizationDescription": "Chcete deaktivovat optimalizaci baterie, aby se synchronizovala pozadí volně a hladce?",
"disabled": "Zakázáno",
"discount": "Ušetříte ${value}%",
"display_settings": "Nastavení zobrazení",
Expand Down
2 changes: 2 additions & 0 deletions res/values/strings_de.arb
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@
"disable_exchange": "Exchange deaktivieren",
"disable_fiat": "Fiat deaktivieren",
"disable_sell": "Verkaufsaktion deaktivieren",
"disableBatteryOptimization": "Batterieoptimierung deaktivieren",
"disableBatteryOptimizationDescription": "Möchten Sie die Batterieoptimierung deaktivieren, um die Hintergrundsynchronisierung freier und reibungsloser zu gestalten?",
"disabled": "Deaktiviert",
"discount": "${value} % sparen",
"display_settings": "Anzeigeeinstellungen",
Expand Down
2 changes: 2 additions & 0 deletions res/values/strings_en.arb
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@
"disable_exchange": "Disable exchange",
"disable_fiat": "Disable fiat",
"disable_sell": "Disable sell action",
"disableBatteryOptimization": "Disable Battery Optimization",
"disableBatteryOptimizationDescription": "Do you want to disable battery optimization in order to make background sync run more freely and smoothly?",
"disabled": "Disabled",
"discount": "Save ${value}%",
"display_settings": "Display settings",
Expand Down
2 changes: 2 additions & 0 deletions res/values/strings_es.arb
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@
"disable_exchange": "Deshabilitar intercambio",
"disable_fiat": "Deshabilitar fiat",
"disable_sell": "Desactivar acción de venta",
"disableBatteryOptimization": "Deshabilitar la optimización de la batería",
"disableBatteryOptimizationDescription": "¿Desea deshabilitar la optimización de la batería para que la sincronización de fondo se ejecute más libremente y sin problemas?",
"disabled": "Desactivado",
"discount": "Ahorra ${value}%",
"display_settings": "Configuración de pantalla",
Expand Down
2 changes: 2 additions & 0 deletions res/values/strings_fr.arb
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@
"disable_exchange": "Désactiver l'échange",
"disable_fiat": "Désactiver les montants en fiat",
"disable_sell": "Désactiver l'action de vente",
"disableBatteryOptimization": "Désactiver l'optimisation de la batterie",
"disableBatteryOptimizationDescription": "Voulez-vous désactiver l'optimisation de la batterie afin de faire fonctionner la synchronisation d'arrière-plan plus librement et en douceur?",
"disabled": "Désactivé",
"discount": "Économisez ${value}%",
"display_settings": "Paramètres d'affichage",
Expand Down
2 changes: 2 additions & 0 deletions res/values/strings_ha.arb
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@
"disable_exchange": "Kashe musanya",
"disable_fiat": "Dakatar da fiat",
"disable_sell": "Kashe karbuwa",
"disableBatteryOptimization": "Kashe ingantawa baturi",
"disableBatteryOptimizationDescription": "Shin kana son kashe ingantawa baturi don yin setnc bankwali gudu da yar kyauta da kyau?",
"disabled": "tsaya",
"discount": "Ajiye ${value}%",
"display_settings": "Nuni saituna",
Expand Down
2 changes: 2 additions & 0 deletions res/values/strings_hi.arb
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@
"disable_exchange": "एक्सचेंज अक्षम करें",
"disable_fiat": "िएट को अक्षम करें",
"disable_sell": "बेचने की कार्रवाई अक्षम करें",
"disableBatteryOptimization": "बैटरी अनुकूलन अक्षम करें",
"disableBatteryOptimizationDescription": "क्या आप बैकग्राउंड सिंक को अधिक स्वतंत्र और सुचारू रूप से चलाने के लिए बैटरी ऑप्टिमाइज़ेशन को अक्षम करना चाहते हैं?",
"disabled": "अक्षम",
"discount": "${value}% बचाएं",
"display_settings": "प्रदर्शन सेटिंग्स",
Expand Down
2 changes: 2 additions & 0 deletions res/values/strings_hr.arb
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@
"disable_exchange": "Onemogući exchange",
"disable_fiat": "Isključi, fiat",
"disable_sell": "Onemogući akciju prodaje",
"disableBatteryOptimization": "Onemogući optimizaciju baterije",
"disableBatteryOptimizationDescription": "Želite li onemogućiti optimizaciju baterije kako bi se pozadinska sinkronizacija radila slobodnije i glatko?",
"disabled": "Onemogućeno",
"discount": "Uštedite ${value}%",
"display_settings": "Postavke zaslona",
Expand Down
2 changes: 2 additions & 0 deletions res/values/strings_id.arb
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@
"disable_exchange": "Nonaktifkan pertukaran",
"disable_fiat": "Nonaktifkan fiat",
"disable_sell": "Nonaktifkan aksi jual",
"disableBatteryOptimization": "Nonaktifkan optimasi baterai",
"disableBatteryOptimizationDescription": "Apakah Anda ingin menonaktifkan optimasi baterai untuk membuat sinkronisasi latar belakang berjalan lebih bebas dan lancar?",
"disabled": "Dinonaktifkan",
"discount": "Hemat ${value}%",
"display_settings": "Pengaturan tampilan",
Expand Down
2 changes: 2 additions & 0 deletions res/values/strings_it.arb
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,8 @@
"disable_exchange": "Disabilita scambio",
"disable_fiat": "Disabilita fiat",
"disable_sell": "Disabilita l'azione di vendita",
"disableBatteryOptimization": "Disabilita l'ottimizzazione della batteria",
"disableBatteryOptimizationDescription": "Vuoi disabilitare l'ottimizzazione della batteria per far funzionare la sincronizzazione in background più libera e senza intoppi?",
"disabled": "Disabilitato",
"discount": "Risparmia ${value}%",
"display_settings": "Impostazioni di visualizzazione",
Expand Down
2 changes: 2 additions & 0 deletions res/values/strings_ja.arb
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@
"disable_exchange": "交換を無効にする",
"disable_fiat": "フィアットを無効にする",
"disable_sell": "販売アクションを無効にする",
"disableBatteryOptimization": "バッテリーの最適化を無効にします",
"disableBatteryOptimizationDescription": "バックグラウンドシンクをより自由かつスムーズに実行するために、バッテリーの最適化を無効にしたいですか?",
"disabled": "無効",
"discount": "${value}%を節約",
"display_settings": "表示設定",
Expand Down
2 changes: 2 additions & 0 deletions res/values/strings_ko.arb
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@
"disable_exchange": "교환 비활성화",
"disable_fiat": "법정화폐 비활성화",
"disable_sell": "판매 조치 비활성화",
"disableBatteryOptimization": "배터리 최적화를 비활성화합니다",
"disableBatteryOptimizationDescription": "백그라운드 동기화를보다 자유롭고 매끄럽게 실행하기 위해 배터리 최적화를 비활성화하고 싶습니까?",
"disabled": "장애가 있는",
"discount": "${value}% 절약",
"display_settings": "디스플레이 설정",
Expand Down
2 changes: 2 additions & 0 deletions res/values/strings_my.arb
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@
"disable_exchange": "လဲလှယ်မှုကို ပိတ်ပါ။",
"disable_fiat": "Fiat ကိုပိတ်ပါ။",
"disable_sell": "ရောင်းချခြင်းလုပ်ဆောင်ချက်ကို ပိတ်ပါ။",
"disableBatteryOptimization": "ဘက်ထရီ optimization ကိုပိတ်ပါ",
"disableBatteryOptimizationDescription": "နောက်ခံထပ်တူပြုခြင်းနှင့်ချောချောမွေ့မွေ့ပြုလုပ်နိုင်ရန်ဘက်ထရီ optimization ကိုသင်ပိတ်ထားလိုပါသလား။",
"disabled": "မသန်စွမ်း",
"discount": "${value}% ချွေတာ",
"display_settings": "ပြသရန် ဆက်တင်များ",
Expand Down
2 changes: 2 additions & 0 deletions res/values/strings_nl.arb
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@
"disable_exchange": "Uitwisseling uitschakelen",
"disable_fiat": "Schakel Fiat uit",
"disable_sell": "Verkoopactie uitschakelen",
"disableBatteryOptimization": "Schakel de batterijoptimalisatie uit",
"disableBatteryOptimizationDescription": "Wilt u de optimalisatie van de batterij uitschakelen om achtergrondsynchronisatie te laten werken, vrijer en soepeler?",
"disabled": "Gehandicapt",
"discount": "Bespaar ${value}%",
"display_settings": "Weergave-instellingen",
Expand Down
Loading

0 comments on commit d6e10bd

Please sign in to comment.