UI: Move advanced GCM configuration get/set off ui process

This commit is contained in:
Marvin W 2020-12-20 19:29:33 +01:00
parent 8b49b05585
commit c648883128
No known key found for this signature in database
GPG Key ID: 072E9235DB996F2A
7 changed files with 209 additions and 134 deletions

View File

@ -54,7 +54,6 @@ public class GcmPrefs implements SharedPreferences.OnSharedPreferenceChangeListe
public static GcmPrefs get(Context context) {
if (INSTANCE == null) {
PackageUtils.warnIfNotPersistentProcess(GcmPrefs.class);
if (context == null) return new GcmPrefs(null);
INSTANCE = new GcmPrefs(context.getApplicationContext());
}
return INSTANCE;
@ -74,19 +73,19 @@ public class GcmPrefs implements SharedPreferences.OnSharedPreferenceChangeListe
private int learntMobile = 300000;
private int learntOther = 300000;
private final Context context;
private SharedPreferences preferences;
private SharedPreferences systemDefaultPreferences;
private GcmPrefs(Context context) {
if (context != null) {
preferences = PreferenceManager.getDefaultSharedPreferences(context);
preferences.registerOnSharedPreferenceChangeListener(this);
try {
systemDefaultPreferences = (SharedPreferences) Context.class.getDeclaredMethod("getSharedPreferences", File.class, int.class).invoke(context, new File("/system/etc/microg.xml"), Context.MODE_PRIVATE);
} catch (Exception ignored) {
}
update();
this.context = context;
preferences = PreferenceManager.getDefaultSharedPreferences(context);
preferences.registerOnSharedPreferenceChangeListener(this);
try {
systemDefaultPreferences = (SharedPreferences) Context.class.getDeclaredMethod("getSharedPreferences", File.class, int.class).invoke(context, new File("/system/etc/microg.xml"), Context.MODE_PRIVATE);
} catch (Exception ignored) {
}
update();
}
private boolean getSettingsBoolean(String key, boolean def) {
@ -127,12 +126,49 @@ public class GcmPrefs implements SharedPreferences.OnSharedPreferenceChangeListe
}
public int getHeartbeatMsFor(NetworkInfo info) {
return getHeartbeatMsFor(getNetworkPrefForInfo(info), false);
return getHeartbeatMsFor(getNetworkPrefForInfo(info));
}
public int getHeartbeatMsFor(String pref, boolean rawRoaming) {
if (PREF_NETWORK_ROAMING.equals(pref) && (rawRoaming || networkRoaming != 0)) {
return networkRoaming * 60000;
public int getMobileInterval() {
return networkMobile;
}
public int getWifiInterval() {
return networkWifi;
}
public int getRoamingInterval() {
return networkRoaming;
}
public int getOtherInterval() {
return networkOther;
}
public void setMobileInterval(int value) {
this.networkMobile = value;
preferences.edit().putString(PREF_NETWORK_MOBILE, Integer.toString(networkMobile)).apply();
}
public void setWifiInterval(int value) {
this.networkWifi = value;
preferences.edit().putString(PREF_NETWORK_WIFI, Integer.toString(networkWifi)).apply();
}
public void setRoamingInterval(int value) {
this.networkRoaming = value;
preferences.edit().putString(PREF_NETWORK_ROAMING, Integer.toString(networkRoaming)).apply();
}
public void setOtherInterval(int value) {
this.networkOther = value;
preferences.edit().putString(PREF_NETWORK_OTHER, Integer.toString(networkOther)).apply();
}
public int getHeartbeatMsFor(String pref) {
if (PREF_NETWORK_ROAMING.equals(pref)) {
if (networkRoaming != 0) return networkRoaming * 60000;
else return learntMobile;
} else if (PREF_NETWORK_MOBILE.equals(pref)) {
if (networkMobile != 0) return networkMobile * 60000;
else return learntMobile;
@ -202,6 +238,18 @@ public class GcmPrefs implements SharedPreferences.OnSharedPreferenceChangeListe
preferences.edit().putInt(PREF_LEARNT_MOBILE, learntMobile).putInt(PREF_LEARNT_WIFI, learntWifi).putInt(PREF_LEARNT_OTHER, learntOther).apply();
}
public int getLearntMobileInterval() {
return learntMobile;
}
public int getLearntWifiInterval() {
return learntWifi;
}
public int getLearntOtherInterval() {
return learntOther;
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
update();
@ -211,21 +259,21 @@ public class GcmPrefs implements SharedPreferences.OnSharedPreferenceChangeListe
return gcmEnabled;
}
public boolean isEnabledFor(NetworkInfo info) {
return isEnabled() && info != null && getHeartbeatMsFor(info) >= 0;
}
public static void setEnabled(Context context, boolean newStatus) {
boolean changed = GcmPrefs.get(context).isEnabled() != newStatus;
PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(GcmPrefs.PREF_ENABLE_GCM, newStatus).commit();
public void setEnabled(boolean value) {
boolean changed = gcmEnabled != value;
preferences.edit().putBoolean(GcmPrefs.PREF_ENABLE_GCM, value).apply();
if (!changed) return;
if (!newStatus) {
if (!value) {
McsService.stop(context);
} else {
context.sendBroadcast(new Intent(TriggerReceiver.FORCE_TRY_RECONNECT, null, context, TriggerReceiver.class));
}
}
public boolean isEnabledFor(NetworkInfo info) {
return isEnabled() && info != null && getHeartbeatMsFor(info) >= 0;
}
public boolean isGcmLogEnabled() {
return gcmLogEnabled;
}
@ -234,6 +282,11 @@ public class GcmPrefs implements SharedPreferences.OnSharedPreferenceChangeListe
return confirmNewApps;
}
public void setConfirmNewApps(boolean value) {
confirmNewApps = value;
preferences.edit().putBoolean(PREF_CONFIRM_NEW_APPS, value).apply();
}
public List<String> getLastPersistedIds() {
if (lastPersistedId.isEmpty()) return Collections.emptyList();
return Arrays.asList(lastPersistedId.split("\\|"));

View File

@ -17,9 +17,6 @@
package org.microg.gms.gcm;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
@ -41,7 +38,6 @@ import android.os.SystemClock;
import android.os.UserHandle;
import android.util.Log;
import androidx.annotation.RequiresApi;
import androidx.legacy.content.WakefulBroadcastReceiver;
import com.squareup.wire.Message;
@ -75,7 +71,6 @@ import okio.ByteString;
import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
import static android.os.Build.VERSION.SDK_INT;
import static org.microg.gms.common.ForegroundServiceContext.EXTRA_FOREGROUND;
import static org.microg.gms.gcm.GcmConstants.ACTION_C2DM_RECEIVE;
import static org.microg.gms.gcm.GcmConstants.EXTRA_APP;
import static org.microg.gms.gcm.GcmConstants.EXTRA_APP_OVERRIDE;
@ -241,7 +236,7 @@ public class McsService extends Service implements Handler.Callback {
return false;
}
// consider connection to be dead if we did not receive an ack within twice the heartbeat interval
int heartbeatMs = GcmPrefs.get(context).getHeartbeatMsFor(activeNetworkPref, false);
int heartbeatMs = GcmPrefs.get(context).getHeartbeatMsFor(activeNetworkPref);
if (heartbeatMs < 0) {
closeAll();
} else if (SystemClock.elapsedRealtime() - lastHeartbeatAckElapsedRealtime > 2 * heartbeatMs) {
@ -271,7 +266,7 @@ public class McsService extends Service implements Handler.Callback {
public void scheduleHeartbeat(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
int heartbeatMs = GcmPrefs.get(this).getHeartbeatMsFor(activeNetworkPref, false);
int heartbeatMs = GcmPrefs.get(this).getHeartbeatMsFor(activeNetworkPref);
if (heartbeatMs < 0) {
closeAll();
}

View File

@ -1,97 +0,0 @@
/*
* Copyright (C) 2017 microG Project Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.microg.gms.ui;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.preference.Preference;
import com.google.android.gms.R;
import org.microg.gms.gcm.GcmPrefs;
import org.microg.gms.gcm.McsService;
import org.microg.gms.gcm.TriggerReceiver;
import org.microg.tools.ui.AbstractSettingsActivity;
import org.microg.tools.ui.ResourceSettingsFragment;
import java.util.Objects;
public class GcmAdvancedFragment extends ResourceSettingsFragment {
private static String[] HEARTBEAT_PREFS = new String[]{GcmPrefs.PREF_NETWORK_MOBILE, GcmPrefs.PREF_NETWORK_ROAMING, GcmPrefs.PREF_NETWORK_WIFI, GcmPrefs.PREF_NETWORK_OTHER};
public GcmAdvancedFragment() {
preferencesResource = R.xml.preferences_gcm_advanced;
}
@Override
public void onCreatePreferences(@Nullable Bundle savedInstanceState, String rootKey) {
super.onCreatePreferences(savedInstanceState, rootKey);
for (String pref : HEARTBEAT_PREFS) {
findPreference(pref).setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
getPreferenceManager().getSharedPreferences().edit().putString(preference.getKey(), (String) newValue).apply();
updateContent();
if (newValue.equals("-1") && preference.getKey().equals(McsService.activeNetworkPref)) {
McsService.stop(getContext());
} else if (!McsService.isConnected(getContext())) {
getContext().sendBroadcast(new Intent(TriggerReceiver.FORCE_TRY_RECONNECT, null, getContext(), TriggerReceiver.class));
}
return true;
}
});
}
updateContent();
}
@Override
public void onResume() {
super.onResume();
updateContent();
}
private void updateContent() {
GcmPrefs prefs = GcmPrefs.get(getContext());
for (String pref : HEARTBEAT_PREFS) {
Preference preference = findPreference(pref);
int state = prefs.getNetworkValue(pref);
if (state == 0) {
int heartbeat = prefs.getHeartbeatMsFor(preference.getKey(), true);
if (heartbeat == 0) {
preference.setSummary("ON / Automatic");
} else {
preference.setSummary("ON / Automatic: " + getHeartbeatString(heartbeat));
}
} else if (state == -1) {
preference.setSummary("OFF");
} else {
preference.setSummary("ON / Manual: " + getHeartbeatString(state * 60000));
}
}
}
private String getHeartbeatString(int heartbeatMs) {
if (heartbeatMs < 120000) {
return (heartbeatMs / 1000) + " seconds";
}
return (heartbeatMs / 60000) + " minutes";
}
}

View File

@ -22,23 +22,29 @@ private const val EXTRA_SERVICE_INFO = "org.microg.gms.gcm.SERVICE_INFO"
private const val EXTRA_CONFIGURATION = "org.microg.gms.gcm.CONFIGURATION"
private const val TAG = "GmsGcmStatusInfo"
data class ServiceInfo(val configuration: ServiceConfiguration, val connected: Boolean, val startTimestamp: Long) : Serializable
data class ServiceInfo(val configuration: ServiceConfiguration, val connected: Boolean, val startTimestamp: Long, val learntMobileInterval: Int, val learntWifiInterval: Int, val learntOtherInterval: Int) : Serializable
// TODO: Intervals
data class ServiceConfiguration(val enabled: Boolean, val confirmNewApps: Boolean) : Serializable {
data class ServiceConfiguration(val enabled: Boolean, val confirmNewApps: Boolean, val mobile: Int, val wifi: Int, val roaming: Int, val other: Int) : Serializable {
fun saveToPrefs(context: Context) {
GcmPrefs.setEnabled(context, enabled)
// TODO: confirm new apps
GcmPrefs.get(context).apply {
isEnabled = enabled
isConfirmNewApps = confirmNewApps
mobileInterval = mobile
wifiInterval = wifi
roamingInterval = roaming
otherInterval = other
}
}
}
private fun GcmPrefs.toConfiguration(): ServiceConfiguration = ServiceConfiguration(isEnabled, isConfirmNewApps)
private fun GcmPrefs.toConfiguration(): ServiceConfiguration = ServiceConfiguration(isEnabled, isConfirmNewApps, mobileInterval, wifiInterval, roamingInterval, otherInterval)
class ServiceInfoReceiver : BroadcastReceiver() {
private fun sendInfoResponse(context: Context) {
context.sendOrderedBroadcast(Intent(ACTION_SERVICE_INFO_RESPONSE).apply {
setPackage(context.packageName)
putExtra(EXTRA_SERVICE_INFO, ServiceInfo(GcmPrefs.get(context).toConfiguration(), McsService.isConnected(context), McsService.getStartTimestamp()))
val prefs = GcmPrefs.get(context)
putExtra(EXTRA_SERVICE_INFO, ServiceInfo(prefs.toConfiguration(), McsService.isConnected(context), McsService.getStartTimestamp(), prefs.learntMobileInterval, prefs.learntWifiInterval, prefs.learntOtherInterval))
}, null)
}

View File

@ -14,6 +14,8 @@ import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.delay
import org.microg.gms.checkin.CheckinPrefs
import org.microg.gms.gcm.GcmPrefs
import org.microg.gms.gcm.getGcmServiceInfo
import org.microg.gms.gcm.setGcmServiceConfiguration
import org.microg.gms.snet.SafetyNetPrefs
class ProvisionService : LifecycleService() {
@ -30,7 +32,7 @@ class ProvisionService : LifecycleService() {
}
intent?.extras?.getBooleanOrNull("checkin_enabled")?.let { CheckinPrefs.setEnabled(this@ProvisionService, it) }
intent?.extras?.getBooleanOrNull("gcm_enabled")?.let { GcmPrefs.setEnabled(this@ProvisionService, it) }
intent?.extras?.getBooleanOrNull("gcm_enabled")?.let { setGcmServiceConfiguration(this@ProvisionService, getGcmServiceInfo(this@ProvisionService).configuration.copy(enabled = it)) }
intent?.extras?.getBooleanOrNull("safetynet_enabled")?.let { SafetyNetPrefs.get(this@ProvisionService).isEnabled = it }
// What else?

View File

@ -0,0 +1,116 @@
/*
* SPDX-FileCopyrightText: 2020, microG Project Team
* SPDX-License-Identifier: Apache-2.0
*/
package org.microg.gms.ui
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import androidx.preference.ListPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.TwoStatePreference
import com.google.android.gms.R
import org.microg.gms.gcm.*
class PushNotificationAdvancedFragment : PreferenceFragmentCompat() {
private lateinit var confirmNewApps: TwoStatePreference
private lateinit var networkMobile: ListPreference
private lateinit var networkWifi: ListPreference
private lateinit var networkRoaming: ListPreference
private lateinit var networkOther: ListPreference
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.preferences_gcm_advanced)
}
override fun onBindPreferences() {
confirmNewApps = preferenceScreen.findPreference(GcmPrefs.PREF_CONFIRM_NEW_APPS) ?: confirmNewApps
networkMobile = preferenceScreen.findPreference(GcmPrefs.PREF_NETWORK_MOBILE) ?: networkMobile
networkWifi = preferenceScreen.findPreference(GcmPrefs.PREF_NETWORK_WIFI) ?: networkWifi
networkRoaming = preferenceScreen.findPreference(GcmPrefs.PREF_NETWORK_ROAMING) ?: networkRoaming
networkOther = preferenceScreen.findPreference(GcmPrefs.PREF_NETWORK_OTHER) ?: networkOther
confirmNewApps.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
lifecycleScope.launchWhenResumed {
if (newValue is Boolean) {
setGcmServiceConfiguration(requireContext(), getGcmServiceInfo(requireContext()).configuration.copy(confirmNewApps = newValue))
}
updateContent()
}
true
}
networkMobile.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
lifecycleScope.launchWhenResumed {
(newValue as? String)?.toIntOrNull()?.let {
setGcmServiceConfiguration(requireContext(), getGcmServiceInfo(requireContext()).configuration.copy(mobile = it))
}
updateContent()
}
true
}
networkWifi.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
lifecycleScope.launchWhenResumed {
(newValue as? String)?.toIntOrNull()?.let {
setGcmServiceConfiguration(requireContext(), getGcmServiceInfo(requireContext()).configuration.copy(wifi = it))
}
updateContent()
}
true
}
networkRoaming.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
lifecycleScope.launchWhenResumed {
(newValue as? String)?.toIntOrNull()?.let {
setGcmServiceConfiguration(requireContext(), getGcmServiceInfo(requireContext()).configuration.copy(roaming = it))
}
updateContent()
}
true
}
networkOther.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
lifecycleScope.launchWhenResumed {
(newValue as? String)?.toIntOrNull()?.let {
setGcmServiceConfiguration(requireContext(), getGcmServiceInfo(requireContext()).configuration.copy(other = it))
}
updateContent()
}
true
}
}
override fun onResume() {
super.onResume()
updateContent()
}
private fun updateContent() {
lifecycleScope.launchWhenResumed {
val serviceInfo = getGcmServiceInfo(requireContext())
confirmNewApps.isChecked = serviceInfo.configuration.confirmNewApps
networkMobile.value = serviceInfo.configuration.mobile.toString()
networkMobile.summary = getSummaryString(serviceInfo.configuration.mobile, serviceInfo.learntMobileInterval)
networkWifi.value = serviceInfo.configuration.wifi.toString()
networkWifi.summary = getSummaryString(serviceInfo.configuration.wifi, serviceInfo.learntWifiInterval)
networkRoaming.value = serviceInfo.configuration.roaming.toString()
networkRoaming.summary = getSummaryString(serviceInfo.configuration.roaming, serviceInfo.learntMobileInterval)
networkOther.value = serviceInfo.configuration.other.toString()
networkOther.summary = getSummaryString(serviceInfo.configuration.other, serviceInfo.learntOtherInterval)
}
}
private fun getSummaryString(value: Int, learnt: Int): String = when (value) {
-1 -> "OFF"
0 -> "ON / Automatic: " + getHeartbeatString(learnt)
else -> "ON / Manual: " + getHeartbeatString(value * 60000)
}
private fun getHeartbeatString(heartbeatMs: Int): String {
return if (heartbeatMs < 120000) {
(heartbeatMs / 1000).toString() + " seconds"
} else (heartbeatMs / 60000).toString() + " minutes"
}
companion object {
private val HEARTBEAT_PREFS = arrayOf(GcmPrefs.PREF_NETWORK_MOBILE, GcmPrefs.PREF_NETWORK_ROAMING, GcmPrefs.PREF_NETWORK_WIFI, GcmPrefs.PREF_NETWORK_OTHER)
}
}

View File

@ -78,7 +78,7 @@
</fragment>
<fragment
android:id="@+id/gcmAdvancedFragment"
android:name="org.microg.gms.ui.GcmAdvancedFragment"
android:name="org.microg.gms.ui.PushNotificationAdvancedFragment"
android:label="@string/service_name_mcs" />
<fragment
android:id="@+id/safetyNetFragment"