XmppPreferenceFragment.java

 1package eu.siacs.conversations.ui.fragment.settings;
 2
 3import android.content.SharedPreferences;
 4
 5import androidx.annotation.NonNull;
 6import androidx.preference.PreferenceFragmentCompat;
 7
 8import eu.siacs.conversations.entities.Account;
 9import eu.siacs.conversations.services.XmppConnectionService;
10import eu.siacs.conversations.ui.XmppActivity;
11
12public abstract class XmppPreferenceFragment extends PreferenceFragmentCompat {
13
14    private final SharedPreferences.OnSharedPreferenceChangeListener
15            sharedPreferenceChangeListener =
16                    (sharedPreferences, key) -> {
17                        if (key == null) {
18                            return;
19                        }
20                        onSharedPreferenceChanged(key);
21                    };
22
23    protected void onSharedPreferenceChanged(@NonNull String key) {}
24
25    public void onBackendConnected() {}
26
27    @Override
28    public void onResume() {
29        super.onResume();
30        final var sharedPreferences = getPreferenceManager().getSharedPreferences();
31        if (sharedPreferences != null) {
32            sharedPreferences.registerOnSharedPreferenceChangeListener(
33                    this.sharedPreferenceChangeListener);
34        }
35        final var xmppActivity = requireXmppActivity();
36        if (xmppActivity.xmppConnectionService != null) {
37            this.onBackendConnected();
38        }
39    }
40
41    @Override
42    public void onPause() {
43        super.onPause();
44        final var sharedPreferences = getPreferenceManager().getSharedPreferences();
45        if (sharedPreferences != null) {
46            sharedPreferences.registerOnSharedPreferenceChangeListener(
47                    this.sharedPreferenceChangeListener);
48        }
49    }
50
51    protected void reconnectAccounts() {
52        final var service = requireService();
53        for (final Account account : service.getAccounts()) {
54            if (account.isEnabled()) {
55                service.reconnectAccountInBackground(account);
56            }
57        }
58    }
59
60    protected XmppActivity requireXmppActivity() {
61        final var activity = requireActivity();
62        if (activity instanceof XmppActivity xmppActivity) {
63            return xmppActivity;
64        }
65        throw new IllegalStateException();
66    }
67
68    protected XmppConnectionService requireService() {
69        final var xmppActivity = requireXmppActivity();
70        final var service = xmppActivity.xmppConnectionService;
71        if (service != null) {
72            return service;
73        }
74        throw new IllegalStateException();
75    }
76
77    protected void runOnUiThread(final Runnable runnable) {
78        requireActivity().runOnUiThread(runnable);
79    }
80}