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