Use ExecutorServices for running threaded tasks

Signed-off-by: Stefan Niedermann <info@niedermann.it>
This commit is contained in:
Stefan Niedermann 2021-06-11 11:05:17 +02:00
parent a2bbff4f02
commit dad6836f73
13 changed files with 87 additions and 53 deletions

View file

@ -33,6 +33,8 @@ import com.nextcloud.android.sso.model.SingleSignOnAccount;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import it.niedermann.android.util.ColorUtil;
import it.niedermann.owncloud.notes.R;
@ -62,6 +64,7 @@ import static java.lang.Boolean.TRUE;
public abstract class BaseNoteFragment extends BrandedFragment implements CategoryDialogListener, EditTitleListener {
private static final String TAG = BaseNoteFragment.class.getSimpleName();
protected final ExecutorService executor = Executors.newCachedThreadPool();
protected static final int MENU_ID_PIN = -1;
public static final String PARAM_NOTE_ID = "noteId";
@ -98,7 +101,7 @@ public abstract class BaseNoteFragment extends BrandedFragment implements Catego
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Thread(() -> {
executor.submit(() -> {
try {
SingleSignOnAccount ssoAccount = SingleAccountHelper.getCurrentSingleSignOnAccount(requireContext().getApplicationContext());
this.localAccount = repo.getAccountByName(ssoAccount.name);
@ -143,7 +146,7 @@ public abstract class BaseNoteFragment extends BrandedFragment implements Catego
} catch (NextcloudFilesAppAccountNotFoundException | NoCurrentAccountSelectedException e) {
e.printStackTrace();
}
}).start();
});
setHasOptionsMenu(true);
}
@ -214,13 +217,13 @@ public abstract class BaseNoteFragment extends BrandedFragment implements Catego
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.menu_cancel) {
new Thread(() -> {
executor.submit(() -> {
if (originalNote == null) {
repo.deleteNoteAndSync(localAccount, note.getId());
} else {
repo.updateNoteAndSync(localAccount, originalNote, null, null, null);
}
}).start();
});
listener.close();
return true;
} else if (itemId == R.id.menu_delete) {
@ -239,11 +242,9 @@ public abstract class BaseNoteFragment extends BrandedFragment implements Catego
showEditTitleDialog();
return true;
} else if (itemId == R.id.menu_move) {
new Thread(() -> {
AccountPickerDialogFragment
.newInstance(new ArrayList<>(repo.getAccounts()), note.getAccountId())
.show(requireActivity().getSupportFragmentManager(), BaseNoteFragment.class.getSimpleName());
}).start();
executor.submit(() -> AccountPickerDialogFragment
.newInstance(new ArrayList<>(repo.getAccounts()), note.getAccountId())
.show(requireActivity().getSupportFragmentManager(), BaseNoteFragment.class.getSimpleName()));
return true;
} else if (itemId == R.id.menu_share) {
ShareUtil.openShareDialog(requireContext(), note.getTitle(), note.getContent());
@ -366,10 +367,10 @@ public abstract class BaseNoteFragment extends BrandedFragment implements Catego
public void onTitleEdited(String newTitle) {
titleModified = true;
note.setTitle(newTitle);
new Thread(() -> {
executor.submit(() -> {
note = repo.updateNoteAndSync(localAccount, note, note.getContent(), newTitle, null);
requireActivity().runOnUiThread(() -> listener.onNoteUpdated(note));
}).start();
});
}
public void moveNote(Account account) {

View file

@ -155,22 +155,22 @@ public class NotePreviewFragment extends SearchableBaseNoteFragment implements O
public void onRefresh() {
if (noteLoaded && repo.isSyncPossible() && SSOUtil.isConfigured(getContext())) {
binding.swiperefreshlayout.setRefreshing(true);
new Thread(() -> {
executor.submit(() -> {
try {
final Account account = repo.getAccountByName(SingleAccountHelper.getCurrentSingleSignOnAccount(requireContext()).name);
repo.addCallbackPull(account, () -> new Thread(() -> {
repo.addCallbackPull(account, () -> executor.submit(() -> {
note = repo.getNoteById(note.getId());
changedText = note.getContent();
requireActivity().runOnUiThread(() -> {
binding.singleNoteContent.setMarkdownString(note.getContent());
binding.swiperefreshlayout.setRefreshing(false);
});
}).start());
}));
repo.scheduleSync(account, false);
} catch (NextcloudFilesAppAccountNotFoundException | NoCurrentAccountSelectedException e) {
e.printStackTrace();
}
}).start();
});
} else {
binding.swiperefreshlayout.setRefreshing(false);
Toast.makeText(requireContext(), getString(R.string.error_sync, getString(R.string.error_no_network)), Toast.LENGTH_LONG).show();

View file

@ -21,6 +21,8 @@ import com.nextcloud.android.sso.helper.SingleAccountHelper;
import com.nextcloud.android.sso.ui.UiExceptionManager;
import java.net.HttpURLConnection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import it.niedermann.owncloud.notes.R;
import it.niedermann.owncloud.notes.branding.BrandingUtil;
@ -39,6 +41,8 @@ public class ImportAccountActivity extends AppCompatActivity {
private static final String TAG = ImportAccountActivity.class.getSimpleName();
public static final int REQUEST_CODE_IMPORT_ACCOUNT = 1;
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private ImportAccountViewModel importAccountViewModel;
private ActivityImportAccountBinding binding;
@ -86,7 +90,7 @@ public class ImportAccountActivity extends AppCompatActivity {
runOnUiThread(() -> binding.progressCircular.setVisibility(View.VISIBLE));
SingleAccountHelper.setCurrentAccount(getApplicationContext(), ssoAccount.name);
new Thread(() -> {
executor.submit(() -> {
Log.i(TAG, "Added account: " + "name:" + ssoAccount.name + ", " + ssoAccount.url + ", userId" + ssoAccount.userId);
try {
Log.i(TAG, "Loading capabilities for " + ssoAccount.name);
@ -140,7 +144,7 @@ public class ImportAccountActivity extends AppCompatActivity {
}
});
}
}).start();
});
});
} catch (AccountImportCancelledException e) {
restoreCleanState();

View file

@ -49,6 +49,8 @@ import com.nextcloud.android.sso.helper.SingleAccountHelper;
import java.net.HttpURLConnection;
import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import it.niedermann.owncloud.notes.LockedActivity;
import it.niedermann.owncloud.notes.R;
@ -104,6 +106,8 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
private static final String TAG = MainActivity.class.getSimpleName();
protected final ExecutorService executor = Executors.newCachedThreadPool();
protected MainViewModel mainViewModel;
private CategoryViewModel categoryViewModel;
@ -164,14 +168,14 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
if (count == 0) {
startActivityForResult(new Intent(this, ImportAccountActivity.class), ImportAccountActivity.REQUEST_CODE_IMPORT_ACCOUNT);
} else {
new Thread(() -> {
executor.submit(() -> {
try {
final Account account = mainViewModel.getLocalAccountByAccountName(SingleAccountHelper.getCurrentSingleSignOnAccount(getApplicationContext()).name);
runOnUiThread(() -> mainViewModel.postCurrentAccount(account));
} catch (NextcloudFilesAppAccountNotFoundException | NoCurrentAccountSelectedException e) {
runOnUiThread(() -> ExceptionDialogFragment.newInstance(e).show(getSupportFragmentManager(), ExceptionDialogFragment.class.getSimpleName()));
}
}).start();
});
}
});
@ -649,7 +653,7 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
try {
AccountImporter.onActivityResult(requestCode, resultCode, data, this, (ssoAccount) -> {
CapabilitiesWorker.update(this);
new Thread(() -> {
executor.submit(() -> {
Log.i(TAG, "Added account: " + "name:" + ssoAccount.name + ", " + ssoAccount.url + ", userId" + ssoAccount.userId);
try {
Log.i(TAG, "Refreshing capabilities for " + ssoAccount.name);
@ -658,11 +662,11 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
mainViewModel.addAccount(ssoAccount.url, ssoAccount.userId, ssoAccount.name, capabilities, displayName, new IResponseCallback<Account>() {
@Override
public void onSuccess(Account result) {
new Thread(() -> {
executor.submit(() -> {
Log.i(TAG, capabilities.toString());
final Account a = mainViewModel.getLocalAccountByAccountName(ssoAccount.name);
runOnUiThread(() -> mainViewModel.postCurrentAccount(a));
}).start();
});
}
@Override
@ -691,7 +695,7 @@ public class MainActivity extends LockedActivity implements NoteClickListener, A
});
}
}
}).start();
});
});
} catch (AccountImportCancelledException e) {
Log.i(TAG, "AccountImport has been cancelled.");

View file

@ -26,6 +26,8 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import it.niedermann.owncloud.notes.BuildConfig;
@ -67,6 +69,8 @@ public class MainViewModel extends AndroidViewModel {
private static final String TAG = MainViewModel.class.getSimpleName();
private final ExecutorService executor = Executors.newCachedThreadPool();
private final SavedStateHandle state;
private static final String KEY_CURRENT_ACCOUNT = "currentAccount";
@ -391,7 +395,7 @@ public class MainViewModel extends AndroidViewModel {
* Updates the network status if necessary and pulls the latest {@link Capabilities} of the given {@param localAccount}
*/
public void synchronizeCapabilities(@NonNull Account localAccount, @NonNull IResponseCallback<Void> callback) {
new Thread(() -> {
executor.submit(() -> {
if (!repo.isSyncPossible()) {
repo.updateNetworkStatus();
}
@ -428,14 +432,14 @@ public class MainViewModel extends AndroidViewModel {
callback.onError(new NetworkErrorException("Sync is not possible, because network is not connected."));
}
}
}, "SYNC_CAPABILITIES").start();
}, "SYNC_CAPABILITIES");
}
/**
* Updates the network status if necessary and pulls the latest notes of the given {@param localAccount}
*/
public void synchronizeNotes(@NonNull Account currentAccount, @NonNull IResponseCallback<Void> callback) {
new Thread(() -> {
executor.submit(() -> {
Log.v(TAG, "[synchronize] - currentAccount: " + currentAccount.getAccountName());
if (!repo.isSyncPossible()) {
repo.updateNetworkStatus();
@ -450,7 +454,7 @@ public class MainViewModel extends AndroidViewModel {
callback.onError(new NetworkErrorException("Sync is not possible, because network is not connected."));
}
}
}, "SYNC_NOTES").start();
}, "SYNC_NOTES");
}
public LiveData<Boolean> getSyncStatus() {
@ -554,12 +558,12 @@ public class MainViewModel extends AndroidViewModel {
} else {
Log.v(TAG, "[getNote] - currentAccount: " + currentAccount.getAccountName());
final MutableLiveData<List<Note>> notes = new MutableLiveData<>();
new Thread(() -> notes.postValue(
executor.submit(() -> notes.postValue(
ids
.stream()
.map(repo::getNoteById)
.collect(Collectors.toList())
)).start();
));
return notes;
}
});

View file

@ -21,6 +21,8 @@ import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import it.niedermann.owncloud.notes.R;
import it.niedermann.owncloud.notes.accountpicker.AccountPickerDialogFragment;
@ -32,6 +34,7 @@ import it.niedermann.owncloud.notes.shared.util.ShareUtil;
public class MultiSelectedActionModeCallback implements Callback {
private final ExecutorService executor = Executors.newSingleThreadExecutor();
@ColorInt
private final int colorAccent;
@NonNull
@ -125,11 +128,9 @@ public class MultiSelectedActionModeCallback implements Callback {
final LiveData<Account> currentAccount$ = mainViewModel.getCurrentAccount();
currentAccount$.observe(lifecycleOwner, account -> {
currentAccount$.removeObservers(lifecycleOwner);
new Thread(() -> {
AccountPickerDialogFragment
.newInstance(new ArrayList<>(mainViewModel.getAccounts()), account.getId())
.show(fragmentManager, AccountPickerDialogFragment.class.getSimpleName());
}).start();
executor.submit(() -> AccountPickerDialogFragment
.newInstance(new ArrayList<>(mainViewModel.getAccounts()), account.getId())
.show(fragmentManager, AccountPickerDialogFragment.class.getSimpleName()));
});
return true;
} else if (itemId == R.id.menu_share) {
@ -139,7 +140,7 @@ public class MultiSelectedActionModeCallback implements Callback {
}
tracker.clearSelection();
new Thread(() -> {
executor.submit(() -> {
if (selection.size() == 1) {
final Note note = mainViewModel.getFullNote(selection.get(0));
ShareUtil.openShareDialog(context, note.getTitle(), note.getContent());
@ -148,7 +149,7 @@ public class MultiSelectedActionModeCallback implements Callback {
context.getResources().getQuantityString(R.plurals.share_multiple, selection.size(), selection.size()),
mainViewModel.collectNoteContents(selection));
}
}).start();
});
return true;
} else if (itemId == R.id.menu_category) {// TODO detect whether all selected notes do have the same category - in this case preselect it
final LiveData<Account> accountLiveData = mainViewModel.getCurrentAccount();

View file

@ -13,8 +13,9 @@ import com.nextcloud.android.sso.exceptions.NoCurrentAccountSelectedException;
import com.nextcloud.android.sso.helper.SingleAccountHelper;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import it.niedermann.owncloud.notes.persistence.NotesDatabase;
import it.niedermann.owncloud.notes.persistence.NotesRepository;
import it.niedermann.owncloud.notes.persistence.entity.Account;
import it.niedermann.owncloud.notes.shared.model.IResponseCallback;
@ -23,7 +24,7 @@ import static androidx.lifecycle.Transformations.distinctUntilChanged;
public class ManageAccountsViewModel extends AndroidViewModel {
private static final String TAG = ManageAccountsViewModel.class.getSimpleName();
private final ExecutorService executor = Executors.newCachedThreadPool();
@NonNull
private final NotesRepository repo;
@ -46,7 +47,7 @@ public class ManageAccountsViewModel extends AndroidViewModel {
}
public void deleteAccount(@NonNull Account account, @NonNull Context context) {
new Thread(() -> {
executor.submit(() -> {
final List<Account> accounts = repo.getAccounts();
for (int i = 0; i < accounts.size(); i++) {
if (accounts.get(i).getId() == account.getId()) {
@ -61,7 +62,7 @@ public class ManageAccountsViewModel extends AndroidViewModel {
break;
}
}
}).start();
});
}
public void selectAccount(@Nullable Account account, @NonNull Context context) {
@ -69,6 +70,6 @@ public class ManageAccountsViewModel extends AndroidViewModel {
}
public void countUnsynchronizedNotes(long accountId, @NonNull IResponseCallback<Long> callback) {
new Thread(() -> callback.onSuccess(repo.countUnsynchronizedNotes(accountId))).start();
executor.submit(() -> callback.onSuccess(repo.countUnsynchronizedNotes(accountId)));
}
}

View file

@ -9,9 +9,13 @@ import androidx.sqlite.db.SupportSQLiteDatabase;
import com.bumptech.glide.Glide;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Migration_18_19 extends Migration {
private static final String TAG = Migration_18_19.class.getSimpleName();
private final ExecutorService executor = Executors.newSingleThreadExecutor();
@NonNull
private final Context context;
@ -27,9 +31,9 @@ public class Migration_18_19 extends Migration {
*/
@Override
public void migrate(@NonNull SupportSQLiteDatabase db) {
new Thread(() -> {
executor.submit(() -> {
Log.i(TAG, "Clearing Glide disk cache");
Glide.get(context.getApplicationContext()).clearDiskCache();
}).start();
});
}
}

View file

@ -11,6 +11,8 @@ import android.util.Log;
import android.widget.RemoteViews;
import java.util.NoSuchElementException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import it.niedermann.owncloud.notes.R;
import it.niedermann.owncloud.notes.persistence.NotesRepository;
@ -18,6 +20,7 @@ import it.niedermann.owncloud.notes.persistence.entity.NotesListWidgetData;
public class NoteListWidget extends AppWidgetProvider {
private static final String TAG = NoteListWidget.class.getSimpleName();
private final ExecutorService executor = Executors.newCachedThreadPool();
static void updateAppWidget(Context context, AppWidgetManager awm, int[] appWidgetIds) {
final NotesRepository repo = NotesRepository.getInstance(context);
@ -83,7 +86,7 @@ public class NoteListWidget extends AppWidgetProvider {
final NotesRepository repo = NotesRepository.getInstance(context);
for (int appWidgetId : appWidgetIds) {
new Thread(() -> repo.removeNoteListWidget(appWidgetId)).start();
executor.submit(() -> repo.removeNoteListWidget(appWidgetId));
}
}

View file

@ -14,6 +14,9 @@ import com.nextcloud.android.sso.exceptions.NextcloudFilesAppAccountNotFoundExce
import com.nextcloud.android.sso.exceptions.NoCurrentAccountSelectedException;
import com.nextcloud.android.sso.helper.SingleAccountHelper;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import it.niedermann.owncloud.notes.LockedActivity;
import it.niedermann.owncloud.notes.NotesApplication;
import it.niedermann.owncloud.notes.R;
@ -34,6 +37,8 @@ import static it.niedermann.owncloud.notes.shared.model.ENavigationCategoryType.
public class NoteListWidgetConfigurationActivity extends LockedActivity {
private static final String TAG = Activity.class.getSimpleName();
private final ExecutorService executor = Executors.newCachedThreadPool();
private int appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
private Account localAccount = null;
@ -104,7 +109,7 @@ public class NoteListWidgetConfigurationActivity extends LockedActivity {
data.setAccountId(localAccount.getId());
data.setThemeMode(NotesApplication.getAppTheme(getApplicationContext()).getModeId());
new Thread(() -> {
executor.submit(() -> {
repo.createOrUpdateNoteListWidgetData(data);
final Intent updateIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, null, getApplicationContext(), NoteListWidget.class)
@ -112,7 +117,7 @@ public class NoteListWidgetConfigurationActivity extends LockedActivity {
setResult(RESULT_OK, updateIntent);
getApplicationContext().sendBroadcast(updateIntent);
finish();
}).start();
});
}
public void onIconClick(NavigationItem item) {
@ -122,7 +127,7 @@ public class NoteListWidgetConfigurationActivity extends LockedActivity {
binding.recyclerView.setAdapter(adapterCategories);
new Thread(() -> {
executor.submit(() -> {
try {
this.localAccount = repo.getAccountByName(SingleAccountHelper.getCurrentSingleSignOnAccount(this).name);
} catch (NextcloudFilesAppAccountNotFoundException | NoCurrentAccountSelectedException e) {
@ -133,7 +138,7 @@ public class NoteListWidgetConfigurationActivity extends LockedActivity {
finish();
}
runOnUiThread(() -> viewModel.getAdapterCategories(localAccount.getId()).observe(this, (navigationItems) -> adapterCategories.setItems(navigationItems)));
}).start();
});
}
@Override

View file

@ -10,6 +10,9 @@ import android.net.Uri;
import android.util.Log;
import android.widget.RemoteViews;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import it.niedermann.owncloud.notes.R;
import it.niedermann.owncloud.notes.edit.BaseNoteFragment;
import it.niedermann.owncloud.notes.edit.EditNoteActivity;
@ -19,6 +22,7 @@ import it.niedermann.owncloud.notes.persistence.entity.SingleNoteWidgetData;
public class SingleNoteWidget extends AppWidgetProvider {
private static final String TAG = SingleNoteWidget.class.getSimpleName();
private final ExecutorService executor = Executors.newCachedThreadPool();
static void updateAppWidget(Context context, AppWidgetManager awm, int[] appWidgetIds) {
final Intent templateIntent = new Intent(context, EditNoteActivity.class);
@ -69,7 +73,7 @@ public class SingleNoteWidget extends AppWidgetProvider {
final NotesRepository repo = NotesRepository.getInstance(context);
for (int appWidgetId : appWidgetIds) {
new Thread(() -> repo.removeSingleNoteWidget(appWidgetId)).start();
executor.submit(() -> repo.removeSingleNoteWidget(appWidgetId));
}
super.onDeleted(context, appWidgetIds);
}

View file

@ -52,7 +52,7 @@ public class SingleNoteWidgetConfigurationActivity extends MainActivity {
int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
new Thread(() -> {
executor.submit(() -> {
try {
mainViewModel.createOrUpdateSingleNoteWidgetData(
new SingleNoteWidgetData(
@ -71,6 +71,6 @@ public class SingleNoteWidgetConfigurationActivity extends MainActivity {
} catch (SQLException e) {
Toast.makeText(this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
}).start();
});
}
}

View file

@ -7,6 +7,8 @@ import android.view.View;
import androidx.annotation.NonNull;
import java.util.Collection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;
public class InterceptedURLSpan extends URLSpan {
@ -14,6 +16,7 @@ public class InterceptedURLSpan extends URLSpan {
private static final String TAG = InterceptedURLSpan.class.getSimpleName();
@NonNull
private final Collection<Function<String, Boolean>> onLinkClickCallbacks;
private final ExecutorService executor = Executors.newCachedThreadPool();
public InterceptedURLSpan(@NonNull Collection<Function<String, Boolean>> onLinkClickCallbacks, String url) {
super(url);
@ -23,7 +26,7 @@ public class InterceptedURLSpan extends URLSpan {
@Override
public void onClick(View widget) {
if (onLinkClickCallbacks.size() > 0) {
new Thread(() -> {
executor.submit(() -> {
for (Function<String, Boolean> callback : onLinkClickCallbacks) {
try {
if (callback.apply(getURL())) {
@ -34,7 +37,7 @@ public class InterceptedURLSpan extends URLSpan {
}
}
super.onClick(widget);
}).start();
});
} else {
super.onClick(widget);
}