Skip to content

Commit

Permalink
[Refactor] Reuse existing threads instead of creating new threads
Browse files Browse the repository at this point in the history
Signed-off-by: Muntashir Al-Islam <[email protected]>
  • Loading branch information
MuntashirAkon committed Feb 11, 2024
1 parent 263f0a9 commit 62a2d10
Show file tree
Hide file tree
Showing 8 changed files with 132 additions and 102 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import io.github.muntashirakon.AppManager.R;
import io.github.muntashirakon.AppManager.db.AppsDb;
import io.github.muntashirakon.AppManager.db.entity.LogFilter;
import io.github.muntashirakon.AppManager.utils.ThreadUtils;

// Copyright 2012 Nolan Lawson
public class LogFilterAdapter extends ArrayAdapter<LogFilter> {
Expand Down Expand Up @@ -61,7 +62,7 @@ public View getView(int position, View convertView, @NonNull ViewGroup parent) {
}
});
holder.actionButton.setOnClickListener(v -> {
new Thread(() -> AppsDb.getInstance().logFilterDao().delete(logFilter)).start();
ThreadUtils.postOnBackgroundThread(() -> AppsDb.getInstance().logFilterDao().delete(logFilter));
remove(logFilter);
notifyDataSetChanged();
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) {
//noinspection ConstantConditions
String filename = inputText.toString();
Context context = mActivity.getApplicationContext();
new Thread(() -> {
ThreadUtils.postOnBackgroundThread(() -> {
Intent intent = ServiceHelper.getLogcatRecorderServiceIfNotAlreadyRunning(context, filename,
mFilterQuery, mLogLevel);
ThreadUtils.postOnMainThread(() -> {
Expand All @@ -94,7 +94,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) {
mListener.onServiceStarted();
}
});
}).start();
});
}
})
.setNegativeButton(R.string.cancel, (dialog, which, inputText, isChecked) ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Future;

import io.github.muntashirakon.AppManager.R;
import io.github.muntashirakon.AppManager.db.entity.App;
Expand All @@ -34,6 +35,7 @@
import io.github.muntashirakon.AppManager.utils.UIUtils;
import io.github.muntashirakon.dialog.SearchableItemsDialogBuilder;
import io.github.muntashirakon.dialog.SearchableMultiChoiceDialogBuilder;
import io.github.muntashirakon.view.ProgressIndicatorCompat;

public class ImportExportRulesPreferences extends PreferenceFragment {
private static final String MIME_JSON = "application/json";
Expand All @@ -42,6 +44,8 @@ public class ImportExportRulesPreferences extends PreferenceFragment {

private final int mUserHandle = UserHandleHidden.myUserId();
private SettingsActivity mActivity;
@Nullable
private Future<?> importExistingFuture;
private final ActivityResultLauncher<String> mExportRules = registerForActivityResult(
new ActivityResultContracts.CreateDocument(MIME_TSV),
uri -> {
Expand Down Expand Up @@ -81,11 +85,10 @@ public class ImportExportRulesPreferences extends PreferenceFragment {
// Back button pressed.
return;
}
new Thread(() -> {
ThreadUtils.postOnBackgroundThread(() -> {
List<String> failedFiles = ExternalComponentsImporter.applyFromWatt(uris, Users.getUsersIds());
if (isDetached()) return;
mActivity.runOnUiThread(() -> displayImportExternalRulesFailedPackagesDialog(failedFiles));
}).start();
ThreadUtils.postOnMainThread(() -> displayImportExternalRulesFailedPackagesDialog(failedFiles));
});
});
private final ActivityResultLauncher<String> mImportFromBlocker = registerForActivityResult(
new ActivityResultContracts.GetMultipleContents(),
Expand All @@ -94,11 +97,10 @@ public class ImportExportRulesPreferences extends PreferenceFragment {
// Back button pressed.
return;
}
new Thread(() -> {
ThreadUtils.postOnBackgroundThread(() -> {
List<String> failedFiles = ExternalComponentsImporter.applyFromBlocker(uris, Users.getUsersIds());
if (isDetached()) return;
mActivity.runOnUiThread(() -> displayImportExternalRulesFailedPackagesDialog(failedFiles));
}).start();
ThreadUtils.postOnMainThread(() -> displayImportExternalRulesFailedPackagesDialog(failedFiles));
});
});

@Override
Expand Down Expand Up @@ -146,6 +148,14 @@ public void onCreate(@Nullable Bundle savedInstanceState) {
setReturnTransition(new MaterialSharedAxis(MaterialSharedAxis.Z, false));
}

@Override
public void onDestroy() {
if (importExistingFuture != null) {
importExistingFuture.cancel(true);
}
super.onDestroy();
}

@Override
public int getTitle() {
return R.string.pref_import_export_blocking_rules;
Expand All @@ -156,12 +166,12 @@ private void importExistingRules(final boolean systemApps) {
Toast.makeText(requireContext(), R.string.only_works_in_root_or_adb_mode, Toast.LENGTH_SHORT).show();
return;
}
mActivity.progressIndicator.show();
new Thread(() -> {
ProgressIndicatorCompat.setVisibility(mActivity.progressIndicator, true);
importExistingFuture = ThreadUtils.postOnBackgroundThread(() -> {
final List<ItemCount> itemCounts = new ArrayList<>();
ItemCount itemCount;
for (App app : new AppDb().getAllInstalledApplications()) {
if (isDetached()) return;
if (ThreadUtils.isInterrupted()) return;
if (!systemApps && app.isSystemApp())
continue;
itemCount = new ItemCount();
Expand All @@ -171,45 +181,53 @@ private void importExistingRules(final boolean systemApps) {
if (itemCount.count > 0) itemCounts.add(itemCount);
}
ThreadUtils.postOnMainThread(() -> displayImportExistingRulesPackageSelectionDialog(itemCounts));
}).start();
});
}

private void displayImportExistingRulesPackageSelectionDialog(@NonNull List<ItemCount> itemCounts) {
if (!itemCounts.isEmpty()) {
final List<String> packages = new ArrayList<>();
final CharSequence[] packagesWithItemCounts = new CharSequence[itemCounts.size()];
ItemCount itemCount;
for (int i = 0; i < itemCounts.size(); ++i) {
itemCount = itemCounts.get(i);
packages.add(itemCount.packageName);
packagesWithItemCounts[i] = new SpannableStringBuilder(itemCount.packageLabel).append("\n")
.append(UIUtils.getSmallerText(UIUtils.getSecondaryText(requireContext(), getResources()
.getQuantityString(R.plurals.no_of_components, itemCount.count,
itemCount.count))));
}
mActivity.progressIndicator.hide();
new SearchableMultiChoiceDialogBuilder<>(requireActivity(), packages, packagesWithItemCounts)
.setTitle(R.string.filtered_packages)
.setPositiveButton(R.string.apply, (dialog, which, selectedPackages) -> {
mActivity.progressIndicator.show();
new Thread(() -> {
List<String> failedPackages = ExternalComponentsImporter
.applyFromExistingBlockList(selectedPackages, mUserHandle);
ThreadUtils.postOnMainThread(() -> displayImportExistingRulesFailedPackagesDialog(failedPackages));
}).start();
})
.setNegativeButton(R.string.cancel, null)
.show();
} else {
mActivity.progressIndicator.hide();
if (itemCounts.isEmpty()) {
ProgressIndicatorCompat.setVisibility(mActivity.progressIndicator, false);
Toast.makeText(requireContext(), R.string.no_matching_package_found, Toast.LENGTH_SHORT).show();
return;
}
final List<String> packages = new ArrayList<>();
final CharSequence[] packagesWithItemCounts = new CharSequence[itemCounts.size()];
ItemCount itemCount;
for (int i = 0; i < itemCounts.size(); ++i) {
itemCount = itemCounts.get(i);
packages.add(itemCount.packageName);
packagesWithItemCounts[i] = new SpannableStringBuilder(itemCount.packageLabel).append("\n")
.append(UIUtils.getSmallerText(UIUtils.getSecondaryText(requireContext(), getResources()
.getQuantityString(R.plurals.no_of_components, itemCount.count,
itemCount.count))));
}
ProgressIndicatorCompat.setVisibility(mActivity.progressIndicator, false);
new SearchableMultiChoiceDialogBuilder<>(requireActivity(), packages, packagesWithItemCounts)
.setTitle(R.string.filtered_packages)
.setPositiveButton(R.string.apply, (dialog, which, selectedPackages) -> {
ProgressIndicatorCompat.setVisibility(mActivity.progressIndicator, true);
ThreadUtils.postOnBackgroundThread(() -> {
List<String> failedPackages = ExternalComponentsImporter
.applyFromExistingBlockList(selectedPackages, mUserHandle);
ThreadUtils.postOnMainThread(() -> displayImportExistingRulesFailedPackagesDialog(failedPackages));
});
})
.setNegativeButton(R.string.cancel, null)
.show();
}

private void displayImportExistingRulesFailedPackagesDialog(@NonNull List<String> failedPackages) {
mActivity.progressIndicator.hide();
if (isDetached()) {
if (failedPackages.isEmpty()) {
UIUtils.displayShortToast(R.string.the_import_was_successful);
} else {
UIUtils.displayShortToast(R.string.failed);
}
return;
}
ProgressIndicatorCompat.setVisibility(mActivity.progressIndicator, false);
if (failedPackages.isEmpty()) {
Toast.makeText(requireContext(), R.string.the_import_was_successful, Toast.LENGTH_SHORT).show();
UIUtils.displayShortToast(R.string.the_import_was_successful);
return;
}
new SearchableItemsDialogBuilder<>(requireActivity(), failedPackages)
Expand All @@ -219,9 +237,17 @@ private void displayImportExistingRulesFailedPackagesDialog(@NonNull List<String
}

private void displayImportExternalRulesFailedPackagesDialog(@NonNull List<String> failedFiles) {
mActivity.progressIndicator.hide();
if (isDetached()) {
if (failedFiles.isEmpty()) {
UIUtils.displayShortToast(R.string.the_import_was_successful);
} else {
UIUtils.displayLongToastPl(R.plurals.failed_to_import_files, failedFiles.size(), failedFiles.size());
}
return;
}
ProgressIndicatorCompat.setVisibility(mActivity.progressIndicator, false);
if (failedFiles.isEmpty()) {
Toast.makeText(requireContext(), R.string.the_import_was_successful, Toast.LENGTH_SHORT).show();
UIUtils.displayShortToast(R.string.the_import_was_successful);
return;
}
new SearchableItemsDialogBuilder<>(requireActivity(), failedFiles)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import io.github.muntashirakon.AppManager.crypto.ks.SecretKeyCompat;
import io.github.muntashirakon.AppManager.logs.Log;
import io.github.muntashirakon.AppManager.settings.Prefs;
import io.github.muntashirakon.AppManager.utils.ThreadUtils;
import io.github.muntashirakon.AppManager.utils.UIUtils;
import io.github.muntashirakon.AppManager.utils.Utils;
import io.github.muntashirakon.dialog.TextInputDialogBuilder;
Expand Down Expand Up @@ -119,7 +120,7 @@ public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
})
.show());
});
new Thread(() -> {
ThreadUtils.postOnBackgroundThread(() -> {
try {
mKeyStoreManager = KeyStoreManager.getInstance();
SecretKey secretKey = mKeyStoreManager.getSecretKey(AES_KEY_ALIAS);
Expand All @@ -135,7 +136,7 @@ public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
} catch (Exception e) {
Log.e(TAG, e);
}
}).start();
});
return alertDialog;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import io.github.muntashirakon.AppManager.crypto.ks.KeyStoreManager;
import io.github.muntashirakon.AppManager.logs.Log;
import io.github.muntashirakon.AppManager.utils.PackageUtils;
import io.github.muntashirakon.AppManager.utils.ThreadUtils;
import io.github.muntashirakon.AppManager.utils.UIUtils;
import io.github.muntashirakon.dialog.ScrollableDialogBuilder;

Expand Down Expand Up @@ -56,11 +57,11 @@ public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.pref_import, null)
.setNeutralButton(R.string.generate_key, null);
new Thread(() -> {
if (isDetached()) return;
ThreadUtils.postOnBackgroundThread(() -> {
if (ThreadUtils.isInterrupted()) return;
CharSequence info = getSigningInfo();
mActivity.runOnUiThread(() -> mBuilder.setMessage(info));
}).start();
ThreadUtils.postOnMainThread(() -> mBuilder.setMessage(info));
});
AlertDialog alertDialog = mBuilder.create();
alertDialog.setOnShowListener(dialog -> {
AlertDialog dialog1 = (AlertDialog) dialog;
Expand All @@ -72,31 +73,31 @@ public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
Bundle args = new Bundle();
args.putString(KeyPairImporterDialogFragment.EXTRA_ALIAS, mTargetAlias);
fragment.setArguments(args);
fragment.setOnKeySelectedListener((keyPair) -> new Thread(() ->
new Thread(() -> addKeyPair(keyPair)).start()).start());
fragment.setOnKeySelectedListener((keyPair) -> ThreadUtils.postOnBackgroundThread(() ->
addKeyPair(keyPair)));
fragment.show(getParentFragmentManager(), KeyPairImporterDialogFragment.TAG);
});
generateButton.setOnClickListener(v -> {
KeyPairGeneratorDialogFragment fragment = new KeyPairGeneratorDialogFragment();
Bundle args = new Bundle();
args.putString(KeyPairGeneratorDialogFragment.EXTRA_KEY_TYPE, CryptoUtils.MODE_ECC);
fragment.setArguments(args);
fragment.setOnGenerateListener((keyPair) -> new Thread(() ->
addKeyPair(keyPair)).start());
fragment.setOnGenerateListener((keyPair) -> ThreadUtils.postOnBackgroundThread(() ->
addKeyPair(keyPair)));
fragment.show(getParentFragmentManager(), KeyPairGeneratorDialogFragment.TAG);
});
defaultOrOkButton.setOnClickListener(v -> new Thread(() -> {
defaultOrOkButton.setOnClickListener(v -> ThreadUtils.postOnBackgroundThread(() -> {
try {
if (isDetached()) return;
mActivity.runOnUiThread(() -> UIUtils.displayShortToast(R.string.done));
if (ThreadUtils.isInterrupted()) return;
ThreadUtils.postOnMainThread(() -> UIUtils.displayShortToast(R.string.done));
keyPairUpdated();
} catch (Exception e) {
Log.e(TAG, e);
mActivity.runOnUiThread(() -> UIUtils.displayLongToast(R.string.failed_to_save_key));
ThreadUtils.postOnMainThread(() -> UIUtils.displayLongToast(R.string.failed_to_save_key));
} finally {
alertDialog.dismiss();
}
}).start());
}));
});
return alertDialog;
}
Expand All @@ -122,15 +123,15 @@ private void addKeyPair(@Nullable KeyPair keyPair) {
}
mKeyStoreManager = KeyStoreManager.getInstance();
mKeyStoreManager.addKeyPair(mTargetAlias, keyPair, true);
if (isDetached()) return;
mActivity.runOnUiThread(() -> UIUtils.displayShortToast(R.string.done));
if (ThreadUtils.isInterrupted()) return;
ThreadUtils.postOnMainThread(() -> UIUtils.displayShortToast(R.string.done));
keyPairUpdated();
if (isDetached()) return;
if (ThreadUtils.isInterrupted()) return;
CharSequence info = getSigningInfo();
mActivity.runOnUiThread(() -> mBuilder.setMessage(info));
ThreadUtils.postOnMainThread(() -> mBuilder.setMessage(info));
} catch (Exception e) {
Log.e(TAG, e);
mActivity.runOnUiThread(() -> UIUtils.displayLongToast(R.string.failed_to_save_key));
ThreadUtils.postOnMainThread(() -> UIUtils.displayLongToast(R.string.failed_to_save_key));
}
}

Expand All @@ -141,15 +142,15 @@ private void keyPairUpdated() {
if (keyPair != null) {
if (mListener != null) {
byte[] bytes = keyPair.getCertificate().getEncoded();
mActivity.runOnUiThread(() -> mListener.keyPairUpdated(keyPair, bytes));
ThreadUtils.postOnMainThread(() -> mListener.keyPairUpdated(keyPair, bytes));
}
return;
}
} catch (Exception e) {
Log.e(TAG, e);
}
if (mListener != null) {
mActivity.runOnUiThread(() -> mListener.keyPairUpdated(null, null));
ThreadUtils.postOnMainThread(() -> mListener.keyPairUpdated(null, null));
}
}

Expand Down
Loading

0 comments on commit 62a2d10

Please sign in to comment.