FileSyncAdapter.java 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. /**
  2. * ownCloud Android client application
  3. *
  4. * @author Bartek Przybylski
  5. * @author David A. Velasco
  6. * Copyright (C) 2011 Bartek Przybylski
  7. * Copyright (C) 2015 ownCloud Inc.
  8. *
  9. * This program is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2,
  11. * as published by the Free Software Foundation.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. package com.owncloud.android.syncadapter;
  23. import android.accounts.Account;
  24. import android.accounts.AccountsException;
  25. import android.app.NotificationManager;
  26. import android.app.PendingIntent;
  27. import android.content.AbstractThreadedSyncAdapter;
  28. import android.content.ContentProviderClient;
  29. import android.content.ContentResolver;
  30. import android.content.Context;
  31. import android.content.Intent;
  32. import android.content.SyncResult;
  33. import android.os.Bundle;
  34. import com.nextcloud.client.account.User;
  35. import com.nextcloud.client.account.UserAccountManager;
  36. import com.owncloud.android.MainApp;
  37. import com.owncloud.android.R;
  38. import com.owncloud.android.authentication.AuthenticatorActivity;
  39. import com.owncloud.android.datamodel.FileDataStorageManager;
  40. import com.owncloud.android.datamodel.OCFile;
  41. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  42. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  43. import com.owncloud.android.lib.common.utils.Log_OC;
  44. import com.owncloud.android.operations.RefreshFolderOperation;
  45. import com.owncloud.android.operations.SynchronizeFolderOperation;
  46. import com.owncloud.android.operations.UpdateOCVersionOperation;
  47. import com.owncloud.android.ui.activity.ErrorsWhileCopyingHandlerActivity;
  48. import com.owncloud.android.ui.notifications.NotificationUtils;
  49. import com.owncloud.android.utils.DataHolderUtil;
  50. import com.owncloud.android.utils.theme.ThemeColorUtils;
  51. import org.apache.jackrabbit.webdav.DavException;
  52. import java.io.IOException;
  53. import java.util.ArrayList;
  54. import java.util.HashMap;
  55. import java.util.List;
  56. import java.util.Map;
  57. import androidx.annotation.PluralsRes;
  58. import androidx.core.app.NotificationCompat;
  59. import androidx.localbroadcastmanager.content.LocalBroadcastManager;
  60. /**
  61. * Implementation of {@link AbstractThreadedSyncAdapter} responsible for synchronizing
  62. * ownCloud files.
  63. *
  64. * Performs a full synchronization of the account received in {@link #onPerformSync(Account, Bundle,
  65. * String, ContentProviderClient, SyncResult)}.
  66. */
  67. public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
  68. private final static String TAG = FileSyncAdapter.class.getSimpleName();
  69. /** Maximum number of failed folder synchronizations that are supported before finishing
  70. * the synchronization operation */
  71. private static final int MAX_FAILED_RESULTS = 3;
  72. public static final String EVENT_FULL_SYNC_START = FileSyncAdapter.class.getName() +
  73. ".EVENT_FULL_SYNC_START";
  74. public static final String EVENT_FULL_SYNC_END = FileSyncAdapter.class.getName() +
  75. ".EVENT_FULL_SYNC_END";
  76. public static final String EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED =
  77. FileSyncAdapter.class.getName() + ".EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED";
  78. public static final String EXTRA_ACCOUNT_NAME = FileSyncAdapter.class.getName() +
  79. ".EXTRA_ACCOUNT_NAME";
  80. public static final String EXTRA_FOLDER_PATH = FileSyncAdapter.class.getName() +
  81. ".EXTRA_FOLDER_PATH";
  82. public static final String EXTRA_RESULT = FileSyncAdapter.class.getName() + ".EXTRA_RESULT";
  83. /** Time stamp for the current synchronization process, used to distinguish fresh data */
  84. private long mCurrentSyncTime;
  85. /** Flag made 'true' when a request to cancel the synchronization is received */
  86. private boolean mCancellation;
  87. /** Counter for failed operations in the synchronization process */
  88. private int mFailedResultsCounter;
  89. /** Result of the last failed operation */
  90. private RemoteOperationResult mLastFailedResult;
  91. /** Counter of conflicts found between local and remote files */
  92. private int mConflictsFound;
  93. /** Counter of failed operations in synchronization of kept-in-sync files */
  94. private int mFailsInFavouritesFound;
  95. /** Map of remote and local paths to files that where locally stored in a location out
  96. * of the ownCloud folder and couldn't be copied automatically into it */
  97. private Map<String, String> mForgottenLocalFiles;
  98. /** {@link SyncResult} instance to return to the system when the synchronization finish */
  99. private SyncResult mSyncResult;
  100. /**
  101. * Creates a {@link FileSyncAdapter}
  102. *
  103. * {@inheritDoc}
  104. */
  105. public FileSyncAdapter(Context context, boolean autoInitialize, UserAccountManager userAccountManager) {
  106. super(context, autoInitialize, userAccountManager);
  107. }
  108. /**
  109. * Creates a {@link FileSyncAdapter}
  110. *
  111. * {@inheritDoc}
  112. */
  113. public FileSyncAdapter(Context context,
  114. boolean autoInitialize,
  115. boolean allowParallelSyncs,
  116. UserAccountManager userAccountManager) {
  117. super(context, autoInitialize, allowParallelSyncs, userAccountManager);
  118. }
  119. /**
  120. * {@inheritDoc}
  121. */
  122. @Override
  123. public synchronized void onPerformSync(Account account, Bundle extras,
  124. String authority, ContentProviderClient providerClient,
  125. SyncResult syncResult) {
  126. mCancellation = false;
  127. mFailedResultsCounter = 0;
  128. mLastFailedResult = null;
  129. mConflictsFound = 0;
  130. mFailsInFavouritesFound = 0;
  131. mForgottenLocalFiles = new HashMap<String, String>();
  132. mSyncResult = syncResult;
  133. mSyncResult.fullSyncRequested = false;
  134. mSyncResult.delayUntil = (System.currentTimeMillis()/1000) + 3*60*60; // avoid too many automatic synchronizations
  135. this.setAccount(account);
  136. this.setContentProviderClient(providerClient);
  137. this.setStorageManager(new FileDataStorageManager(account, providerClient));
  138. try {
  139. this.initClientForCurrentAccount();
  140. } catch (IOException | AccountsException e) {
  141. /// the account is unknown for the Synchronization Manager, unreachable this context,
  142. // or can not be authenticated; don't try this again
  143. mSyncResult.tooManyRetries = true;
  144. notifyFailedSynchronization();
  145. return;
  146. }
  147. Log_OC.d(TAG, "Synchronization of ownCloud account " + account.name + " starting");
  148. sendLocalBroadcast(EVENT_FULL_SYNC_START, null, null); // message to signal the start
  149. // of the synchronization to the UI
  150. /* When 'true' the process was requested by the user through the user interface;
  151. when 'false', it was requested automatically by the system */
  152. boolean mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
  153. try {
  154. updateOCVersion();
  155. mCurrentSyncTime = System.currentTimeMillis();
  156. if (!mCancellation) {
  157. synchronizeFolder(getStorageManager().getFileByPath(OCFile.ROOT_PATH));
  158. } else {
  159. Log_OC.d(TAG, "Leaving synchronization before synchronizing the root folder " +
  160. "because cancellation request");
  161. }
  162. } finally {
  163. // it's important making this although very unexpected errors occur;
  164. // that's the reason for the finally
  165. if (mFailedResultsCounter > 0 && mIsManualSync) {
  166. /// don't let the system synchronization manager retries MANUAL synchronizations
  167. // (be careful: "MANUAL" currently includes the synchronization requested when
  168. // a new account is created and when the user changes the current account)
  169. mSyncResult.tooManyRetries = true;
  170. /// notify the user about the failure of MANUAL synchronization
  171. notifyFailedSynchronization();
  172. }
  173. if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
  174. notifyFailsInFavourites();
  175. }
  176. if (mForgottenLocalFiles.size() > 0) {
  177. notifyForgottenLocalFiles();
  178. }
  179. sendLocalBroadcast(EVENT_FULL_SYNC_END, null, mLastFailedResult); // message to signal
  180. // the end to the UI
  181. }
  182. }
  183. /**
  184. * Called by system SyncManager when a synchronization is required to be cancelled.
  185. *
  186. * Sets the mCancellation flag to 'true'. THe synchronization will be stopped later,
  187. * before a new folder is fetched. Data of the last folder synchronized will be still
  188. * locally saved.
  189. *
  190. * See {@link #onPerformSync(Account, Bundle, String, ContentProviderClient, SyncResult)}
  191. * and {@link #synchronizeFolder(OCFile)}.
  192. */
  193. @Override
  194. public void onSyncCanceled() {
  195. Log_OC.d(TAG, "Synchronization of " + getAccount().name + " has been requested to cancel");
  196. mCancellation = true;
  197. super.onSyncCanceled();
  198. }
  199. /**
  200. * Updates the locally stored version value of the ownCloud server
  201. */
  202. private void updateOCVersion() {
  203. UpdateOCVersionOperation update = new UpdateOCVersionOperation(getAccount(), getContext());
  204. RemoteOperationResult result = update.execute(getClient());
  205. if (!result.isSuccess()) {
  206. mLastFailedResult = result;
  207. }
  208. }
  209. /**
  210. * Synchronizes the list of files contained in a folder identified with its remote path.
  211. *
  212. * Fetches the list and properties of the files contained in the given folder, including their
  213. * properties, and updates the local database with them.
  214. *
  215. * Enters in the child folders to synchronize their contents also, following a recursive
  216. * depth first strategy.
  217. *
  218. * @param folder Folder to synchronize.
  219. */
  220. private void synchronizeFolder(OCFile folder) {
  221. if (mFailedResultsCounter > MAX_FAILED_RESULTS || isFinisher(mLastFailedResult)) {
  222. return;
  223. }
  224. // folder synchronization
  225. RefreshFolderOperation synchFolderOp = new RefreshFolderOperation(folder,
  226. mCurrentSyncTime,
  227. true,
  228. false,
  229. getStorageManager(),
  230. getUser(),
  231. getContext());
  232. RemoteOperationResult result = synchFolderOp.execute(getClient());
  233. // synchronized folder -> notice to UI - ALWAYS, although !result.isSuccess
  234. sendLocalBroadcast(EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED, folder.getRemotePath(), result);
  235. // check the result of synchronizing the folder
  236. if (result.isSuccess() || result.getCode() == ResultCode.SYNC_CONFLICT) {
  237. if (result.getCode() == ResultCode.SYNC_CONFLICT) {
  238. mConflictsFound += synchFolderOp.getConflictsFound();
  239. mFailsInFavouritesFound += synchFolderOp.getFailsInKeptInSyncFound();
  240. }
  241. if (synchFolderOp.getForgottenLocalFiles().size() > 0) {
  242. mForgottenLocalFiles.putAll(synchFolderOp.getForgottenLocalFiles());
  243. }
  244. if (result.isSuccess()) {
  245. // synchronize children folders
  246. List<OCFile> children = synchFolderOp.getChildren();
  247. // beware of the 'hidden' recursion here!
  248. syncChildren(children);
  249. }
  250. } else if (result.getCode() != ResultCode.FILE_NOT_FOUND) {
  251. // in failures, the statistics for the global result are updated
  252. if (RemoteOperationResult.ResultCode.UNAUTHORIZED.equals(result.getCode())) {
  253. mSyncResult.stats.numAuthExceptions++;
  254. } else if (result.getException() instanceof DavException) {
  255. mSyncResult.stats.numParseExceptions++;
  256. } else if (result.getException() instanceof IOException) {
  257. mSyncResult.stats.numIoExceptions++;
  258. }
  259. mFailedResultsCounter++;
  260. mLastFailedResult = result;
  261. } // else, ResultCode.FILE_NOT_FOUND is ignored, remote folder was
  262. // removed from other thread or other client during the synchronization,
  263. // before this thread fetched its contents
  264. }
  265. /**
  266. * Checks if a failed result should terminate the synchronization process immediately,
  267. * according to OUR OWN POLICY
  268. *
  269. * @param failedResult Remote operation result to check.
  270. * @return 'True' if the result should immediately finish the
  271. * synchronization
  272. */
  273. private boolean isFinisher(RemoteOperationResult failedResult) {
  274. if (failedResult != null) {
  275. RemoteOperationResult.ResultCode code = failedResult.getCode();
  276. return code.equals(RemoteOperationResult.ResultCode.SSL_ERROR)
  277. || code.equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)
  278. || code.equals(RemoteOperationResult.ResultCode.BAD_OC_VERSION)
  279. || code.equals(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
  280. }
  281. return false;
  282. }
  283. /**
  284. * Triggers the synchronization of any folder contained in the list of received files.
  285. *
  286. * No consideration of etag here because it MUST walk down anyway, in case that kept-in-sync files
  287. * have local changes.
  288. *
  289. * @param files Files to recursively synchronize.
  290. */
  291. private void syncChildren(List<OCFile> files) {
  292. int i;
  293. OCFile newFile;
  294. for (i=0; i < files.size() && !mCancellation; i++) {
  295. newFile = files.get(i);
  296. if (newFile.isFolder()) {
  297. synchronizeFolder(newFile);
  298. }
  299. }
  300. if (mCancellation && i <files.size()) {
  301. Log_OC.d(TAG,
  302. "Leaving synchronization before synchronizing " + files.get(i).getRemotePath() +
  303. " due to cancellation request");
  304. }
  305. }
  306. /**
  307. * Sends a message to any application component interested in the progress of the
  308. * synchronization.
  309. *
  310. * @param event Event in the process of synchronization to be notified.
  311. * @param dirRemotePath Remote path of the folder target of the event occurred.
  312. * @param result Result of an individual {@link SynchronizeFolderOperation},
  313. * if completed; may be null.
  314. */
  315. private void sendLocalBroadcast(String event, String dirRemotePath,
  316. RemoteOperationResult result) {
  317. Log_OC.d(TAG, "Send broadcast " + event);
  318. Intent intent = new Intent(event);
  319. intent.putExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME, getAccount().name);
  320. if (dirRemotePath != null) {
  321. intent.putExtra(FileSyncAdapter.EXTRA_FOLDER_PATH, dirRemotePath);
  322. }
  323. if (result != null) {
  324. DataHolderUtil dataHolderUtil = DataHolderUtil.getInstance();
  325. String dataHolderItemId = dataHolderUtil.nextItemId();
  326. dataHolderUtil.save(dataHolderUtil.nextItemId(), result);
  327. intent.putExtra(FileSyncAdapter.EXTRA_RESULT, dataHolderItemId);
  328. }
  329. intent.setPackage(getContext().getPackageName());
  330. LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
  331. }
  332. /**
  333. * Notifies the user about a failed synchronization through the status notification bar
  334. */
  335. private void notifyFailedSynchronization() {
  336. NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
  337. boolean needsToUpdateCredentials = mLastFailedResult != null
  338. && ResultCode.UNAUTHORIZED.equals(mLastFailedResult.getCode());
  339. if (needsToUpdateCredentials) {
  340. // let the user update credentials with one click
  341. Intent updateAccountCredentials = new Intent(getContext(), AuthenticatorActivity.class);
  342. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
  343. updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION,
  344. AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
  345. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  346. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
  347. updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
  348. notificationBuilder
  349. .setTicker(i18n(R.string.sync_fail_ticker_unauthorized))
  350. .setContentTitle(i18n(R.string.sync_fail_ticker_unauthorized))
  351. .setContentIntent(PendingIntent.getActivity(
  352. getContext(), (int)System.currentTimeMillis(), updateAccountCredentials,
  353. PendingIntent.FLAG_ONE_SHOT
  354. ))
  355. .setContentText(i18n(R.string.sync_fail_content_unauthorized, getAccount().name));
  356. } else {
  357. notificationBuilder
  358. .setTicker(i18n(R.string.sync_fail_ticker))
  359. .setContentTitle(i18n(R.string.sync_fail_ticker))
  360. .setContentText(i18n(R.string.sync_fail_content, getAccount().name));
  361. }
  362. showNotification(R.string.sync_fail_ticker, notificationBuilder);
  363. }
  364. /**
  365. * Notifies the user about conflicts and strange fails when trying to synchronize the contents
  366. * of kept-in-sync files.
  367. *
  368. * By now, we won't consider a failed synchronization.
  369. */
  370. private void notifyFailsInFavourites() {
  371. if (mFailedResultsCounter > 0) {
  372. NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
  373. notificationBuilder.setTicker(i18n(R.string.sync_fail_in_favourites_ticker));
  374. // TODO put something smart in the contentIntent below
  375. notificationBuilder
  376. .setContentIntent(PendingIntent.getActivity(
  377. getContext(), (int) System.currentTimeMillis(), new Intent(), 0
  378. ))
  379. .setContentTitle(i18n(R.string.sync_fail_in_favourites_ticker))
  380. .setContentText(getQuantityString(
  381. R.plurals.sync_fail_in_favourites_content,
  382. mFailedResultsCounter,
  383. mFailedResultsCounter + mConflictsFound, mConflictsFound
  384. )
  385. );
  386. showNotification(R.string.sync_fail_in_favourites_ticker, notificationBuilder);
  387. } else {
  388. NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
  389. notificationBuilder.setTicker(i18n(R.string.sync_conflicts_in_favourites_ticker));
  390. // TODO put something smart in the contentIntent below
  391. notificationBuilder
  392. .setContentIntent(PendingIntent.getActivity(
  393. getContext(), (int) System.currentTimeMillis(), new Intent(), 0
  394. ))
  395. .setContentTitle(i18n(R.string.sync_conflicts_in_favourites_ticker))
  396. .setContentText(i18n(R.string.sync_conflicts_in_favourites_ticker, mConflictsFound));
  397. showNotification(R.string.sync_conflicts_in_favourites_ticker, notificationBuilder);
  398. }
  399. }
  400. /**
  401. * Notifies the user about local copies of files out of the ownCloud local directory that
  402. * were 'forgotten' because copying them inside the ownCloud local directory was not possible.
  403. *
  404. * We don't want links to files out of the ownCloud local directory (foreign files) anymore.
  405. * It's easy to have synchronization problems if a local file is linked to more than one
  406. * remote file.
  407. *
  408. * We won't consider a synchronization as failed when foreign files can not be copied to
  409. * the ownCloud local directory.
  410. */
  411. private void notifyForgottenLocalFiles() {
  412. NotificationCompat.Builder notificationBuilder = createNotificationBuilder();
  413. notificationBuilder.setTicker(i18n(R.string.sync_foreign_files_forgotten_ticker));
  414. /// includes a pending intent in the notification showing a more detailed explanation
  415. Intent explanationIntent = new Intent(getContext(), ErrorsWhileCopyingHandlerActivity.class);
  416. explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_ACCOUNT, getAccount());
  417. ArrayList<String> remotePaths = new ArrayList<String>();
  418. ArrayList<String> localPaths = new ArrayList<String>();
  419. remotePaths.addAll(mForgottenLocalFiles.keySet());
  420. localPaths.addAll(mForgottenLocalFiles.values());
  421. explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_LOCAL_PATHS, localPaths);
  422. explanationIntent.putExtra(ErrorsWhileCopyingHandlerActivity.EXTRA_REMOTE_PATHS, remotePaths);
  423. explanationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  424. notificationBuilder
  425. .setContentIntent(PendingIntent.getActivity(
  426. getContext(), (int) System.currentTimeMillis(), explanationIntent, 0
  427. ))
  428. .setContentTitle(i18n(R.string.sync_foreign_files_forgotten_ticker))
  429. .setContentText(getQuantityString(
  430. R.plurals.sync_foreign_files_forgotten_content,
  431. mForgottenLocalFiles.size(),
  432. mForgottenLocalFiles.size(),
  433. i18n(R.string.app_name))
  434. );
  435. showNotification(R.string.sync_foreign_files_forgotten_ticker, notificationBuilder);
  436. }
  437. /**
  438. * Creates a notification builder with some commonly used settings
  439. *
  440. * @return notification builder
  441. */
  442. private NotificationCompat.Builder createNotificationBuilder() {
  443. NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext());
  444. notificationBuilder.setSmallIcon(R.drawable.notification_icon).setAutoCancel(true);
  445. notificationBuilder.setColor(ThemeColorUtils.primaryColor(getContext(), true));
  446. return notificationBuilder;
  447. }
  448. /**
  449. * Builds and shows the notification
  450. *
  451. * @param id
  452. * @param builder
  453. */
  454. private void showNotification(int id, NotificationCompat.Builder builder) {
  455. NotificationManager notificationManager = (NotificationManager) getContext().
  456. getSystemService(Context.NOTIFICATION_SERVICE);
  457. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
  458. builder.setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_FILE_SYNC);
  459. }
  460. notificationManager.notify(id, builder.build());
  461. }
  462. /**
  463. * Shorthand translation
  464. *
  465. * @param key
  466. * @param args
  467. * @return
  468. */
  469. private String i18n(int key, Object... args) {
  470. return getContext().getString(key, args);
  471. }
  472. /**
  473. * Shorthand plurals translation.
  474. *
  475. * @param id The desired plurals identifier.
  476. * @param quantity The number used to get the correct string for the current language's plural rules.
  477. * @param formatArgs The format arguments that will be used for substitution.
  478. * @return formatted, plurals respecting string
  479. */
  480. private String getQuantityString(@PluralsRes int id, int quantity, Object... formatArgs) {
  481. return getContext().getResources().getQuantityString(id, quantity, formatArgs);
  482. }
  483. }