Add settings screen

Thanks to an anonymous contributor
This commit is contained in:
xynngh 2020-05-16 19:44:55 +04:00
parent 7a59f59e6a
commit 1d80f22bc9
12 changed files with 218 additions and 8 deletions

View File

@ -42,6 +42,7 @@ dependencies {
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'com.google.android.material:material:1.1.0'
implementation 'androidx.preference:preference:1.1.1'
implementation 'androidx.work:work-runtime:2.3.4'
implementation "org.greenrobot:eventbus:$eventbus_version"
annotationProcessor "org.greenrobot:eventbus-annotation-processor:$eventbus_version"

View File

@ -29,6 +29,13 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SettingsActivity"
android:label="@string/title_settings_activity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
</activity>
<activity
android:name=".DebugActivity"
android:label="@string/debug_activity_label" />

View File

@ -1,5 +1,6 @@
package dummydomain.yetanothercallblocker;
import android.annotation.SuppressLint;
import android.app.Application;
import org.greenrobot.eventbus.EventBus;
@ -10,6 +11,7 @@ public class App extends Application {
private static App instance;
@SuppressLint("StaticFieldLeak")
private static Settings settings;
@Override
@ -19,6 +21,7 @@ public class App extends Application {
instance = this;
settings = new Settings(this);
settings.init();
EventBus.builder()
.throwSubscriberException(BuildConfig.DEBUG)

View File

@ -5,13 +5,15 @@ import android.content.SharedPreferences;
public class GenericSettings {
protected final Context context;
protected final SharedPreferences pref;
public GenericSettings(Context context, String name) {
this(context.getSharedPreferences(name, Context.MODE_PRIVATE));
this(context, context.getSharedPreferences(name, Context.MODE_PRIVATE));
}
public GenericSettings(SharedPreferences pref) {
public GenericSettings(Context context, SharedPreferences pref) {
this.context = context;
this.pref = pref;
}
@ -43,4 +45,8 @@ public class GenericSettings {
pref.edit().putLong(key, value).apply();
}
public boolean isSet(String key) {
return pref.contains(key);
}
}

View File

@ -196,6 +196,10 @@ public class MainActivity extends AppCompatActivity {
loadCallLog();
}
public void onOpenSettings(MenuItem item) {
startActivity(new Intent(this, SettingsActivity.class));
}
public void onOpenDebugActivity(MenuItem item) {
startActivity(new Intent(this, DebugActivity.class));
}

View File

@ -2,16 +2,52 @@ package dummydomain.yetanothercallblocker;
import android.content.Context;
import androidx.preference.PreferenceManager;
public class Settings extends GenericSettings {
private static final String PREF_INCOMING_CALL_NOTIFICATIONS = "incomingCallNotifications";
private static final String PREF_BLOCK_CALLS = "blockCalls";
private static final String PREF_USE_CONTACTS = "useContacts";
private static final String PREF_LAST_UPDATE_TIME = "lastUpdateTime";
private static final String PREF_LAST_UPDATE_CHECK_TIME = "lastUpdateCheckTime";
public static final String PREF_INCOMING_CALL_NOTIFICATIONS = "incomingCallNotifications";
public static final String PREF_BLOCK_CALLS = "blockCalls";
public static final String PREF_USE_CONTACTS = "useContacts";
public static final String PREF_LAST_UPDATE_TIME = "lastUpdateTime";
public static final String PREF_LAST_UPDATE_CHECK_TIME = "lastUpdateCheckTime";
private static final String SYS_PREFERENCES_VERSION = "__preferencesVersion";
private static final int PREFERENCES_VERSION = 1;
Settings(Context context) {
super(context, "yacb_preferences");
super(context, PreferenceManager.getDefaultSharedPreferences(context));
}
private Settings(Context context, String name) {
super(context, name);
}
public void init() {
int preferencesVersion = getInt(SYS_PREFERENCES_VERSION, -1);
if (preferencesVersion == PREFERENCES_VERSION) return;
if (preferencesVersion < 1) {
PreferenceManager.setDefaultValues(context, R.xml.root_preferences, false);
Settings oldSettings = new Settings(context, "yacb_preferences");
if (oldSettings.isSet(PREF_INCOMING_CALL_NOTIFICATIONS)) {
setIncomingCallNotifications(oldSettings.getIncomingCallNotifications());
}
if (oldSettings.isSet(PREF_BLOCK_CALLS)) {
setBlockCalls(oldSettings.getBlockCalls());
}
if (oldSettings.isSet(PREF_USE_CONTACTS)) {
setUseContacts(oldSettings.getUseContacts());
}
setLastUpdateTime(oldSettings.getLastUpdateTime());
setLastUpdateCheckTime(oldSettings.getLastUpdateCheckTime());
}
setInt(SYS_PREFERENCES_VERSION, PREFERENCES_VERSION);
}
public boolean getIncomingCallNotifications() {

View File

@ -0,0 +1,100 @@
package dummydomain.yetanothercallblocker;
import android.os.Bundle;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceGroup;
import androidx.preference.PreferenceScreen;
import androidx.preference.SwitchPreferenceCompat;
import dummydomain.yetanothercallblocker.work.UpdateScheduler;
import static java.util.Objects.requireNonNull;
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
public static class SettingsFragment extends PreferenceFragmentCompat {
private static final String PREF_AUTO_UPDATE_ENABLED = "autoUpdateEnabled";
private final UpdateScheduler updateScheduler = UpdateScheduler.get(App.getInstance());
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
SwitchPreferenceCompat incomingCallNotificationPref =
requireNonNull(findPreference(Settings.PREF_INCOMING_CALL_NOTIFICATIONS));
incomingCallNotificationPref.setOnPreferenceChangeListener((preference, newValue) -> {
if (Boolean.TRUE.equals(newValue)) {
PermissionHelper.checkPermissions((AppCompatActivity) getActivity(), true, false, false);
}
return true;
});
SwitchPreferenceCompat blockCallsPref =
requireNonNull(findPreference(Settings.PREF_BLOCK_CALLS));
blockCallsPref.setOnPreferenceChangeListener((preference, newValue) -> {
if (Boolean.TRUE.equals(newValue)) {
PermissionHelper.checkPermissions((AppCompatActivity) getActivity(), false, true, false);
}
return true;
});
SwitchPreferenceCompat nonPersistentAutoUpdatePref =
requireNonNull(findPreference(PREF_AUTO_UPDATE_ENABLED));
nonPersistentAutoUpdatePref.setChecked(updateScheduler.isAutoUpdateScheduled());
nonPersistentAutoUpdatePref.setOnPreferenceChangeListener((preference, newValue) -> {
if (Boolean.TRUE.equals(newValue)) {
updateScheduler.scheduleAutoUpdates();
} else {
updateScheduler.cancelAutoUpdateWorker();
}
return true;
});
SwitchPreferenceCompat useContactsPref =
requireNonNull(findPreference(Settings.PREF_USE_CONTACTS));
useContactsPref.setOnPreferenceChangeListener((preference, newValue) -> {
if (Boolean.TRUE.equals(newValue)) {
PermissionHelper.checkPermissions((AppCompatActivity) getActivity(), false, false, true);
}
return true;
});
PreferenceScreen preferenceScreen = getPreferenceScreen();
int count = preferenceScreen.getPreferenceCount();
for (int i = 0; i < count; i++) {
Preference preference = preferenceScreen.getPreference(i);
preference.setIconSpaceReserved(false);
if (preference instanceof PreferenceGroup) {
PreferenceGroup group = (PreferenceGroup) preference;
int nestedCount = group.getPreferenceCount();
for (int k = 0; k < nestedCount; k++) {
Preference nested = group.getPreference(k);
nested.setIconSpaceReserved(false);
}
}
}
}
}
}

View File

@ -0,0 +1,9 @@
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/settings"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

View File

@ -25,6 +25,10 @@
android:onClick="onUseContactsChanged"
android:title="@string/use_contacts" />
<item
android:onClick="onOpenSettings"
android:title="@string/open_settings_activity" />
<item
android:onClick="onOpenDebugActivity"
android:title="@string/open_debug_activity" />

View File

@ -21,7 +21,9 @@
<string name="sia_category_robocall">Робот/автомат</string>
<string name="sia_category_nonprofit">Некоммерческая орг</string>
<string name="block_calls">Блокир-ть нежелат. вызовы</string>
<string name="block_calls_summary">Автоматически сбрасывать звонки c номеров с отрицательным рейтингом</string>
<string name="auto_updates">Авто-обновл. базы номеров</string>
<string name="auto_updates_summary">Получать ежедневные обновления базы (загружаются только изменения, поэтому расход трафика небольшой)</string>
<string name="open_debug_activity">Работа с базой номеров</string>
<string name="debug_activity_label">Работа с базой номеров</string>
<string name="debug_query_db">Искать в установленной базе</string>
@ -30,6 +32,7 @@
<string name="debug_not_found">Не найдено</string>
<string name="debug_update_result">Обновление завершено. Версия: %d</string>
<string name="incoming_call_notifications">Отображ. уведомл. при входящих</string>
<string name="incoming_call_notifications_summary">Отображает уведомление с краткой информацией о номере (рейтинги, кол-во отзывов, категория) при входящих вызовах</string>
<string name="title_activity_reviews">Отзывы</string>
<string name="reviews_loading">Загружаем отзывы…</string>
<string name="sia_category_fax">Факс</string>
@ -64,5 +67,9 @@
<string name="call_log_permission_message">Разрешите доступ к журналу вызовов, чтобы здесь отображались недавние вызовы</string>
<string name="notification_background_operation">Выполняется процесс в фоне…</string>
<string name="use_contacts">Отображать имена контактов</string>
<string name="use_contacts_summary">Номера из телефонной книги никогда не блокируются, и имя контакта отображается рядом/вместо номера</string>
<string name="notification_incoming_call_contact">Контакт</string>
<string name="open_settings_activity">Настройки</string>
<string name="title_settings_activity">Настройки</string>
<string name="settings_category_main">Основные</string>
</resources>

View File

@ -73,10 +73,18 @@
<string name="load_reviews_confirmation_title">Are you sure?</string>
<string name="load_reviews_confirmation_message">Loading online reviews will leak the number to a 3rd party service. Are you sure you want to do it with a number present in your Contacts?</string>
<string name="open_settings_activity">Settings</string>
<string name="title_settings_activity">Settings</string>
<string name="settings_category_main">Main</string>
<string name="incoming_call_notifications">Incoming call notifications</string>
<string name="incoming_call_notifications_summary">Displays a notification with phone number summary (rating, reviews count, category) during incoming calls</string>
<string name="block_calls">Block unwanted calls</string>
<string name="block_calls_summary">Automatically blocks calls with negative rating</string>
<string name="auto_updates">Auto-update database</string>
<string name="auto_updates_summary">Automatically receive daily DB updates (these are incremental/delta updates, so they consume very little traffic)</string>
<string name="use_contacts">Use contacts</string>
<string name="use_contacts_summary">Numbers present in the phone book are never blocked and the contact name is displayed next to/instead of a number throughout the app</string>
<string name="open_debug_activity">Open debug screen</string>
<string name="debug_activity_label">Debug</string>

View File

@ -0,0 +1,25 @@
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<PreferenceCategory app:title="@string/settings_category_main">
<SwitchPreferenceCompat
app:defaultValue="true"
app:key="incomingCallNotifications"
app:summary="@string/incoming_call_notifications_summary"
app:title="@string/incoming_call_notifications" />
<SwitchPreferenceCompat
app:key="blockCalls"
app:summary="@string/block_calls_summary"
app:title="@string/block_calls" />
<SwitchPreferenceCompat
app:key="autoUpdateEnabled"
app:persistent="false"
app:summary="@string/auto_updates_summary"
app:title="@string/auto_updates" />
<SwitchPreferenceCompat
app:key="useContacts"
app:summary="@string/use_contacts_summary"
app:title="@string/use_contacts" />
</PreferenceCategory>
</PreferenceScreen>