072cc24122c671478d64ce9adbc7b9c461ee52fd
[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 import android.widget.Toast;
45
46 import com.actionbarsherlock.app.ActionBar;
47 import com.actionbarsherlock.app.SherlockPreferenceActivity;
48 import com.actionbarsherlock.view.Menu;
49 import com.actionbarsherlock.view.MenuItem;
50 import com.owncloud.android.MainApp;
51 import com.owncloud.android.R;
52 import com.owncloud.android.authentication.AccountUtils;
53 import com.owncloud.android.authentication.AuthenticatorActivity;
54 import com.owncloud.android.datamodel.OCFile;
55 import com.owncloud.android.db.DbHandler;
56 import com.owncloud.android.lib.common.utils.Log_OC;
57 import com.owncloud.android.ui.LongClickableCheckBoxPreference;
58 import com.owncloud.android.utils.DisplayUtils;
59
60
61 /**
62 * An Activity that allows the user to change the application's settings.
63 *
64 * @author Bartek Przybylski
65 * @author David A. Velasco
66 */
67 public class Preferences extends SherlockPreferenceActivity implements AccountManagerCallback<Boolean> {
68
69 private static final String TAG = "OwnCloudPreferences";
70
71 private static final int ACTION_SELECT_UPLOAD_PATH = 1;
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
84
85 @SuppressWarnings("deprecation")
86 @Override
87 public void onCreate(Bundle savedInstanceState) {
88 super.onCreate(savedInstanceState);
89 mDbHandler = new DbHandler(getBaseContext());
90 addPreferencesFromResource(R.xml.preferences);
91
92 ActionBar actionBar = getSherlock().getActionBar();
93 actionBar.setIcon(DisplayUtils.getSeasonalIconId());
94 actionBar.setDisplayHomeAsUpEnabled(true);
95 actionBar.setTitle(R.string.actionbar_settings);
96
97 // Load the accounts category for adding the list of accounts
98 mAccountsPrefCategory = (PreferenceCategory) findPreference("accounts_category");
99
100 ListView listView = getListView();
101 listView.setOnItemLongClickListener(new OnItemLongClickListener() {
102 @Override
103 public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
104 ListView listView = (ListView) parent;
105 ListAdapter listAdapter = listView.getAdapter();
106 Object obj = listAdapter.getItem(position);
107
108 if (obj != null && obj instanceof LongClickableCheckBoxPreference) {
109 mShowContextMenu = true;
110 mAccountName = ((LongClickableCheckBoxPreference) obj).getKey();
111
112 Preferences.this.openContextMenu(listView);
113
114 View.OnLongClickListener longListener = (View.OnLongClickListener) obj;
115 return longListener.onLongClick(view);
116 }
117 return false;
118 }
119 });
120
121 // Register context menu for list of preferences.
122 registerForContextMenu(getListView());
123
124 pCode = (CheckBoxPreference) findPreference("set_pincode");
125 if (pCode != null){
126 pCode.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
127 @Override
128 public boolean onPreferenceChange(Preference preference, Object newValue) {
129 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
130 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "preferences");
131 i.putExtra(PinCodeActivity.EXTRA_NEW_STATE, newValue.toString());
132 startActivity(i);
133
134 return true;
135 }
136 });
137
138 }
139
140 PreferenceCategory preferenceCategory = (PreferenceCategory) findPreference("more");
141
142 boolean helpEnabled = getResources().getBoolean(R.bool.help_enabled);
143 Preference pHelp = findPreference("help");
144 if (pHelp != null ){
145 if (helpEnabled) {
146 pHelp.setOnPreferenceClickListener(new OnPreferenceClickListener() {
147 @Override
148 public boolean onPreferenceClick(Preference preference) {
149 String helpWeb =(String) getText(R.string.url_help);
150 if (helpWeb != null && helpWeb.length() > 0) {
151 Uri uriUrl = Uri.parse(helpWeb);
152 Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
153 startActivity(intent);
154 }
155 return true;
156 }
157 });
158 } else {
159 preferenceCategory.removePreference(pHelp);
160 }
161
162 }
163
164
165 boolean recommendEnabled = getResources().getBoolean(R.bool.recommend_enabled);
166 Preference pRecommend = findPreference("recommend");
167 if (pRecommend != null){
168 if (recommendEnabled) {
169 pRecommend.setOnPreferenceClickListener(new OnPreferenceClickListener() {
170 @Override
171 public boolean onPreferenceClick(Preference preference) {
172
173 Intent intent = new Intent(Intent.ACTION_SENDTO);
174 intent.setType("text/plain");
175 intent.setData(Uri.parse(getString(R.string.mail_recommend)));
176 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
177
178 String appName = getString(R.string.app_name);
179 String downloadUrl = getString(R.string.url_app_download);
180 Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(Preferences.this);
181 String username = currentAccount.name.substring(0, currentAccount.name.lastIndexOf('@'));
182
183 String recommendSubject = String.format(getString(R.string.recommend_subject), appName);
184 String recommendText = String.format(getString(R.string.recommend_text), appName, downloadUrl, username);
185
186 intent.putExtra(Intent.EXTRA_SUBJECT, recommendSubject);
187 intent.putExtra(Intent.EXTRA_TEXT, recommendText);
188 startActivity(intent);
189
190
191 return(true);
192
193 }
194 });
195 } else {
196 preferenceCategory.removePreference(pRecommend);
197 }
198
199 }
200
201 boolean feedbackEnabled = getResources().getBoolean(R.bool.feedback_enabled);
202 Preference pFeedback = findPreference("feedback");
203 if (pFeedback != null){
204 if (feedbackEnabled) {
205 pFeedback.setOnPreferenceClickListener(new OnPreferenceClickListener() {
206 @Override
207 public boolean onPreferenceClick(Preference preference) {
208 String feedbackMail =(String) getText(R.string.mail_feedback);
209 String feedback =(String) getText(R.string.prefs_feedback);
210 Intent intent = new Intent(Intent.ACTION_SENDTO);
211 intent.setType("text/plain");
212 intent.putExtra(Intent.EXTRA_SUBJECT, feedback);
213
214 intent.setData(Uri.parse(feedbackMail));
215 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
216 startActivity(intent);
217
218 return true;
219 }
220 });
221 } else {
222 preferenceCategory.removePreference(pFeedback);
223 }
224
225 }
226
227 boolean imprintEnabled = getResources().getBoolean(R.bool.imprint_enabled);
228 Preference pImprint = findPreference("imprint");
229 if (pImprint != null) {
230 if (imprintEnabled) {
231 pImprint.setOnPreferenceClickListener(new OnPreferenceClickListener() {
232 @Override
233 public boolean onPreferenceClick(Preference preference) {
234 String imprintWeb = (String) getText(R.string.url_imprint);
235 if (imprintWeb != null && imprintWeb.length() > 0) {
236 Uri uriUrl = Uri.parse(imprintWeb);
237 Intent intent = new Intent(Intent.ACTION_VIEW, uriUrl);
238 startActivity(intent);
239 }
240 //ImprintDialog.newInstance(true).show(preference.get, "IMPRINT_DIALOG");
241 return true;
242 }
243 });
244 } else {
245 preferenceCategory.removePreference(pImprint);
246 }
247 }
248
249 mPrefInstantUploadPath = findPreference("instant_upload_path");
250 if (mPrefInstantUploadPath != null){
251
252 mPrefInstantUploadPath.setOnPreferenceClickListener(new OnPreferenceClickListener() {
253 @Override
254 public boolean onPreferenceClick(Preference preference) {
255 startActivityForResult(new Intent(Preferences.this, MoveActivity.class),
256 ACTION_SELECT_UPLOAD_PATH);
257 return true;
258 }
259 });
260 }
261
262 /* About App */
263 pAboutApp = (Preference) findPreference("about_app");
264 if (pAboutApp != null) {
265 pAboutApp.setTitle(String.format(getString(R.string.about_android), getString(R.string.app_name)));
266 PackageInfo pkg;
267 try {
268 pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
269 pAboutApp.setSummary(String.format(getString(R.string.about_version), pkg.versionName));
270 } catch (NameNotFoundException e) {
271 Log_OC.e(TAG, "Error while showing about dialog", e);
272 }
273 }
274
275 loadInstantUploadPath();
276
277 }
278
279 @Override
280 protected void onPause() {
281 saveInstantUploadPathOnPreferences();
282 super.onPause();
283 }
284
285 @Override
286 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
287
288 // Filter for only showing contextual menu when long press on the
289 // accounts
290 if (mShowContextMenu) {
291 getMenuInflater().inflate(R.menu.account_picker_long_click, menu);
292 mShowContextMenu = false;
293 }
294 super.onCreateContextMenu(menu, v, menuInfo);
295 }
296
297 /**
298 * Called when the user clicked on an item into the context menu created at
299 * {@link #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} for
300 * every ownCloud {@link Account} , containing 'secondary actions' for them.
301 *
302 * {@inheritDoc}
303 */
304 @Override
305 public boolean onContextItemSelected(android.view.MenuItem item) {
306 AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
307 Account accounts[] = am.getAccountsByType(MainApp.getAccountType());
308 for (Account a : accounts) {
309 if (a.name.equals(mAccountName)) {
310 if (item.getItemId() == R.id.change_password) {
311
312 // Change account password
313 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
314 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, a);
315 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION,
316 AuthenticatorActivity.ACTION_UPDATE_TOKEN);
317 startActivity(updateAccountCredentials);
318
319 } else if (item.getItemId() == R.id.delete_account) {
320
321 // Remove account
322 am.removeAccount(a, this, mHandler);
323 }
324 }
325 }
326
327 return true;
328 }
329
330 @Override
331 public void run(AccountManagerFuture<Boolean> future) {
332 if (future.isDone()) {
333 Account a = AccountUtils.getCurrentOwnCloudAccount(this);
334 String accountName = "";
335 if (a == null) {
336 Account[] accounts = AccountManager.get(this).getAccountsByType(MainApp.getAccountType());
337 if (accounts.length != 0)
338 accountName = accounts[0].name;
339 AccountUtils.setCurrentOwnCloudAccount(this, accountName);
340 }
341 addAccountsCheckboxPreferences();
342 }
343 }
344
345 @Override
346 protected void onResume() {
347 super.onResume();
348 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
349 boolean state = appPrefs.getBoolean("set_pincode", false);
350 pCode.setChecked(state);
351
352 // Populate the accounts category with the list of accounts
353 addAccountsCheckboxPreferences();
354 }
355
356 @Override
357 public boolean onCreateOptionsMenu(Menu menu) {
358 super.onCreateOptionsMenu(menu);
359 return true;
360 }
361
362 @Override
363 public boolean onMenuItemSelected(int featureId, MenuItem item) {
364 super.onMenuItemSelected(featureId, item);
365 Intent intent;
366
367 switch (item.getItemId()) {
368 case android.R.id.home:
369 intent = new Intent(getBaseContext(), FileDisplayActivity.class);
370 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
371 startActivity(intent);
372 break;
373 default:
374 Log_OC.w(TAG, "Unknown menu item triggered");
375 return false;
376 }
377 return true;
378 }
379
380 @Override
381 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
382 super.onActivityResult(requestCode, resultCode, data);
383
384 if (requestCode == ACTION_SELECT_UPLOAD_PATH && (resultCode == RESULT_OK ||
385 resultCode == MoveActivity.RESULT_OK_AND_MOVE)){
386
387 OCFile folderToMoveAt = (OCFile) data.getParcelableExtra(MoveActivity.EXTRA_CURRENT_FOLDER);
388
389 mUploadPath = folderToMoveAt.getRemotePath();
390
391 saveInstantUploadPathOnPreferences();
392 }
393 }
394
395 @Override
396 protected void onDestroy() {
397 mDbHandler.close();
398 super.onDestroy();
399 }
400
401 /**
402 * Create the list of accounts that has been added into the app
403 */
404 @SuppressWarnings("deprecation")
405 private void addAccountsCheckboxPreferences() {
406
407 // Remove accounts in case list is refreshing for avoiding to have
408 // duplicate items
409 if (mAccountsPrefCategory.getPreferenceCount() > 0) {
410 mAccountsPrefCategory.removeAll();
411 }
412
413 AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
414 Account accounts[] = am.getAccountsByType(MainApp.getAccountType());
415 Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
416
417 if (am.getAccountsByType(MainApp.getAccountType()).length == 0) {
418 // Show create account screen if there isn't any account
419 am.addAccount(MainApp.getAccountType(), null, null, null, this,
420 null,
421 null);
422 }
423 else {
424
425 for (Account a : accounts) {
426 LongClickableCheckBoxPreference accountPreference = new LongClickableCheckBoxPreference(this);
427 accountPreference.setKey(a.name);
428 // Handle internationalized domain names
429 accountPreference.setTitle(DisplayUtils.convertIdn(a.name, false));
430 mAccountsPrefCategory.addPreference(accountPreference);
431
432 // Check the current account that is being used
433 if (a.name.equals(currentAccount.name)) {
434 accountPreference.setChecked(true);
435 } else {
436 accountPreference.setChecked(false);
437 }
438
439 accountPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
440 @Override
441 public boolean onPreferenceChange(Preference preference, Object newValue) {
442 String key = preference.getKey();
443 AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
444 Account accounts[] = am.getAccountsByType(MainApp.getAccountType());
445 for (Account a : accounts) {
446 CheckBoxPreference p = (CheckBoxPreference) findPreference(a.name);
447 if (key.equals(a.name)) {
448 boolean accountChanged = !p.isChecked();
449 p.setChecked(true);
450 AccountUtils.setCurrentOwnCloudAccount(
451 getApplicationContext(),
452 a.name
453 );
454 if (accountChanged) {
455 // restart the main activity
456 Intent i = new Intent(
457 Preferences.this,
458 FileDisplayActivity.class
459 );
460 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
461 startActivity(i);
462 } else {
463 finish();
464 }
465 } else {
466 p.setChecked(false);
467 }
468 }
469 return (Boolean) newValue;
470 }
471 });
472
473 }
474
475 // Add Create Account preference at the end of account list if
476 // Multiaccount is enabled
477 if (getResources().getBoolean(R.bool.multiaccount_support)) {
478 createAddAccountPreference();
479 }
480
481 }
482 }
483
484 /**
485 * Create the preference for allow adding new accounts
486 */
487 private void createAddAccountPreference() {
488 Preference addAccountPref = new Preference(this);
489 addAccountPref.setKey("add_account");
490 addAccountPref.setTitle(getString(R.string.prefs_add_account));
491 mAccountsPrefCategory.addPreference(addAccountPref);
492
493 addAccountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
494 @Override
495 public boolean onPreferenceClick(Preference preference) {
496 AccountManager am = AccountManager.get(getApplicationContext());
497 am.addAccount(MainApp.getAccountType(), null, null, null, Preferences.this, null, null);
498 return true;
499 }
500 });
501
502 }
503
504 /**
505 * Load upload path set on preferences
506 */
507 private void loadInstantUploadPath() {
508 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
509 mUploadPath = appPrefs.getString("instant_upload_path", getString(R.string.instant_upload_path));
510 mPrefInstantUploadPath.setSummary(mUploadPath);
511 }
512
513 /**
514 * Save the "Instant Upload Path" on preferences
515 */
516 private void saveInstantUploadPathOnPreferences() {
517 mPrefInstantUploadPath.setSummary(mUploadPath);
518 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
519 SharedPreferences.Editor editor = appPrefs.edit();
520 editor.putString("instant_upload_path", mUploadPath);
521 editor.commit();
522 }
523 }