version code is now read by package an not by BuildConfig and therefore working with ant
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / Preferences.java
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.ui.activity;
23
24 import android.accounts.Account;
25 import android.accounts.AccountManager;
26 import android.accounts.AccountManagerCallback;
27 import android.accounts.AccountManagerFuture;
28 import android.content.ComponentName;
29 import android.content.Context;
30 import android.content.Intent;
31 import android.content.ServiceConnection;
32 import android.content.SharedPreferences;
33 import android.content.pm.PackageInfo;
34 import android.content.pm.PackageManager.NameNotFoundException;
35 import android.content.res.Configuration;
36 import android.net.Uri;
37 import android.os.AsyncTask;
38 import android.os.Bundle;
39 import android.os.Handler;
40 import android.os.IBinder;
41 import android.preference.CheckBoxPreference;
42 import android.preference.Preference;
43 import android.preference.Preference.OnPreferenceChangeListener;
44 import android.preference.Preference.OnPreferenceClickListener;
45 import android.preference.PreferenceActivity;
46 import android.preference.PreferenceCategory;
47 import android.preference.PreferenceManager;
48 import android.support.annotation.LayoutRes;
49 import android.support.annotation.Nullable;
50 import android.support.v7.app.ActionBar;
51 import android.support.v7.app.AlertDialog;
52 import android.support.v7.app.AppCompatDelegate;
53 import android.support.v7.widget.Toolbar;
54 import android.view.ContextMenu;
55 import android.view.ContextMenu.ContextMenuInfo;
56 import android.view.Menu;
57 import android.view.MenuInflater;
58 import android.view.MenuItem;
59 import android.view.View;
60 import android.view.ViewGroup;
61 import android.widget.AdapterView;
62 import android.widget.AdapterView.OnItemLongClickListener;
63 import android.widget.ArrayAdapter;
64 import android.widget.ListAdapter;
65 import android.widget.ListView;
66 import android.widget.Toast;
67
68 import com.owncloud.android.BuildConfig;
69 import com.owncloud.android.MainApp;
70 import com.owncloud.android.R;
71 import com.owncloud.android.authentication.AccountUtils;
72 import com.owncloud.android.authentication.AuthenticatorActivity;
73 import com.owncloud.android.datamodel.FileDataStorageManager;
74 import com.owncloud.android.datamodel.OCFile;
75 import com.owncloud.android.datamodel.ThumbnailsCacheManager;
76 import com.owncloud.android.db.DbHandler;
77 import com.owncloud.android.files.FileOperationsHelper;
78 import com.owncloud.android.files.services.FileDownloader;
79 import com.owncloud.android.files.services.FileUploader;
80 import com.owncloud.android.lib.common.utils.Log_OC;
81 import com.owncloud.android.services.OperationsService;
82 import com.owncloud.android.ui.RadioButtonPreference;
83 import com.owncloud.android.utils.DisplayUtils;
84
85 import java.io.BufferedReader;
86 import java.io.IOException;
87 import java.io.InputStreamReader;
88 import java.net.MalformedURLException;
89 import java.net.URL;
90 import java.util.concurrent.ExecutionException;
91
92
93 /**
94 * An Activity that allows the user to change the application's settings.
95 *
96 * It proxies the necessary calls via {@link android.support.v7.app.AppCompatDelegate} to be used
97 * with AppCompat.
98 */
99 public class Preferences extends PreferenceActivity
100 implements AccountManagerCallback<Boolean>, ComponentsGetter {
101
102 private static final String TAG = "OwnCloudPreferences";
103
104 private static final int ACTION_SELECT_UPLOAD_PATH = 1;
105 private static final int ACTION_SELECT_UPLOAD_VIDEO_PATH = 2;
106
107 private DbHandler mDbHandler;
108 private CheckBoxPreference pCode;
109 private Preference pAboutApp;
110 private AppCompatDelegate mDelegate;
111
112 private PreferenceCategory mAccountsPrefCategory = null;
113 private final Handler mHandler = new Handler();
114 private String mAccountName;
115 private boolean mShowContextMenu = false;
116 private String mUploadPath;
117 private PreferenceCategory mPrefInstantUploadCategory;
118 private Preference mPrefInstantUpload;
119 private Preference mPrefInstantUploadPath;
120 private Preference mPrefInstantUploadPathWiFi;
121 private Preference mPrefInstantVideoUpload;
122 private Preference mPrefInstantVideoUploadPath;
123 private Preference mPrefInstantVideoUploadPathWiFi;
124 private String mUploadVideoPath;
125
126 protected FileDownloader.FileDownloaderBinder mDownloaderBinder = null;
127 protected FileUploader.FileUploaderBinder mUploaderBinder = null;
128 private ServiceConnection mDownloadServiceConnection, mUploadServiceConnection = null;
129
130 @SuppressWarnings("deprecation")
131 @Override
132 public void onCreate(Bundle savedInstanceState) {
133 getDelegate().installViewFactory();
134 getDelegate().onCreate(savedInstanceState);
135 super.onCreate(savedInstanceState);
136 mDbHandler = new DbHandler(getBaseContext());
137 addPreferencesFromResource(R.xml.preferences);
138
139 ActionBar actionBar = getSupportActionBar();
140 actionBar.setDisplayHomeAsUpEnabled(true);
141 actionBar.setTitle(R.string.actionbar_settings);
142
143 // For adding content description tag to a title field in the action bar
144 int actionBarTitleId = getResources().getIdentifier("action_bar_title", "id", "android");
145 View actionBarTitleView = getWindow().getDecorView().findViewById(actionBarTitleId);
146 if (actionBarTitleView != null) { // it's null in Android 2.x
147 getWindow().getDecorView().findViewById(actionBarTitleId).
148 setContentDescription(getString(R.string.actionbar_settings));
149 }
150
151 // Load the accounts category for adding the list of accounts
152 mAccountsPrefCategory = (PreferenceCategory) findPreference("accounts_category");
153
154 ListView listView = getListView();
155 listView.setOnItemLongClickListener(new OnItemLongClickListener() {
156 @Override
157 public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
158 ListView listView = (ListView) parent;
159 ListAdapter listAdapter = listView.getAdapter();
160 Object obj = listAdapter.getItem(position);
161
162 if (obj != null && obj instanceof RadioButtonPreference) {
163 mShowContextMenu = true;
164 mAccountName = ((RadioButtonPreference) obj).getKey();
165
166 String[] items = {
167 getResources().getString(R.string.change_password),
168 getResources().getString(R.string.delete_account)
169 };
170 final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Preferences.this);
171 View convertView = getLayoutInflater().inflate(R.layout.alert_dialog_list_view, null);
172 alertDialogBuilder.setView(convertView);
173 ListView lv = (ListView) convertView.findViewById(R.id.list);
174 ArrayAdapter<String> adapter = new ArrayAdapter<String>(
175 Preferences.this,R.layout.simple_dialog_list_item,items);
176 lv.setAdapter(adapter);
177
178 //Setup proper inline listener
179 final AlertDialog alertDialog = alertDialogBuilder.create();
180 lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
181 @Override
182 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
183 AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
184 Account accounts[] = am.getAccountsByType(MainApp.getAccountType());
185 for (Account a : accounts) {
186 if (a.name.equals(mAccountName)) {
187 if (position==0) {
188
189 // Change account password
190 Intent updateAccountCredentials = new Intent(Preferences.this, AuthenticatorActivity.class);
191 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, a);
192 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION,
193 AuthenticatorActivity.ACTION_UPDATE_TOKEN);
194 startActivity(updateAccountCredentials);
195 alertDialog.cancel();
196
197 } else if (position==1) {
198
199 // Remove account
200 am.removeAccount(a, Preferences.this, mHandler);
201 Log_OC.d(TAG, "Remove an account " + a.name);
202 alertDialog.cancel();
203 }
204 }
205 }
206 }
207 });
208 alertDialog.show();
209
210 View.OnLongClickListener longListener = (View.OnLongClickListener) obj;
211 return longListener.onLongClick(view);
212 }
213 return false;
214 }
215 });
216
217 // Load package info
218 String temp;
219 try {
220 PackageInfo pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
221 temp = pkg.versionName;
222 } catch (NameNotFoundException e) {
223 temp = "";
224 Log_OC.e(TAG, "Error while showing about dialog", e);
225 }
226 final String appVersion = temp;
227
228 // Register context menu for list of preferences.
229 registerForContextMenu(getListView());
230
231 pCode = (CheckBoxPreference) findPreference("set_pincode");
232 if (pCode != null){
233 pCode.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
234 @Override
235 public boolean onPreferenceChange(Preference preference, Object newValue) {
236 Intent i = new Intent(getApplicationContext(), PassCodeActivity.class);
237 Boolean enable = (Boolean) newValue;
238 i.setAction(
239 enable.booleanValue() ? PassCodeActivity.ACTION_ENABLE :
240 PassCodeActivity.ACTION_DISABLE
241 );
242 startActivity(i);
243
244 return true;
245 }
246 });
247
248 }
249
250 final Preference pCacheSize = findPreference("pref_cache_size");
251 if (pCacheSize != null){
252 final SharedPreferences appPrefs =
253 PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
254 Long cacheSize = ThumbnailsCacheManager.getMaxSize();
255 pCacheSize.setSummary(cacheSize + " Mb");
256 pCacheSize.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
257 @Override
258 public boolean onPreferenceChange(Preference preference, Object newValue) {
259 Long size = Long.decode((String) newValue);
260 if (ThumbnailsCacheManager.setMaxSize(size)){
261 appPrefs.edit().putString("pref_cache_size", size.toString());
262 pCacheSize.setSummary(size + " MB");
263 return true;
264 } else {
265 return false;
266 }
267 }
268 });
269 }
270
271 PreferenceCategory preferenceCategory = (PreferenceCategory) findPreference("more");
272
273 boolean helpEnabled = getResources().getBoolean(R.bool.help_enabled);
274 Preference pHelp = findPreference("help");
275 if (pHelp != null ){
276 if (helpEnabled) {
277 pHelp.setOnPreferenceClickListener(new OnPreferenceClickListener() {
278 @Override
279 public boolean onPreferenceClick(Preference preference) {
280 String helpWeb =(String) getText(R.string.url_help);
281 if (helpWeb != null && helpWeb.length() > 0) {
282 Uri uriUrl = Uri.parse(helpWeb);
283 Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
284 startActivity(intent);
285 }
286 return true;
287 }
288 });
289 } else {
290 preferenceCategory.removePreference(pHelp);
291 }
292
293 }
294
295 if (BuildConfig.DEBUG) {
296 Preference pLog = findPreference("log");
297 if (pLog != null ){
298 pLog.setOnPreferenceClickListener(new OnPreferenceClickListener() {
299 @Override
300 public boolean onPreferenceClick(Preference preference) {
301 Intent loggerIntent = new Intent(getApplicationContext(),
302 LogHistoryActivity.class);
303 startActivity(loggerIntent);
304 return true;
305 }
306 });
307 }
308 }
309
310 boolean recommendEnabled = getResources().getBoolean(R.bool.recommend_enabled);
311 Preference pRecommend = findPreference("recommend");
312 if (pRecommend != null){
313 if (recommendEnabled) {
314 pRecommend.setOnPreferenceClickListener(new OnPreferenceClickListener() {
315 @Override
316 public boolean onPreferenceClick(Preference preference) {
317
318 Intent intent = new Intent(Intent.ACTION_SENDTO);
319 intent.setType("text/plain");
320 intent.setData(Uri.parse(getString(R.string.mail_recommend)));
321 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
322
323 String appName = getString(R.string.app_name);
324 String downloadUrl = getString(R.string.url_app_download);
325 Account currentAccount = AccountUtils.
326 getCurrentOwnCloudAccount(Preferences.this);
327 String username = currentAccount.name.substring(0,
328 currentAccount.name.lastIndexOf('@'));
329
330 String recommendSubject = String.format(getString(R.string.recommend_subject),
331 appName);
332 String recommendText = String.format(getString(R.string.recommend_text),
333 appName, downloadUrl);
334
335 intent.putExtra(Intent.EXTRA_SUBJECT, recommendSubject);
336 intent.putExtra(Intent.EXTRA_TEXT, recommendText);
337 startActivity(intent);
338
339 return(true);
340
341 }
342 });
343 } else {
344 preferenceCategory.removePreference(pRecommend);
345 }
346
347 }
348
349 boolean feedbackEnabled = getResources().getBoolean(R.bool.feedback_enabled);
350 Preference pFeedback = findPreference("feedback");
351 if (pFeedback != null){
352 if (feedbackEnabled) {
353 pFeedback.setOnPreferenceClickListener(new OnPreferenceClickListener() {
354 @Override
355 public boolean onPreferenceClick(Preference preference) {
356 String feedbackMail =(String) getText(R.string.mail_feedback);
357 String feedback =(String) getText(R.string.prefs_feedback) + " - android v" + appVersion;
358 Intent intent = new Intent(Intent.ACTION_SENDTO);
359 intent.setType("text/plain");
360 intent.putExtra(Intent.EXTRA_SUBJECT, feedback);
361
362 intent.setData(Uri.parse(feedbackMail));
363 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
364 startActivity(intent);
365
366 return true;
367 }
368 });
369 } else {
370 preferenceCategory.removePreference(pFeedback);
371 }
372
373 }
374
375 boolean imprintEnabled = getResources().getBoolean(R.bool.imprint_enabled);
376 Preference pImprint = findPreference("imprint");
377 if (pImprint != null) {
378 if (imprintEnabled) {
379 pImprint.setOnPreferenceClickListener(new OnPreferenceClickListener() {
380 @Override
381 public boolean onPreferenceClick(Preference preference) {
382 String imprintWeb = (String) getText(R.string.url_imprint);
383 if (imprintWeb != null && imprintWeb.length() > 0) {
384 Uri uriUrl = Uri.parse(imprintWeb);
385 Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
386 startActivity(intent);
387 }
388 //ImprintDialog.newInstance(true).show(preference.get, "IMPRINT_DIALOG");
389 return true;
390 }
391 });
392 } else {
393 preferenceCategory.removePreference(pImprint);
394 }
395 }
396
397 mPrefInstantUploadPath = findPreference("instant_upload_path");
398 if (mPrefInstantUploadPath != null){
399
400 mPrefInstantUploadPath.setOnPreferenceClickListener(new OnPreferenceClickListener() {
401 @Override
402 public boolean onPreferenceClick(Preference preference) {
403 if (!mUploadPath.endsWith(OCFile.PATH_SEPARATOR)) {
404 mUploadPath += OCFile.PATH_SEPARATOR;
405 }
406 Intent intent = new Intent(Preferences.this, UploadPathActivity.class);
407 intent.putExtra(UploadPathActivity.KEY_INSTANT_UPLOAD_PATH, mUploadPath);
408 startActivityForResult(intent, ACTION_SELECT_UPLOAD_PATH);
409 return true;
410 }
411 });
412 }
413
414 mPrefInstantUploadCategory =
415 (PreferenceCategory) findPreference("instant_uploading_category");
416
417 mPrefInstantUploadPathWiFi = findPreference("instant_upload_on_wifi");
418 mPrefInstantUpload = findPreference("instant_uploading");
419
420 toggleInstantPictureOptions(((CheckBoxPreference) mPrefInstantUpload).isChecked());
421
422 mPrefInstantUpload.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
423
424 @Override
425 public boolean onPreferenceChange(Preference preference, Object newValue) {
426 toggleInstantPictureOptions((Boolean) newValue);
427 return true;
428 }
429 });
430
431 mPrefInstantVideoUploadPath = findPreference("instant_video_upload_path");
432 if (mPrefInstantVideoUploadPath != null){
433
434 mPrefInstantVideoUploadPath.setOnPreferenceClickListener(new OnPreferenceClickListener() {
435 @Override
436 public boolean onPreferenceClick(Preference preference) {
437 if (!mUploadVideoPath.endsWith(OCFile.PATH_SEPARATOR)) {
438 mUploadVideoPath += OCFile.PATH_SEPARATOR;
439 }
440 Intent intent = new Intent(Preferences.this, UploadPathActivity.class);
441 intent.putExtra(UploadPathActivity.KEY_INSTANT_UPLOAD_PATH,
442 mUploadVideoPath);
443 startActivityForResult(intent, ACTION_SELECT_UPLOAD_VIDEO_PATH);
444 return true;
445 }
446 });
447 }
448
449 mPrefInstantVideoUploadPathWiFi = findPreference("instant_video_upload_on_wifi");
450 mPrefInstantVideoUpload = findPreference("instant_video_uploading");
451 toggleInstantVideoOptions(((CheckBoxPreference) mPrefInstantVideoUpload).isChecked());
452
453 mPrefInstantVideoUpload.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
454
455 @Override
456 public boolean onPreferenceChange(Preference preference, Object newValue) {
457 toggleInstantVideoOptions((Boolean) newValue);
458 return true;
459 }
460 });
461
462 /* About App */
463 pAboutApp = (Preference) findPreference("about_app");
464 if (pAboutApp != null) {
465 pAboutApp.setTitle(String.format(getString(R.string.about_android), getString(R.string.app_name)));
466 pAboutApp.setSummary(String.format(getString(R.string.about_version), BuildConfig.VERSION_CODE));
467 }
468
469 loadInstantUploadPath();
470 loadInstantUploadVideoPath();
471
472 /* ComponentsGetter */
473 mDownloadServiceConnection = newTransferenceServiceConnection();
474 if (mDownloadServiceConnection != null) {
475 bindService(new Intent(this, FileDownloader.class), mDownloadServiceConnection,
476 Context.BIND_AUTO_CREATE);
477 }
478 mUploadServiceConnection = newTransferenceServiceConnection();
479 if (mUploadServiceConnection != null) {
480 bindService(new Intent(this, FileUploader.class), mUploadServiceConnection,
481 Context.BIND_AUTO_CREATE);
482 }
483
484 /* Link to Beta apks */
485 Preference pBetaLink = findPreference("beta_link");
486 if (pBetaLink != null ){
487 pBetaLink.setOnPreferenceClickListener(new OnPreferenceClickListener() {
488 @Override
489 public boolean onPreferenceClick(Preference preference) {
490 Integer latestVersion = -1;
491 Integer currentVersion = -1;
492 try {
493 currentVersion = getPackageManager().getPackageInfo
494 (getPackageName(), 0).versionCode;
495 LoadingVersionNumberTask loadTask = new LoadingVersionNumberTask();
496 loadTask.execute();
497 latestVersion = loadTask.get();
498 } catch (InterruptedException | ExecutionException e) {
499 e.printStackTrace();
500 } catch (NameNotFoundException e) {
501 e.printStackTrace();
502 }
503 if (latestVersion == -1 || currentVersion == -1) {
504 Toast.makeText(getApplicationContext(), "No information available!",
505 Toast.LENGTH_SHORT).show();
506 }
507 if (latestVersion > currentVersion) {
508 String betaLinkWeb = (String) getText(R.string.beta_link) +
509 latestVersion + ".apk";
510 if (betaLinkWeb != null && betaLinkWeb.length() > 0) {
511 Uri uriUrl = Uri.parse(betaLinkWeb);
512 Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
513 startActivity(intent);
514 return true;
515 }
516 } else {
517 Toast.makeText(getApplicationContext(), "No new version available!",
518 Toast.LENGTH_SHORT).show();
519 return true;
520 }
521 return true;
522 }
523 });
524 }
525
526 /* Link to Beta apks */
527 Preference pChangelogLink = findPreference("changelog_link");
528 if (pChangelogLink != null) {
529 pChangelogLink.setOnPreferenceClickListener(new OnPreferenceClickListener() {
530 @Override
531 public boolean onPreferenceClick(Preference preference) {
532 String betaLinkWeb = getString(R.string.changelog);
533 if (betaLinkWeb != null && betaLinkWeb.length() > 0) {
534 Uri uriUrl = Uri.parse(betaLinkWeb);
535 Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
536 startActivity(intent);
537 return true;
538 }
539 return true;
540 }
541 });
542 }
543 }
544
545 private void toggleInstantPictureOptions(Boolean value){
546 if (value){
547 mPrefInstantUploadCategory.addPreference(mPrefInstantUploadPathWiFi);
548 mPrefInstantUploadCategory.addPreference(mPrefInstantUploadPath);
549 } else {
550 // mPrefInstantUploadCategory.removePreference(mPrefInstantUploadPathWiFi);
551 // mPrefInstantUploadCategory.removePreference(mPrefInstantUploadPath);
552 }
553 }
554
555 private void toggleInstantVideoOptions(Boolean value){
556 if (value){
557 mPrefInstantUploadCategory.addPreference(mPrefInstantVideoUploadPathWiFi);
558 mPrefInstantUploadCategory.addPreference(mPrefInstantVideoUploadPath);
559 } else {
560 // mPrefInstantUploadCategory.removePreference(mPrefInstantVideoUploadPathWiFi);
561 // mPrefInstantUploadCategory.removePreference(mPrefInstantVideoUploadPath);
562 }
563 }
564
565 @Override
566 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
567
568 // Filter for only showing contextual menu when long press on the
569 // accounts
570 if (mShowContextMenu) {
571 getMenuInflater().inflate(R.menu.account_picker_long_click, menu);
572 mShowContextMenu = false;
573 }
574 super.onCreateContextMenu(menu, v, menuInfo);
575 }
576
577 @Override
578 public void run(AccountManagerFuture<Boolean> future) {
579 if (future.isDone()) {
580 // after remove account
581 Account account = new Account(mAccountName, MainApp.getAccountType());
582 if (!AccountUtils.exists(account, MainApp.getAppContext())) {
583 // Cancel tranfers
584 if (mUploaderBinder != null) {
585 mUploaderBinder.cancel(account);
586 }
587 if (mDownloaderBinder != null) {
588 mDownloaderBinder.cancel(account);
589 }
590 }
591
592 Account a = AccountUtils.getCurrentOwnCloudAccount(this);
593 String accountName = "";
594 if (a == null) {
595 Account[] accounts = AccountManager.get(this)
596 .getAccountsByType(MainApp.getAccountType());
597 if (accounts.length != 0)
598 accountName = accounts[0].name;
599 AccountUtils.setCurrentOwnCloudAccount(this, accountName);
600 }
601 addAccountsCheckboxPreferences();
602 }
603 }
604
605 @Override
606 protected void onResume() {
607 super.onResume();
608 SharedPreferences appPrefs =
609 PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
610 boolean state = appPrefs.getBoolean("set_pincode", false);
611 pCode.setChecked(state);
612
613 // Populate the accounts category with the list of accounts
614 addAccountsCheckboxPreferences();
615 }
616
617 @Override
618 public boolean onCreateOptionsMenu(Menu menu) {
619 super.onCreateOptionsMenu(menu);
620 return true;
621 }
622
623 @Override
624 public boolean onMenuItemSelected(int featureId, MenuItem item) {
625 super.onMenuItemSelected(featureId, item);
626 Intent intent;
627
628 switch (item.getItemId()) {
629 case android.R.id.home:
630 intent = new Intent(getBaseContext(), FileDisplayActivity.class);
631 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
632 startActivity(intent);
633 break;
634 default:
635 Log_OC.w(TAG, "Unknown menu item triggered");
636 return false;
637 }
638 return true;
639 }
640
641 @Override
642 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
643 super.onActivityResult(requestCode, resultCode, data);
644
645 if (requestCode == ACTION_SELECT_UPLOAD_PATH && resultCode == RESULT_OK){
646
647 OCFile folderToUpload =
648 (OCFile) data.getParcelableExtra(UploadPathActivity.EXTRA_FOLDER);
649
650 mUploadPath = folderToUpload.getRemotePath();
651
652 mUploadPath = DisplayUtils.getPathWithoutLastSlash(mUploadPath);
653
654 // Show the path on summary preference
655 mPrefInstantUploadPath.setSummary(mUploadPath);
656
657 saveInstantUploadPathOnPreferences();
658
659 } else if (requestCode == ACTION_SELECT_UPLOAD_VIDEO_PATH && resultCode == RESULT_OK){
660
661 OCFile folderToUploadVideo =
662 (OCFile) data.getParcelableExtra(UploadPathActivity.EXTRA_FOLDER);
663
664 mUploadVideoPath = folderToUploadVideo.getRemotePath();
665
666 mUploadVideoPath = DisplayUtils.getPathWithoutLastSlash(mUploadVideoPath);
667
668 // Show the video path on summary preference
669 mPrefInstantVideoUploadPath.setSummary(mUploadVideoPath);
670
671 saveInstantUploadVideoPathOnPreferences();
672 }
673 }
674
675 public ActionBar getSupportActionBar() {
676 return getDelegate().getSupportActionBar();
677 }
678
679 public void setSupportActionBar(@Nullable Toolbar toolbar) {
680 getDelegate().setSupportActionBar(toolbar);
681 }
682
683 @Override
684 public MenuInflater getMenuInflater() {
685 return getDelegate().getMenuInflater();
686 }
687
688 @Override
689 public void setContentView(@LayoutRes int layoutResID) {
690 getDelegate().setContentView(layoutResID);
691 }
692 @Override
693 public void setContentView(View view) {
694 getDelegate().setContentView(view);
695 }
696
697 @Override
698 public void setContentView(View view, ViewGroup.LayoutParams params) {
699 getDelegate().setContentView(view, params);
700 }
701
702 @Override
703 public void addContentView(View view, ViewGroup.LayoutParams params) {
704 getDelegate().addContentView(view, params);
705 }
706
707 @Override
708 protected void onPostResume() {
709 super.onPostResume();
710 getDelegate().onPostResume();
711 }
712
713 @Override
714 protected void onTitleChanged(CharSequence title, int color) {
715 super.onTitleChanged(title, color);
716 getDelegate().setTitle(title);
717 }
718
719 @Override
720 public void onConfigurationChanged(Configuration newConfig) {
721 super.onConfigurationChanged(newConfig);
722 getDelegate().onConfigurationChanged(newConfig);
723 }
724
725 @Override
726 protected void onPostCreate(Bundle savedInstanceState) {
727 super.onPostCreate(savedInstanceState);
728 getDelegate().onPostCreate(savedInstanceState);
729 }
730
731 @Override
732 protected void onDestroy() {
733 mDbHandler.close();
734
735 if (mDownloadServiceConnection != null) {
736 unbindService(mDownloadServiceConnection);
737 mDownloadServiceConnection = null;
738 }
739 if (mUploadServiceConnection != null) {
740 unbindService(mUploadServiceConnection);
741 mUploadServiceConnection = null;
742 }
743
744 super.onDestroy();
745 getDelegate().onDestroy();
746 }
747
748 @Override
749 protected void onStop() {
750 super.onStop();
751 getDelegate().onStop();
752 }
753
754 public void invalidateOptionsMenu() {
755 getDelegate().invalidateOptionsMenu();
756 }
757
758 private AppCompatDelegate getDelegate() {
759 if (mDelegate == null) {
760 mDelegate = AppCompatDelegate.create(this, null);
761 }
762 return mDelegate;
763 }
764
765 /**
766 * Create the list of accounts that has been added into the app
767 */
768 @SuppressWarnings("deprecation")
769 private void addAccountsCheckboxPreferences() {
770
771 // Remove accounts in case list is refreshing for avoiding to have
772 // duplicate items
773 if (mAccountsPrefCategory.getPreferenceCount() > 0) {
774 mAccountsPrefCategory.removeAll();
775 }
776
777 AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
778 Account accounts[] = am.getAccountsByType(MainApp.getAccountType());
779 Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
780
781 if (am.getAccountsByType(MainApp.getAccountType()).length == 0) {
782 // Show create account screen if there isn't any account
783 am.addAccount(MainApp.getAccountType(), null, null, null, this,
784 null,
785 null);
786 }
787 else {
788
789 for (Account a : accounts) {
790 RadioButtonPreference accountPreference = new RadioButtonPreference(this);
791 accountPreference.setKey(a.name);
792 // Handle internationalized domain names
793 accountPreference.setTitle(DisplayUtils.convertIdn(a.name, false));
794 mAccountsPrefCategory.addPreference(accountPreference);
795
796 // Check the current account that is being used
797 if (a.name.equals(currentAccount.name)) {
798 accountPreference.setChecked(true);
799 } else {
800 accountPreference.setChecked(false);
801 }
802
803 accountPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
804 @Override
805 public boolean onPreferenceChange(Preference preference, Object newValue) {
806 String key = preference.getKey();
807 AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
808 Account accounts[] = am.getAccountsByType(MainApp.getAccountType());
809 for (Account a : accounts) {
810 RadioButtonPreference p =
811 (RadioButtonPreference) findPreference(a.name);
812 if (key.equals(a.name)) {
813 boolean accountChanged = !p.isChecked();
814 p.setChecked(true);
815 AccountUtils.setCurrentOwnCloudAccount(
816 getApplicationContext(),
817 a.name
818 );
819 if (accountChanged) {
820 // restart the main activity
821 Intent i = new Intent(
822 Preferences.this,
823 FileDisplayActivity.class
824 );
825 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
826 i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
827 startActivity(i);
828 } else {
829 finish();
830 }
831 } else {
832 p.setChecked(false);
833 }
834 }
835 return (Boolean) newValue;
836 }
837 });
838
839 }
840
841 // Add Create Account preference at the end of account list if
842 // Multiaccount is enabled
843 if (getResources().getBoolean(R.bool.multiaccount_support)) {
844 createAddAccountPreference();
845 }
846
847 }
848 }
849
850 /**
851 * Create the preference for allow adding new accounts
852 */
853 private void createAddAccountPreference() {
854 Preference addAccountPref = new Preference(this);
855 addAccountPref.setKey("add_account");
856 addAccountPref.setTitle(getString(R.string.prefs_add_account));
857 mAccountsPrefCategory.addPreference(addAccountPref);
858
859 addAccountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
860 @Override
861 public boolean onPreferenceClick(Preference preference) {
862 AccountManager am = AccountManager.get(getApplicationContext());
863 am.addAccount(MainApp.getAccountType(), null, null, null, Preferences.this,
864 null, null);
865 return true;
866 }
867 });
868
869 }
870
871 /**
872 * Load upload path set on preferences
873 */
874 private void loadInstantUploadPath() {
875 SharedPreferences appPrefs =
876 PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
877 mUploadPath = appPrefs.getString("instant_upload_path", getString(R.string.instant_upload_path));
878 mPrefInstantUploadPath.setSummary(mUploadPath);
879 }
880
881 /**
882 * Save the "Instant Upload Path" on preferences
883 */
884 private void saveInstantUploadPathOnPreferences() {
885 SharedPreferences appPrefs =
886 PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
887 SharedPreferences.Editor editor = appPrefs.edit();
888 editor.putString("instant_upload_path", mUploadPath);
889 editor.commit();
890 }
891
892 /**
893 * Load upload video path set on preferences
894 */
895 private void loadInstantUploadVideoPath() {
896 SharedPreferences appPrefs =
897 PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
898 mUploadVideoPath = appPrefs.getString("instant_video_upload_path", getString(R.string.instant_upload_path));
899 mPrefInstantVideoUploadPath.setSummary(mUploadVideoPath);
900 }
901
902 /**
903 * Save the "Instant Video Upload Path" on preferences
904 */
905 private void saveInstantUploadVideoPathOnPreferences() {
906 SharedPreferences appPrefs =
907 PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
908 SharedPreferences.Editor editor = appPrefs.edit();
909 editor.putString("instant_video_upload_path", mUploadVideoPath);
910 editor.commit();
911 }
912
913 // Methods for ComponetsGetter
914 @Override
915 public FileDownloader.FileDownloaderBinder getFileDownloaderBinder() {
916 return mDownloaderBinder;
917 }
918
919
920 @Override
921 public FileUploader.FileUploaderBinder getFileUploaderBinder() {
922 return mUploaderBinder;
923 }
924
925 @Override
926 public OperationsService.OperationsServiceBinder getOperationsServiceBinder() {
927 return null;
928 }
929
930 @Override
931 public FileDataStorageManager getStorageManager() {
932 return null;
933 }
934
935 @Override
936 public FileOperationsHelper getFileOperationsHelper() {
937 return null;
938 }
939
940 protected ServiceConnection newTransferenceServiceConnection() {
941 return new PreferencesServiceConnection();
942 }
943
944 /** Defines callbacks for service binding, passed to bindService() */
945 private class PreferencesServiceConnection implements ServiceConnection {
946
947 @Override
948 public void onServiceConnected(ComponentName component, IBinder service) {
949
950 if (component.equals(new ComponentName(Preferences.this, FileDownloader.class))) {
951 mDownloaderBinder = (FileDownloader.FileDownloaderBinder) service;
952
953 } else if (component.equals(new ComponentName(Preferences.this, FileUploader.class))) {
954 Log_OC.d(TAG, "Upload service connected");
955 mUploaderBinder = (FileUploader.FileUploaderBinder) service;
956 } else {
957 return;
958 }
959
960 }
961
962 @Override
963 public void onServiceDisconnected(ComponentName component) {
964 if (component.equals(new ComponentName(Preferences.this, FileDownloader.class))) {
965 Log_OC.d(TAG, "Download service suddenly disconnected");
966 mDownloaderBinder = null;
967 } else if (component.equals(new ComponentName(Preferences.this, FileUploader.class))) {
968 Log_OC.d(TAG, "Upload service suddenly disconnected");
969 mUploaderBinder = null;
970 }
971 }
972 };
973
974 /**
975 *
976 * Class for loading the version number
977 *
978 */
979 private class LoadingVersionNumberTask extends AsyncTask<Void, Void, Integer> {
980 protected Integer doInBackground(Void... args) {
981 try {
982 URL url = new URL("https://github.com/owncloud/android/raw/beta/apks/latest");
983 BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
984
985 Integer latestVersion = Integer.parseInt(in.readLine());
986 in.close();
987
988 return latestVersion;
989
990 } catch (MalformedURLException e) {
991 e.printStackTrace();
992 } catch (IOException e) {
993 e.printStackTrace();
994 }
995 return -1;
996 }
997 }
998 }