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