com.gianlu.commonutils.preferences.Prefs Java Examples

The following examples show how to use com.gianlu.commonutils.preferences.Prefs. 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: HttpClient.java    From Aria2App with GNU General Public License v3.0 6 votes vote down vote up
@UiThread
private HttpClient(@NonNull MultiProfile.UserProfile profile, @NonNull OnConnect connectionListener, boolean close) throws GeneralSecurityException, IOException, NetUtils.InvalidUrlException {
    this(profile);

    executorService.submit(() -> {
        try (Socket socket = new Socket()) {
            final long initializedAt = System.currentTimeMillis();
            socket.connect(new InetSocketAddress(profile.serverAddr, profile.serverPort), (int) TimeUnit.SECONDS.toMillis(Prefs.getInt(PK.A2_NETWORK_TIMEOUT)));
            handler.post(() -> {
                if (connectionListener.onConnected(HttpClient.this))
                    connectionListener.onPingTested(HttpClient.this, System.currentTimeMillis() - initializedAt);
            });

            if (close) close();
        } catch (IOException ex) {
            handler.post(() -> connectionListener.onFailedConnecting(profile, ex));
            close();
        }
    });
}
 
Example #2
Source File: PyxDiscoveryApi.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 6 votes vote down vote up
public final void getWelcomeMessage(@Nullable Activity activity, @NonNull Pyx.OnResult<String> listener) {
    String cached = Prefs.getString(PK.WELCOME_MSG_CACHE, null);
    if (cached != null && !CommonUtils.isDebug()) {
        long age = Prefs.getLong(PK.WELCOME_MSG_CACHE_AGE, 0);
        if (System.currentTimeMillis() - age < TimeUnit.HOURS.toMillis(12)) {
            listener.onDone(cached);
            return;
        }
    }

    executor.execute(new LifecycleAwareRunnable(handler, activity == null ? listener : activity) {
        @Override
        public void run() {
            try {
                JSONObject obj = new JSONObject(requestSync(WELCOME_MSG_URL));
                final String msg = obj.getString("msg");
                Prefs.putString(PK.WELCOME_MSG_CACHE, msg);
                Prefs.putLong(PK.WELCOME_MSG_CACHE_AGE, System.currentTimeMillis());
                post(() -> listener.onDone(msg));
            } catch (JSONException | IOException ex) {
                post(() -> listener.onException(ex));
            }
        }
    });
}
 
Example #3
Source File: PreferenceActivity.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void buildPreferences(@NonNull Context context) {
    MaterialCheckboxPreference nightMode = new MaterialCheckboxPreference.Builder(context)
            .defaultValue(PK.NIGHT_MODE.fallback())
            .key(PK.NIGHT_MODE.key())
            .build();
    nightMode.setTitle(R.string.prefs_nightMode);
    nightMode.setSummary(R.string.prefs_nightMode_summary);
    addPreference(nightMode);

    if (!Prefs.isSetEmpty(PK.BLOCKED_USERS)) {
        MaterialStandardPreference unblock = new MaterialStandardPreference(context);
        unblock.setTitle(R.string.unblockUser);
        unblock.setSummary(R.string.unblockUser_summary);
        unblock.setOnClickListener(v -> showUnblockDialog(context));
        addPreference(unblock);
    }
}
 
Example #4
Source File: AnalyticsPreferenceDialog.java    From CommonUtils with Apache License 2.0 6 votes vote down vote up
@NonNull
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_analytics_preference, container, false);

    SwitchMaterial tracking = layout.findViewById(R.id.analyticsPrefsDialog_tracking);
    tracking.setChecked(Prefs.getBoolean(CommonPK.TRACKING_ENABLED, true));
    tracking.setOnCheckedChangeListener((buttonView, isChecked) -> Prefs.putBoolean(CommonPK.TRACKING_ENABLED, isChecked));

    SwitchMaterial crashReport = layout.findViewById(R.id.analyticsPrefsDialog_crashReport);
    crashReport.setChecked(Prefs.getBoolean(CommonPK.CRASH_REPORT_ENABLED, true));
    crashReport.setOnCheckedChangeListener((buttonView, isChecked) -> Prefs.putBoolean(CommonPK.CRASH_REPORT_ENABLED, isChecked));

    Button ok = layout.findViewById(R.id.analyticsPrefsDialog_ok);
    ok.setOnClickListener(v -> dismissAllowingStateLoss());

    return layout;
}
 
Example #5
Source File: PreferenceActivity.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 6 votes vote down vote up
private void showUnblockDialog(@NonNull Context context) {
    String[] entries = Prefs.getSet(PK.BLOCKED_USERS, new HashSet<>()).toArray(new String[0]);
    boolean[] checked = new boolean[entries.length];

    MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(context);
    builder.setTitle(R.string.unblockUser)
            .setMultiChoiceItems(entries, checked, (dialog, which, isChecked) -> checked[which] = isChecked)
            .setPositiveButton(R.string.unblock, (dialog, which) -> {
                for (int i = 0; i < checked.length; i++) {
                    if (checked[i]) BlockedUsers.unblock(entries[i]);
                }

                if (Prefs.isSetEmpty(PK.BLOCKED_USERS)) onBackPressed();
            }).setNegativeButton(android.R.string.cancel, null);

    showDialog(builder);
}
 
Example #6
Source File: GamesFragment.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 6 votes vote down vote up
public void viewGame(int gid, boolean locked) {
    if (adapter == null) return;

    if (locked && adapter.doesFilterOutLockedLobbies()) {
        Prefs.putBoolean(PK.FILTER_LOCKED_LOBBIES, false);
        adapter.setFilterOutLockedLobbies(false);
    }

    int pos = Utils.indexOf(adapter.getVisibleGames(), gid);
    if (pos != -1) {
        RecyclerView list = rmv.list();
        list.scrollToPosition(pos);
        RecyclerView.ViewHolder holder = list.findViewHolderForAdapterPosition(pos);
        if (holder instanceof GamesAdapter.ViewHolder)
            ((GamesAdapter.ViewHolder) holder).expand.performClick();
    }
}
 
Example #7
Source File: LoadingActivity.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (requestCode == GOOGLE_SIGN_IN_CODE) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result == null) return;

        if (result.isSuccess()) {
            googleSignedIn(result.getSignInAccount());
        } else {
            if (result.getStatus().getStatusCode() == GoogleSignInStatusCodes.SIGN_IN_CANCELLED)
                Prefs.putBoolean(PK.SHOULD_PROMPT_GOOGLE_PLAY, false);

            String msg = result.getStatus().getStatusMessage();
            if (msg != null && !msg.isEmpty())
                Toaster.with(this).message(msg).show();
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}
 
Example #8
Source File: OptionsAdapter.java    From Aria2App with GNU General Public License v3.0 6 votes vote down vote up
@NonNull
public static OptionsAdapter setup(@NonNull Context context, @NonNull OptionsMap map, boolean global, boolean quick, boolean quickOnTop, Listener listener) throws IOException, JSONException {
    List<String> all;
    if (global) all = OptionsManager.get(context).loadGlobalOptions();
    else all = OptionsManager.get(context).loadDownloadOptions();

    Set<String> filter;
    if (quick) filter = Prefs.getSet(PK.A2_QUICK_OPTIONS_MIXED, null);
    else filter = null;

    List<Option> options = Option.fromOptionsMap(map, all, filter);
    if (quickOnTop)
        Collections.sort(options, new OptionsManager.IsQuickComparator());

    return new OptionsAdapter(context, options, listener);
}
 
Example #9
Source File: FetchHelper.java    From Aria2App with GNU General Public License v3.0 6 votes vote down vote up
private FetchHelper(@NonNull Context context) throws GeneralSecurityException, IOException, ProfilesManager.NoCurrentProfileException, InitializationException, Aria2Helper.InitializingException {
    MultiProfile.UserProfile profile = ProfilesManager.get(context).getCurrentSpecific();
    MultiProfile.DirectDownload dd = profile.directDownload;
    if (dd == null) throw new DirectDownloadNotEnabledException();

    OkHttpClient.Builder client = new OkHttpClient.Builder();
    if (!dd.hostnameVerifier) {
        client.hostnameVerifier((s, sslSession) -> true);
    }

    if (dd.certificate != null) NetUtils.setSslSocketFactory(client, dd.certificate);
    if (dd.auth) client.addInterceptor(new BasicAuthInterceptor(dd.username, dd.password));

    FetchConfiguration fetchConfiguration = new FetchConfiguration.Builder(context)
            .setDownloadConcurrentLimit(Prefs.getInt(PK.DD_MAX_SIMULTANEOUS_DOWNLOADS))
            .setProgressReportingInterval(1000)
            .enableAutoStart(Prefs.getBoolean(PK.DD_RESUME))
            .setHttpDownloader(new OkHttpDownloader(client.build()))
            .build();

    fetch = Fetch.Impl.getInstance(fetchConfiguration);
    profilesManager = ProfilesManager.get(context);
    handler = new Handler(Looper.getMainLooper());
    aria2 = Aria2Helper.instantiate(context);
}
 
Example #10
Source File: FirstLoadedPyx.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 6 votes vote down vote up
public final void register(@NonNull String nickname, @Nullable String idCode, @Nullable Activity activity, @NonNull OnResult<RegisteredPyx> listener) {
    try {
        listener.onDone(InstanceHolder.holder().get(InstanceHolder.Level.REGISTERED));
    } catch (LevelMismatchException exx) {
        executor.execute(new LifecycleAwareRunnable(handler, activity == null ? listener : activity) {
            @Override
            public void run() {
                try {
                    User user = requestSync(PyxRequests.register(nickname, idCode, Prefs.getString(PK.LAST_PERSISTENT_ID, null)));
                    Prefs.putString(PK.LAST_PERSISTENT_ID, user.persistentId);
                    RegisteredPyx pyx = upgrade(user);
                    post(() -> listener.onDone(pyx));
                } catch (JSONException | PyxException | IOException ex) {
                    post(() -> listener.onException(ex));
                }
            }
        });
    }
}
 
Example #11
Source File: DomainActivity.java    From DNSHero with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.domain_preferences:
            startActivity(new Intent(this, PreferenceActivity.class));
            return true;
        case android.R.id.home:
            onBackPressed();
            return true;
        case R.id.domain_favorite:
            Domain domain = (Domain) getIntent().getSerializableExtra("domain");
            if (domain != null) {
                if (Prefs.setContains(PK.FAVORITES, domain.name))
                    Prefs.removeFromSet(PK.FAVORITES, domain.name);
                else
                    Prefs.addToSet(PK.FAVORITES, domain.name);

                invalidateOptionsMenu();
                return true;
            } else {
                return false;
            }
        default:
            return super.onOptionsItemSelected(item);
    }
}
 
Example #12
Source File: RegisteredPyx.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 6 votes vote down vote up
public final void logout() {
    request(PyxRequests.logout(), null, new OnSuccess() {
        @Override
        public void onDone() {
            if (pollingThread != null) pollingThread.safeStop();
        }

        @Override
        public void onException(@NonNull Exception ex) {
            Log.e(TAG, "Failed logging out.", ex);
        }
    });

    InstanceHolder.holder().invalidate();
    Prefs.remove(PK.LAST_JSESSIONID);
}
 
Example #13
Source File: MainActivity.java    From Aria2App with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onItemCountUpdated(int count) {
    if (drawerManager != null) drawerManager.updateBadge(DrawerItem.HOME, count);

    if (count == 0) {
        if (Prefs.getSet(PK.A2_MAIN_FILTERS).size() == Download.Status.values().length
                && (searchView == null || searchView.getQuery() == null || searchView.getQuery().length() == 0))
            recyclerViewLayout.showInfo(R.string.noDownloads_addOne);
        else
            recyclerViewLayout.showInfo(R.string.noDownloads_changeFilters);
    } else {
        recyclerViewLayout.showList();
    }

    tutorialManager.tryShowingTutorials(this);
}
 
Example #14
Source File: LoadingActivity.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 6 votes vote down vote up
private void signInSilently() {
    GoogleSignInOptions signInOptions = GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN;
    GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
    if (GoogleSignIn.hasPermissions(account, signInOptions.getScopeArray())) {
        googleSignedIn(account);
    } else {
        GoogleSignInClient signInClient = GoogleSignIn.getClient(this, signInOptions);
        signInClient.silentSignIn().addOnCompleteListener(this, task -> {
            if (task.isSuccessful()) {
                googleSignedIn(task.getResult());
            } else {
                if (Prefs.getBoolean(PK.SHOULD_PROMPT_GOOGLE_PLAY, true)) {
                    Intent intent = signInClient.getSignInIntent();
                    startActivityForResult(intent, GOOGLE_SIGN_IN_CODE);
                }
            }
        });
    }
}
 
Example #15
Source File: NetUtils.java    From Aria2App with GNU General Public License v3.0 6 votes vote down vote up
@NonNull
public static OkHttpClient buildClient(@NonNull MultiProfile.UserProfile profile) throws GeneralSecurityException, IOException {
    int timeout = Prefs.getInt(PK.A2_NETWORK_TIMEOUT);

    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.connectTimeout(timeout, TimeUnit.SECONDS)
            .readTimeout(timeout, TimeUnit.SECONDS)
            .writeTimeout(timeout, TimeUnit.SECONDS);

    if (profile.certificate != null)
        setSslSocketFactory(builder, profile.certificate);

    if (!profile.hostnameVerifier)
        builder.hostnameVerifier((s, sslSession) -> true);

    return builder.build();
}
 
Example #16
Source File: FilesFragment.java    From Aria2App with GNU General Public License v3.0 6 votes vote down vote up
private void shouldDownload(@NonNull MultiProfile profile, @NonNull OptionsMap global, @NonNull AriaFile file, boolean share) {
    AnalyticsApplication.sendAnalytics(Utils.ACTION_DOWNLOAD_FILE);

    if (Prefs.getBoolean(PK.DD_USE_EXTERNAL) || share) {
        MultiProfile.DirectDownload dd = profile.getProfile(getContext()).directDownload;
        HttpUrl base;
        if (dd == null || (base = dd.getUrl()) == null) return;

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(file.getDownloadUrl(global, base).toString()));

        if (dd.auth) {
            Bundle headers = new Bundle();
            headers.putString("Authorization", dd.getAuthorizationHeader());
            intent.putExtra(Browser.EXTRA_HEADERS, headers);
        }

        startActivity(intent);
    } else {
        startDownloadInternal(profile, file, null);
    }
}
 
Example #17
Source File: FilesFragment.java    From Aria2App with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onDownloadDirectory(@NonNull MultiProfile profile, @NonNull AriaDirectory dir) {
    if (dirSheet != null) {
        dirSheet.dismiss();
        dirSheet = null;
        dismissDialog();
    }

    AnalyticsApplication.sendAnalytics(Utils.ACTION_DOWNLOAD_DIRECTORY);

    if (Prefs.getBoolean(PK.DD_USE_EXTERNAL)) {
        AlertDialog.Builder builder = new MaterialAlertDialogBuilder(requireContext());
        builder.setTitle(R.string.cannotDownloadDirWithExternal)
                .setMessage(R.string.cannotDownloadDirWithExternal_message)
                .setPositiveButton(android.R.string.yes, (dialog, which) -> startDownloadInternal(profile, null, dir))
                .setNegativeButton(android.R.string.no, null);

        showDialog(builder);
    } else {
        startDownloadInternal(profile, null, dir);
    }
}
 
Example #18
Source File: PreferenceActivity.java    From DNSHero with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void buildPreferences(@NonNull Context context) {
    if (!Prefs.isSetEmpty(PK.FAVORITES)) {
        final MaterialStandardPreference remove = new MaterialStandardPreference(context);
        remove.setTitle(R.string.removeFavorite);
        remove.setSummary(R.string.removeFavorite_summary);
        remove.setOnClickListener(v -> showRemoveDialog(context));
        addPreference(remove);
    }

    MaterialStandardPreference clear = new MaterialStandardPreference(context);
    clear.setTitle(R.string.clearFavorites);
    clear.setSummary(R.string.clearFavorites_summary);
    clear.setOnClickListener(v -> {
        Prefs.putSet(PK.FAVORITES, new HashSet<>());
        onBackPressed();
    });
    addPreference(clear);
}
 
Example #19
Source File: PreferenceActivity.java    From DNSHero with GNU General Public License v3.0 6 votes vote down vote up
private void showRemoveDialog(Context context) {
    final String[] entries = Prefs.getSet(PK.FAVORITES, new HashSet<>()).toArray(new String[0]);
    final boolean[] checked = new boolean[entries.length];

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle(R.string.removeFavorite)
            .setMultiChoiceItems(entries, checked, (dialog, which, isChecked) -> checked[which] = isChecked)
            .setPositiveButton(R.string.remove, (dialog, which) -> {
                for (int i = 0; i < checked.length; i++) {
                    if (checked[i]) Prefs.removeFromSet(PK.FAVORITES, entries[i]);
                }

                if (Prefs.isSetEmpty(PK.FAVORITES)) onBackPressed();
            }).setNegativeButton(android.R.string.cancel, null);

    showDialog(builder);
}
 
Example #20
Source File: MultiProfile.java    From Aria2App with GNU General Public License v3.0 6 votes vote down vote up
@NonNull
public static MultiProfile forInAppDownloader() {
    int port = ThreadLocalRandom.current().nextInt(2000, 8000);
    Prefs.putInt(Aria2PK.RPC_PORT, port);

    String token = CommonUtils.randomString(8, ThreadLocalRandom.current());
    Prefs.putString(Aria2PK.RPC_TOKEN, token);

    MultiProfile profile = new MultiProfile(IN_APP_DOWNLOADER_NAME, true);
    profile.add(ConnectivityCondition.newUniqueCondition(),
            new ConnectionFragment.Fields(ConnectionMethod.WEBSOCKET, "localhost", port, "/jsonrpc", false, null, false),
            new AuthenticationFragment.Fields(AbstractClient.AuthMethod.TOKEN, token, null, null),
            new DirectDownloadFragment.Fields(null));

    return profile;
}
 
Example #21
Source File: MainActivity.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.main_logout:
            drawerAction();
            return true;
        case R.id.main_keepScreenOn:
            item.setChecked(!item.isChecked());
            Prefs.putBoolean(PK.KEEP_SCREEN_ON, item.isChecked());
            setKeepScreenOn(item.isChecked());
            return true;
    }

    return super.onOptionsItemSelected(item);
}
 
Example #22
Source File: PayloadUpdater.java    From Aria2App with GNU General Public License v3.0 5 votes vote down vote up
public PayloadUpdater(Context context, OnPayload<P> listener) throws Aria2Helper.InitializingException {
    this.helper = Aria2Helper.instantiate(context);
    this.listener = listener;
    this.handler = new Handler(Looper.getMainLooper());
    this.errorHandler = ErrorHandler.get();
    this.updateInterval = Prefs.getInt(PK.A2_UPDATE_INTERVAL) * 1000;
}
 
Example #23
Source File: GamesFragment.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.gamesFragment_showLocked) {
        boolean show = !item.isChecked();
        item.setChecked(show);
        Prefs.putBoolean(PK.FILTER_LOCKED_LOBBIES, !show);
        if (adapter != null) adapter.setFilterOutLockedLobbies(!show);
        return true;
    }

    return super.onOptionsItemSelected(item);
}
 
Example #24
Source File: PreferenceActivity.java    From Aria2App with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == DOWNLOAD_PATH_CODE) {
        if (resultCode == RESULT_OK && isAdded() && data.getData() != null) {
            DocumentFile file = DocumentFile.fromTreeUri(requireContext(), data.getData());
            if (file != null)
                Prefs.putString(PK.DD_DOWNLOAD_PATH, file.getUri().toString());
        }

        return;
    }

    super.onActivityResult(requestCode, resultCode, data);
}
 
Example #25
Source File: SearchActivity.java    From Aria2App with GNU General Public License v3.0 5 votes vote down vote up
private void showEnginesDialog(@NotNull List<SearchEngine> engines) {
    CharSequence[] enginesNames = new CharSequence[engines.size()];

    for (int i = 0; i < engines.size(); i++) {
        SearchEngine engine = engines.get(i);
        enginesNames[i] = engine.name + (engine.proxyed ? " (proxyed)" : "");
    }

    final boolean[] checkedEngines = new boolean[engines.size()];
    Set<String> checkedEnginesSet = Prefs.getSet(PK.A2_SEARCH_ENGINES, null);

    if (checkedEnginesSet == null) {
        Arrays.fill(checkedEngines, true);
    } else {
        for (String checkedEngine : checkedEnginesSet)
            for (int i = 0; i < engines.size(); i++)
                if (Objects.equals(engines.get(i).id, checkedEngine))
                    checkedEngines[i] = true;
    }

    MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
    builder.setTitle(R.string.searchEngines)
            .setMultiChoiceItems(enginesNames, checkedEngines, (dialog, which, isChecked) -> checkedEngines[which] = isChecked)
            .setPositiveButton(R.string.apply, (dialog, which) -> {
                Set<String> set = new HashSet<>();
                for (int i = 0; i < checkedEngines.length; i++)
                    if (checkedEngines[i]) set.add(engines.get(i).id);

                if (set.isEmpty()) {
                    Toaster.with(SearchActivity.this).message(R.string.noEnginesSelected).show();
                } else {
                    Prefs.putSet(PK.A2_SEARCH_ENGINES, set);
                    if (query != null) onQueryTextSubmit(query);
                }
            })
            .setNegativeButton(android.R.string.cancel, null);

    showDialog(builder);
}
 
Example #26
Source File: ProfilesManager.java    From Aria2App with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
public MultiProfile getLastProfile() {
    String id = Prefs.getString(PK.LAST_USED_PROFILE, null);
    if (id == null || !profileExists(id)) return null;

    try {
        return retrieveProfile(id);
    } catch (IOException | JSONException ex) {
        Log.e(TAG, "Failed getting profile: " + id, ex);
        return null;
    }
}
 
Example #27
Source File: LoadingActivity.java    From Aria2App with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean onConnected(@NonNull AbstractClient client) {
    ongoingTest = null;

    if (Prefs.getBoolean(PK.A2_ENABLE_NOTIFS, true))
        NotificationService.start(this);

    if (shareData != null) {
        try {
            new URL(shareData.toString());
        } catch (MalformedURLException ex) {
            launchMain();
            return false;
        }

        if (!Prefs.getBoolean(PK.A2_SKIP_WEBVIEW_DIALOG) && Utils.hasWebView(this)) {
            AlertDialog.Builder builder = new MaterialAlertDialogBuilder(this);
            builder.setTitle(R.string.useWebView)
                    .setMessage(R.string.useWebView_message)
                    .setPositiveButton(android.R.string.yes, (dialog, which) -> launchWebView())
                    .setNeutralButton(android.R.string.no, (dialog, which) -> launchMain());
            showDialog(builder);
            return false;
        }
    }

    launchMain();
    return false;
}
 
Example #28
Source File: Pyx.java    From PretendYoureXyzzyAndroid with GNU General Public License v3.0 5 votes vote down vote up
static void parseAndSave(@NonNull JSONArray array) throws JSONException {
    List<Server> servers = new ArrayList<>(array.length());
    for (int i = 0; i < array.length(); i++) {
        JSONObject obj = array.getJSONObject(i);
        String name = CommonUtils.getStupidString(obj, "name");

        HttpUrl url = new HttpUrl.Builder()
                .host(obj.getString("host"))
                .scheme(obj.getBoolean("secure") ? "https" : "http")
                .port(obj.getInt("port"))
                .encodedPath(obj.getString("path"))
                .build();

        String metrics = CommonUtils.getStupidString(obj, "metrics");
        servers.add(new Server(url, metrics == null ? null : HttpUrl.parse(metrics),
                name == null ? (url.host() + " server") : name,
                obj.has("params") ? new Params(obj.getJSONObject("params")) : Params.defaultValues(),
                false));
    }

    JSONArray json = new JSONArray();
    for (Server server : servers)
        json.put(server.toJson());

    JsonStoring.intoPrefs().putJsonArray(PK.API_SERVERS, json);
    Prefs.putLong(PK.API_SERVERS_CACHE_AGE, System.currentTimeMillis());
}
 
Example #29
Source File: BootCompletedReceiver.java    From Aria2Android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (!Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()))
        return;

    if (Prefs.getBoolean(PK.START_AT_BOOT))
        new Aria2Ui(context, null).startServiceFromReceiver();
}
 
Example #30
Source File: WebViewActivity.java    From Aria2App with GNU General Public License v3.0 5 votes vote down vote up
private void showGoToDialog(boolean compulsory) {
    EditText input = new EditText(this);
    input.setSingleLine(true);
    input.setHint(R.string.webViewUrlHint);
    input.setInputType(InputType.TYPE_TEXT_VARIATION_URI);

    AlertDialog.Builder builder = new MaterialAlertDialogBuilder(this);
    builder.setTitle(R.string.goTo)
            .setView(input)
            .setCancelable(!compulsory)
            .setNeutralButton(R.string.setAsDefault, (dialog, which) -> {
                String text = input.getText().toString();
                if (text.isEmpty()) {
                    Prefs.remove(PK.WEBVIEW_HOMEPAGE);
                    return;
                }

                Prefs.putString(PK.WEBVIEW_HOMEPAGE, guessUrl(text));
                web.loadUrl(guessUrl(text));
                ThisApplication.sendAnalytics(Utils.ACTION_WEBVIEW_SET_HOMEPAGE);
            })
            .setPositiveButton(R.string.visit, (dialog, which) -> web.loadUrl(guessUrl(input.getText().toString())));

    if (compulsory)
        builder.setNegativeButton(android.R.string.cancel, (d, i) -> onBackPressed());
    else
        builder.setNegativeButton(android.R.string.cancel, null);

    showDialog(builder);
}