Add context description tag to action bar title
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / Preferences.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18 package com.owncloud.android.ui.activity;
19
20 import android.accounts.Account;
21 import android.accounts.AccountManager;
22 import android.accounts.AccountManagerCallback;
23 import android.accounts.AccountManagerFuture;
24 import android.content.Intent;
25 import android.content.SharedPreferences;
26 import android.content.pm.PackageInfo;
27 import android.content.pm.PackageManager.NameNotFoundException;
28 import android.net.Uri;
29 import android.os.Bundle;
30 import android.os.Handler;
31 import android.preference.CheckBoxPreference;
32 import android.preference.Preference;
33 import android.preference.Preference.OnPreferenceChangeListener;
34 import android.preference.Preference.OnPreferenceClickListener;
35 import android.preference.PreferenceCategory;
36 import android.preference.PreferenceManager;
37 import android.view.ContextMenu;
38 import android.view.ContextMenu.ContextMenuInfo;
39 import android.view.View;
40 import android.widget.AdapterView;
41 import android.widget.AdapterView.OnItemLongClickListener;
42 import android.widget.ListAdapter;
43 import android.widget.ListView;
44
45 import com.actionbarsherlock.app.ActionBar;
46 import com.actionbarsherlock.app.SherlockPreferenceActivity;
47 import com.actionbarsherlock.view.Menu;
48 import com.actionbarsherlock.view.MenuItem;
49 import com.owncloud.android.MainApp;
50 import com.owncloud.android.R;
51 import com.owncloud.android.authentication.AccountUtils;
52 import com.owncloud.android.authentication.AuthenticatorActivity;
53 import com.owncloud.android.datamodel.OCFile;
54 import com.owncloud.android.db.DbHandler;
55 import com.owncloud.android.lib.common.utils.Log_OC;
56 import com.owncloud.android.ui.RadioButtonPreference;
57 import com.owncloud.android.utils.DisplayUtils;
58
59
60 /**
61 * An Activity that allows the user to change the application's settings.
62 *
63 * @author Bartek Przybylski
64 * @author David A. Velasco
65 */
66 public class Preferences extends SherlockPreferenceActivity implements AccountManagerCallback<Boolean> {
67
68 private static final String TAG = "OwnCloudPreferences";
69
70 private static final int ACTION_SELECT_UPLOAD_PATH = 1;
71 private static final int ACTION_SELECT_UPLOAD_VIDEO_PATH = 2;
72
73 private DbHandler mDbHandler;
74 private CheckBoxPreference pCode;
75 private Preference pAboutApp;
76
77 private PreferenceCategory mAccountsPrefCategory = null;
78 private final Handler mHandler = new Handler();
79 private String mAccountName;
80 private boolean mShowContextMenu = false;
81 private String mUploadPath;
82 private Preference mPrefInstantUploadPath;
83 private Preference mPrefInstantVideoUploadPath;
84 private String mUploadVideoPath;
85
86
87 @SuppressWarnings("deprecation")
88 @Override
89 public void onCreate(Bundle savedInstanceState) {
90 super.onCreate(savedInstanceState);
91 mDbHandler = new DbHandler(getBaseContext());
92 addPreferencesFromResource(R.xml.preferences);
93
94 ActionBar actionBar = getSherlock().getActionBar();
95 actionBar.setIcon(DisplayUtils.getSeasonalIconId());
96 actionBar.setDisplayHomeAsUpEnabled(true);
97 actionBar.setTitle(R.string.actionbar_settings);
98
99 // For adding content description tag to a title field in the action bar
100 int actionBarTitleId = getResources().getIdentifier("action_bar_title", "id", "android");
101 getWindow().getDecorView().findViewById(actionBarTitleId).setContentDescription(getString(R.string.actionbar_settings));
102
103 // Load the accounts category for adding the list of accounts
104 mAccountsPrefCategory = (PreferenceCategory) findPreference("accounts_category");
105
106 ListView listView = getListView();
107 listView.setOnItemLongClickListener(new OnItemLongClickListener() {
108 @Override
109 public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
110 ListView listView = (ListView) parent;
111 ListAdapter listAdapter = listView.getAdapter();
112 Object obj = listAdapter.getItem(position);
113
114 if (obj != null && obj instanceof RadioButtonPreference) {
115 mShowContextMenu = true;
116 mAccountName = ((RadioButtonPreference) obj).getKey();
117
118 Preferences.this.openContextMenu(listView);
119
120 View.OnLongClickListener longListener = (View.OnLongClickListener) obj;
121 return longListener.onLongClick(view);
122 }
123 return false;
124 }
125 });
126
127 // Load package info
128 String temp;
129 try {
130 PackageInfo pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
131 temp = pkg.versionName;
132 } catch (NameNotFoundException e) {
133 temp = "";
134 Log_OC.e(TAG, "Error while showing about dialog", e);
135 }
136 final String appVersion = temp;
137
138 // Register context menu for list of preferences.
139 registerForContextMenu(getListView());
140
141 pCode = (CheckBoxPreference) findPreference("set_pincode");
142 if (pCode != null){
143 pCode.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
144 @Override
145 public boolean onPreferenceChange(Preference preference, Object newValue) {
146 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
147 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "preferences");
148 i.putExtra(PinCodeActivity.EXTRA_NEW_STATE, newValue.toString());
149 startActivity(i);
150
151 return true;
152 }
153 });
154
155 }
156
157 PreferenceCategory preferenceCategory = (PreferenceCategory) findPreference("more");
158
159 boolean helpEnabled = getResources().getBoolean(R.bool.help_enabled);
160 Preference pHelp = findPreference("help");
161 if (pHelp != null ){
162 if (helpEnabled) {
163 pHelp.setOnPreferenceClickListener(new OnPreferenceClickListener() {
164 @Override
165 public boolean onPreferenceClick(Preference preference) {
166 String helpWeb =(String) getText(R.string.url_help);
167 if (helpWeb != null && helpWeb.length() > 0) {
168 Uri uriUrl = Uri.parse(helpWeb);
169 Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
170 startActivity(intent);
171 }
172 return true;
173 }
174 });
175 } else {
176 preferenceCategory.removePreference(pHelp);
177 }
178
179 }
180
181
182 boolean recommendEnabled = getResources().getBoolean(R.bool.recommend_enabled);
183 Preference pRecommend = findPreference("recommend");
184 if (pRecommend != null){
185 if (recommendEnabled) {
186 pRecommend.setOnPreferenceClickListener(new OnPreferenceClickListener() {
187 @Override
188 public boolean onPreferenceClick(Preference preference) {
189
190 Intent intent = new Intent(Intent.ACTION_SENDTO);
191 intent.setType("text/plain");
192 intent.setData(Uri.parse(getString(R.string.mail_recommend)));
193 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
194
195 String appName = getString(R.string.app_name);
196 String downloadUrl = getString(R.string.url_app_download);
197 Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(Preferences.this);
198 String username = currentAccount.name.substring(0, currentAccount.name.lastIndexOf('@'));
199
200 String recommendSubject = String.format(getString(R.string.recommend_subject), appName);
201 String recommendText = String.format(getString(R.string.recommend_text), appName, downloadUrl, username);
202
203 intent.putExtra(Intent.EXTRA_SUBJECT, recommendSubject);
204 intent.putExtra(Intent.EXTRA_TEXT, recommendText);
205 startActivity(intent);
206
207
208 return(true);
209
210 }
211 });
212 } else {
213 preferenceCategory.removePreference(pRecommend);
214 }
215
216 }
217
218 boolean feedbackEnabled = getResources().getBoolean(R.bool.feedback_enabled);
219 Preference pFeedback = findPreference("feedback");
220 if (pFeedback != null){
221 if (feedbackEnabled) {
222 pFeedback.setOnPreferenceClickListener(new OnPreferenceClickListener() {
223 @Override
224 public boolean onPreferenceClick(Preference preference) {
225 String feedbackMail =(String) getText(R.string.mail_feedback);
226 String feedback =(String) getText(R.string.prefs_feedback) + " - android v" + appVersion;
227 Intent intent = new Intent(Intent.ACTION_SENDTO);
228 intent.setType("text/plain");
229 intent.putExtra(Intent.EXTRA_SUBJECT, feedback);
230
231 intent.setData(Uri.parse(feedbackMail));
232 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
233 startActivity(intent);
234
235 return true;
236 }
237 });
238 } else {
239 preferenceCategory.removePreference(pFeedback);
240 }
241
242 }
243
244 boolean imprintEnabled = getResources().getBoolean(R.bool.imprint_enabled);
245 Preference pImprint = findPreference("imprint");
246 if (pImprint != null) {
247 if (imprintEnabled) {
248 pImprint.setOnPreferenceClickListener(new OnPreferenceClickListener() {
249 @Override
250 public boolean onPreferenceClick(Preference preference) {
251 String imprintWeb = (String) getText(R.string.url_imprint);
252 if (imprintWeb != null && imprintWeb.length() > 0) {
253 Uri uriUrl = Uri.parse(imprintWeb);
254 Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
255 startActivity(intent);
256 }
257 //ImprintDialog.newInstance(true).show(preference.get, "IMPRINT_DIALOG");
258 return true;
259 }
260 });
261 } else {
262 preferenceCategory.removePreference(pImprint);
263 }
264 }
265
266 mPrefInstantUploadPath = findPreference("instant_upload_path");
267 if (mPrefInstantUploadPath != null){
268
269 mPrefInstantUploadPath.setOnPreferenceClickListener(new OnPreferenceClickListener() {
270 @Override
271 public boolean onPreferenceClick(Preference preference) {
272 if (!mUploadPath.endsWith(OCFile.PATH_SEPARATOR)) {
273 mUploadPath += OCFile.PATH_SEPARATOR;
274 }
275 Intent intent = new Intent(Preferences.this, UploadPathActivity.class);
276 intent.putExtra(UploadPathActivity.KEY_INSTANT_UPLOAD_PATH, mUploadPath);
277 startActivityForResult(intent, ACTION_SELECT_UPLOAD_PATH);
278 return true;
279 }
280 });
281 }
282
283 mPrefInstantVideoUploadPath = findPreference("instant_video_upload_path");
284 if (mPrefInstantVideoUploadPath != null){
285
286 mPrefInstantVideoUploadPath.setOnPreferenceClickListener(new OnPreferenceClickListener() {
287 @Override
288 public boolean onPreferenceClick(Preference preference) {
289 if (!mUploadVideoPath.endsWith(OCFile.PATH_SEPARATOR)) {
290 mUploadVideoPath += OCFile.PATH_SEPARATOR;
291 }
292 Intent intent = new Intent(Preferences.this, UploadPathActivity.class);
293 intent.putExtra(UploadPathActivity.KEY_INSTANT_UPLOAD_PATH, mUploadVideoPath);
294 startActivityForResult(intent, ACTION_SELECT_UPLOAD_VIDEO_PATH);
295 return true;
296 }
297 });
298 }
299
300 /* About App */
301 pAboutApp = (Preference) findPreference("about_app");
302 if (pAboutApp != null) {
303 pAboutApp.setTitle(String.format(getString(R.string.about_android), getString(R.string.app_name)));
304 pAboutApp.setSummary(String.format(getString(R.string.about_version), appVersion));
305 }
306
307 loadInstantUploadPath();
308 loadInstantUploadVideoPath();
309
310 }
311
312 @Override
313 protected void onPause() {
314 super.onPause();
315 }
316
317 @Override
318 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
319
320 // Filter for only showing contextual menu when long press on the
321 // accounts
322 if (mShowContextMenu) {
323 getMenuInflater().inflate(R.menu.account_picker_long_click, menu);
324 mShowContextMenu = false;
325 }
326 super.onCreateContextMenu(menu, v, menuInfo);
327 }
328
329 /**
330 * Called when the user clicked on an item into the context menu created at
331 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} for
332 * every ownCloud {@link Account} , containing 'secondary actions' for them.
333 *
334 * {@inheritDoc}
335 */
336 @Override
337 public boolean onContextItemSelected(android.view.MenuItem item) {
338 AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
339 Account accounts[] = am.getAccountsByType(MainApp.getAccountType());
340 for (Account a : accounts) {
341 if (a.name.equals(mAccountName)) {
342 if (item.getItemId() == R.id.change_password) {
343
344 // Change account password
345 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
346 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, a);
347 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION,
348 AuthenticatorActivity.ACTION_UPDATE_TOKEN);
349 startActivity(updateAccountCredentials);
350
351 } else if (item.getItemId() == R.id.delete_account) {
352
353 // Remove account
354 am.removeAccount(a, this, mHandler);
355 }
356 }
357 }
358
359 return true;
360 }
361
362 @Override
363 public void run(AccountManagerFuture<Boolean> future) {
364 if (future.isDone()) {
365 Account a = AccountUtils.getCurrentOwnCloudAccount(this);
366 String accountName = "";
367 if (a == null) {
368 Account[] accounts = AccountManager.get(this).getAccountsByType(MainApp.getAccountType());
369 if (accounts.length != 0)
370 accountName = accounts[0].name;
371 AccountUtils.setCurrentOwnCloudAccount(this, accountName);
372 }
373 addAccountsCheckboxPreferences();
374 }
375 }
376
377 @Override
378 protected void onResume() {
379 super.onResume();
380 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
381 boolean state = appPrefs.getBoolean("set_pincode", false);
382 pCode.setChecked(state);
383
384 // Populate the accounts category with the list of accounts
385 addAccountsCheckboxPreferences();
386 }
387
388 @Override
389 public boolean onCreateOptionsMenu(Menu menu) {
390 super.onCreateOptionsMenu(menu);
391 return true;
392 }
393
394 @Override
395 public boolean onMenuItemSelected(int featureId, MenuItem item) {
396 super.onMenuItemSelected(featureId, item);
397 Intent intent;
398
399 switch (item.getItemId()) {
400 case android.R.id.home:
401 intent = new Intent(getBaseContext(), FileDisplayActivity.class);
402 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
403 startActivity(intent);
404 break;
405 default:
406 Log_OC.w(TAG, "Unknown menu item triggered");
407 return false;
408 }
409 return true;
410 }
411
412 @Override
413 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
414 super.onActivityResult(requestCode, resultCode, data);
415
416 if (requestCode == ACTION_SELECT_UPLOAD_PATH && resultCode == RESULT_OK){
417
418 OCFile folderToUpload = (OCFile) data.getParcelableExtra(UploadPathActivity.EXTRA_FOLDER);
419
420 mUploadPath = folderToUpload.getRemotePath();
421
422 mUploadPath = DisplayUtils.getPathWithoutLastSlash(mUploadPath);
423
424 // Show the path on summary preference
425 mPrefInstantUploadPath.setSummary(mUploadPath);
426
427 saveInstantUploadPathOnPreferences();
428
429 } else if (requestCode == ACTION_SELECT_UPLOAD_VIDEO_PATH && resultCode == RESULT_OK){
430
431 OCFile folderToUploadVideo = (OCFile) data.getParcelableExtra(UploadPathActivity.EXTRA_FOLDER);
432
433 mUploadVideoPath = folderToUploadVideo.getRemotePath();
434
435 mUploadVideoPath = DisplayUtils.getPathWithoutLastSlash(mUploadVideoPath);
436
437 // Show the video path on summary preference
438 mPrefInstantVideoUploadPath.setSummary(mUploadVideoPath);
439
440 saveInstantUploadVideoPathOnPreferences();
441 }
442 }
443
444 @Override
445 protected void onDestroy() {
446 mDbHandler.close();
447 super.onDestroy();
448 }
449
450 /**
451 * Create the list of accounts that has been added into the app
452 */
453 @SuppressWarnings("deprecation")
454 private void addAccountsCheckboxPreferences() {
455
456 // Remove accounts in case list is refreshing for avoiding to have
457 // duplicate items
458 if (mAccountsPrefCategory.getPreferenceCount() > 0) {
459 mAccountsPrefCategory.removeAll();
460 }
461
462 AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
463 Account accounts[] = am.getAccountsByType(MainApp.getAccountType());
464 Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
465
466 if (am.getAccountsByType(MainApp.getAccountType()).length == 0) {
467 // Show create account screen if there isn't any account
468 am.addAccount(MainApp.getAccountType(), null, null, null, this,
469 null,
470 null);
471 }
472 else {
473
474 for (Account a : accounts) {
475 RadioButtonPreference accountPreference = new RadioButtonPreference(this);
476 accountPreference.setKey(a.name);
477 // Handle internationalized domain names
478 accountPreference.setTitle(DisplayUtils.convertIdn(a.name, false));
479 mAccountsPrefCategory.addPreference(accountPreference);
480
481 // Check the current account that is being used
482 if (a.name.equals(currentAccount.name)) {
483 accountPreference.setChecked(true);
484 } else {
485 accountPreference.setChecked(false);
486 }
487
488 accountPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
489 @Override
490 public boolean onPreferenceChange(Preference preference, Object newValue) {
491 String key = preference.getKey();
492 AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
493 Account accounts[] = am.getAccountsByType(MainApp.getAccountType());
494 for (Account a : accounts) {
495 RadioButtonPreference p = (RadioButtonPreference) findPreference(a.name);
496 if (key.equals(a.name)) {
497 boolean accountChanged = !p.isChecked();
498 p.setChecked(true);
499 AccountUtils.setCurrentOwnCloudAccount(
500 getApplicationContext(),
501 a.name
502 );
503 if (accountChanged) {
504 // restart the main activity
505 Intent i = new Intent(
506 Preferences.this,
507 FileDisplayActivity.class
508 );
509 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
510 startActivity(i);
511 } else {
512 finish();
513 }
514 } else {
515 p.setChecked(false);
516 }
517 }
518 return (Boolean) newValue;
519 }
520 });
521
522 }
523
524 // Add Create Account preference at the end of account list if
525 // Multiaccount is enabled
526 if (getResources().getBoolean(R.bool.multiaccount_support)) {
527 createAddAccountPreference();
528 }
529
530 }
531 }
532
533 /**
534 * Create the preference for allow adding new accounts
535 */
536 private void createAddAccountPreference() {
537 Preference addAccountPref = new Preference(this);
538 addAccountPref.setKey("add_account");
539 addAccountPref.setTitle(getString(R.string.prefs_add_account));
540 mAccountsPrefCategory.addPreference(addAccountPref);
541
542 addAccountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
543 @Override
544 public boolean onPreferenceClick(Preference preference) {
545 AccountManager am = AccountManager.get(getApplicationContext());
546 am.addAccount(MainApp.getAccountType(), null, null, null, Preferences.this, null, null);
547 return true;
548 }
549 });
550
551 }
552
553 /**
554 * Load upload path set on preferences
555 */
556 private void loadInstantUploadPath() {
557 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
558 mUploadPath = appPrefs.getString("instant_upload_path", getString(R.string.instant_upload_path));
559 mPrefInstantUploadPath.setSummary(mUploadPath);
560 }
561
562 /**
563 * Save the "Instant Upload Path" on preferences
564 */
565 private void saveInstantUploadPathOnPreferences() {
566 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
567 SharedPreferences.Editor editor = appPrefs.edit();
568 editor.putString("instant_upload_path", mUploadPath);
569 editor.commit();
570 }
571
572 /**
573 * Load upload video path set on preferences
574 */
575 private void loadInstantUploadVideoPath() {
576 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
577 mUploadVideoPath = appPrefs.getString("instant_video_upload_path", getString(R.string.instant_upload_path));
578 mPrefInstantVideoUploadPath.setSummary(mUploadVideoPath);
579 }
580
581 /**
582 * Save the "Instant Video Upload Path" on preferences
583 */
584 private void saveInstantUploadVideoPathOnPreferences() {
585 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
586 SharedPreferences.Editor editor = appPrefs.edit();
587 editor.putString("instant_video_upload_path", mUploadVideoPath);
588 editor.commit();
589 }
590 }