List of usage examples for android.accounts AccountManager addAccountExplicitly
public boolean addAccountExplicitly(Account account, String password, Bundle userdata)
From source file:com.skywomantechnology.app.guildviewer.sync.GuildViewerSyncAdapter.java
/** * Helper method to get the fake account to be used with SyncAdapter, or make a new one if the * fake account doesn't exist yet.//w w w . ja v a 2s.com * * @param context * The context used to access the account service * @return a fake account. */ public static Account getSyncAccount(Context context) { // Get an instance of the Android account manager AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE); // Create the account type and default account Account newAccount = new Account(context.getString(R.string.app_name), context.getString(R.string.sync_account_type)); // If the password doesn't exist, the account doesn't exist if (null == accountManager.getPassword(newAccount)) { // Add the account and account type, no password or user data // If successful, return the Account object, otherwise report an error. if (!accountManager.addAccountExplicitly(newAccount, "", null)) { return null; } // If you don't set android:syncable="true" in your <provider> element in the manifest, // then call context.setIsSyncable(account, AUTHORITY, 1) here. onAccountCreated(newAccount, context); } return newAccount; }
From source file:info.semanticsoftware.semassist.android.activity.AuthenticationActivity.java
/** Sends an authentication request when the save button is pushed. * @param v view /*from ww w.jav a 2s. c o m*/ */ public void onSaveClick(View v) { TextView tvUsername = (TextView) this.findViewById(R.id.uc_txt_username); TextView tvPassword = (TextView) this.findViewById(R.id.uc_txt_password); //Qualified username, i.e, user@semanticassistants.com String qUsername = tvUsername.getText().toString(); String username = null; if (qUsername.indexOf("@") > 0) { username = qUsername.substring(0, qUsername.indexOf("@")); } else { username = qUsername; } String password = tvPassword.getText().toString(); //TODO do client-side validation like password length etc. String response = authenicate(username, password); if (!response.equals(Constants.AUTHENTICATION_FAIL)) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); Editor editor = settings.edit(); editor.putString("username", username); editor.putString("password", password); //FIXME replace this with a descent XML parser String acctype = ""; int start = response.indexOf("<accType>"); int end = response.indexOf("</accType>"); if (start > -1 && end > -1) { acctype = response.substring(start + "<accType>".length(), end); } editor.putString("acctype", acctype); String sessionId = ""; start = response.indexOf("<sessionId>"); end = response.indexOf("</sessionId>"); if (start > -1 && end > -1) { sessionId = response.substring(start + "<sessionId>".length(), end); } editor.putString("sessionId", sessionId); String reqNum = ""; start = response.indexOf("<reqNum>"); end = response.indexOf("</reqNum>"); if (start > -1 && end > -1) { reqNum = response.substring(start + "<reqNum>".length(), end); } editor.putString("reqNum", reqNum); boolean result = editor.commit(); if (result) { Toast.makeText(this, R.string.authenticationSuccess, Toast.LENGTH_LONG).show(); String accountType = this.getIntent().getStringExtra("auth.token"); if (accountType == null) { accountType = SemAssistAuthenticator.ACCOUNT_TYPE; } AccountManager accMgr = AccountManager.get(this); // Add the account to the Android Account Manager String accountName = username + "@semanticassistants.com"; final Account account = new Account(accountName, accountType); accMgr.addAccountExplicitly(account, password, null); // Inform the caller (could be the Android Account Manager or the SA app) that the process was successful final Intent intent = new Intent(); intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, accountName); intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType); intent.putExtra(AccountManager.KEY_AUTHTOKEN, accountType); this.setAccountAuthenticatorResult(intent.getExtras()); this.setResult(RESULT_OK, intent); this.finish(); } else { Toast.makeText(this, "Could not write the preferences.", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, R.string.authenticationFail, Toast.LENGTH_LONG).show(); } }
From source file:org.microg.gms.auth.login.LoginActivity.java
@SuppressLint("AddJavascriptInterface") @Override// ww w . jav a2s . c o m protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); accountType = AuthConstants.DEFAULT_ACCOUNT_TYPE; accountManager = AccountManager.get(LoginActivity.this); inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); webView = createWebView(this); webView.addJavascriptInterface(new JsBridge(), "mm"); authContent = (ViewGroup) findViewById(R.id.auth_content); ((ViewGroup) findViewById(R.id.auth_root)).addView(webView); webView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { Log.d(TAG, "pageFinished: " + url); if ("identifier".equals(Uri.parse(url).getFragment())) runOnUiThread(new Runnable() { @Override public void run() { webView.setVisibility(VISIBLE); } }); if ("close".equals(Uri.parse(url).getFragment())) closeWeb(false); if (url.startsWith(PROGRAMMATIC_AUTH_URL)) closeWeb(true); } }); if (getIntent().hasExtra(EXTRA_TOKEN)) { if (getIntent().hasExtra(EXTRA_EMAIL)) { AccountManager accountManager = AccountManager.get(LoginActivity.this); Account account = new Account(getIntent().getStringExtra(EXTRA_EMAIL), accountType); accountManager.addAccountExplicitly(account, getIntent().getStringExtra(EXTRA_TOKEN), null); retrieveGmsToken(account); } else { retrieveRtToken(getIntent().getStringExtra(EXTRA_TOKEN)); } } else { setMessage(R.string.auth_before_connect); setBackButtonText(android.R.string.cancel); setNextButtonText(R.string.auth_sign_in); } }
From source file:mobile.tiis.appv2.LoginActivity.java
/** * This method will take the url built to use the webservice * and will try to parse JSON from the webservice stream to get * the user and password if they are correct or not. In case correct, fills * the Android Account Manager./* w w w . ja v a2 s .c om*/ * * <p>This method will throw a Toast message when user and password * are not valid * */ protected void startWebService(final CharSequence loginURL, final String username, final String password) { client.setBasicAuth(username, password, true); //new handler in case of login error in the thread handler = new Handler(); Thread thread = new Thread(new Runnable() { public void run() { try { int balanceCounter = 0; DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(loginURL.toString()); Utils.writeNetworkLogFileOnSD( Utils.returnDeviceIdAndTimestamp(getApplicationContext()) + loginURL.toString()); httpGet.setHeader("Authorization", "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP)); HttpResponse httpResponse = httpClient.execute(httpGet); InputStream inputStream = httpResponse.getEntity().getContent(); Log.d("", loginURL.toString()); ByteArrayInputStream bais = Utils.getMultiReadInputStream(inputStream); Utils.writeNetworkLogFileOnSD(Utils.returnDeviceIdAndTimestamp(getApplicationContext()) + Utils.getStringFromInputStreamAndLeaveStreamOpen(bais)); bais.reset(); JsonFactory factory = new JsonFactory(); JsonParser jsonParser = factory.createJsonParser(bais); JsonToken token = jsonParser.nextToken(); if (token == JsonToken.START_OBJECT) { balanceCounter++; boolean idNextToHfId = false; while (!(balanceCounter == 0)) { token = jsonParser.nextToken(); if (token == JsonToken.START_OBJECT) { balanceCounter++; } else if (token == JsonToken.END_OBJECT) { balanceCounter--; } else if (token == JsonToken.FIELD_NAME) { String object = jsonParser.getCurrentName(); switch (object) { case "HealthFacilityId": token = jsonParser.nextToken(); app.setLoggedInUserHealthFacilityId(jsonParser.getText()); Log.d("", "healthFacilityId is: " + jsonParser.getText()); idNextToHfId = true; break; case "Firstname": token = jsonParser.nextToken(); app.setLoggedInFirstname(jsonParser.getText()); Log.d("", "firstname is: " + jsonParser.getText()); break; case "Lastname": token = jsonParser.nextToken(); app.setLoggedInLastname(jsonParser.getText()); Log.d("", "lastname is: " + jsonParser.getText()); break; case "Username": token = jsonParser.nextToken(); app.setLoggedInUsername(jsonParser.getText()); Log.d("", "username is: " + jsonParser.getText()); break; case "Lastlogin": token = jsonParser.nextToken(); Log.d("", "lastlogin is: " + jsonParser.getText()); break; case "Id": if (idNextToHfId) { token = jsonParser.nextToken(); app.setLoggedInUserId(jsonParser.getText()); Log.d("", "Id is: " + jsonParser.getText()); } break; default: break; } } } Account account = new Account(username, ACCOUNT_TYPE); AccountManager accountManager = AccountManager.get(LoginActivity.this); // boolean accountCreated = accountManager.addAccountExplicitly(account, LoginActivity.this.password, null); boolean accountCreated = accountManager.addAccountExplicitly(account, password, null); Bundle extras = LoginActivity.this.getIntent().getExtras(); if (extras != null) { if (accountCreated) { //Pass the new account back to the account manager AccountAuthenticatorResponse response = extras .getParcelable(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE); Bundle res = new Bundle(); res.putString(AccountManager.KEY_ACCOUNT_NAME, username); res.putString(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE); res.putString(AccountManager.KEY_PASSWORD, password); response.onResult(res); } } SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("secondSyncNeeded", true); editor.commit(); ContentValues values = new ContentValues(); values.put(SQLHandler.SyncColumns.UPDATED, 1); values.put(SQLHandler.UserColumns.FIRSTNAME, app.getLOGGED_IN_FIRSTNAME()); values.put(SQLHandler.UserColumns.LASTNAME, app.getLOGGED_IN_LASTNAME()); values.put(SQLHandler.UserColumns.HEALTH_FACILITY_ID, app.getLOGGED_IN_USER_HF_ID()); values.put(SQLHandler.UserColumns.ID, app.getLOGGED_IN_USER_ID()); values.put(SQLHandler.UserColumns.USERNAME, app.getLOGGED_IN_USERNAME()); values.put(SQLHandler.UserColumns.PASSWORD, password); databaseHandler.addUser(values); Log.d(TAG, "initiating offline for " + username + " password = " + password); app.initializeOffline(username, password); Intent intent; if (prefs.getBoolean("synchronization_needed", true)) { Log.d("supportLog", "call the loggin second time before the account was found"); intent = new Intent(LoginActivity.this, LotSettingsActivity.class); } else { Log.d("supportLog", "call the loggin second time before the account was found"); intent = new Intent(LoginActivity.this, LotSettingsActivity.class); evaluateIfFirstLogin(app.getLOGGED_IN_USER_ID()); } app.setUsername(username); startActivity(intent); } //if login failed show error else { handler.post(new Runnable() { public void run() { progressDialog.show(); progressDialog.dismiss(); toastMessage("Login failed.\nPlease check your details!"); loginButton.setEnabled(true); } }); } } catch (Exception e) { handler.post(new Runnable() { public void run() { progressDialog.show(); progressDialog.dismiss(); toastMessage("Login failed Login failed.\n" + "Please check your details or your web connectivity"); loginButton.setEnabled(true); } }); e.printStackTrace(); } } }); thread.start(); }
From source file:github.popeen.dsub.activity.SubsonicFragmentActivity.java
private void createAccount() { final Context context = this; new SilentBackgroundTask<Void>(this) { @Override//from ww w.j a v a 2s . c o m protected Void doInBackground() throws Throwable { AccountManager accountManager = (AccountManager) context.getSystemService(ACCOUNT_SERVICE); Account account = new Account(Constants.SYNC_ACCOUNT_NAME, Constants.SYNC_ACCOUNT_TYPE); accountManager.addAccountExplicitly(account, null, null); SharedPreferences prefs = Util.getPreferences(context); boolean syncEnabled = prefs.getBoolean(Constants.PREFERENCES_KEY_SYNC_ENABLED, true); int syncInterval = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_SYNC_INTERVAL, "60")); // Add enabled/frequency to playlist/podcasts syncing ContentResolver.setSyncAutomatically(account, Constants.SYNC_ACCOUNT_PLAYLIST_AUTHORITY, syncEnabled); ContentResolver.addPeriodicSync(account, Constants.SYNC_ACCOUNT_PLAYLIST_AUTHORITY, new Bundle(), 60L * syncInterval); ContentResolver.setSyncAutomatically(account, Constants.SYNC_ACCOUNT_PODCAST_AUTHORITY, syncEnabled); ContentResolver.addPeriodicSync(account, Constants.SYNC_ACCOUNT_PODCAST_AUTHORITY, new Bundle(), 60L * syncInterval); // Add for starred/recently added ContentResolver.setSyncAutomatically(account, Constants.SYNC_ACCOUNT_STARRED_AUTHORITY, (syncEnabled && prefs.getBoolean(Constants.PREFERENCES_KEY_SYNC_STARRED, false))); ContentResolver.addPeriodicSync(account, Constants.SYNC_ACCOUNT_STARRED_AUTHORITY, new Bundle(), 60L * syncInterval); ContentResolver.setSyncAutomatically(account, Constants.SYNC_ACCOUNT_MOST_RECENT_AUTHORITY, (syncEnabled && prefs.getBoolean(Constants.PREFERENCES_KEY_SYNC_MOST_RECENT, false))); ContentResolver.addPeriodicSync(account, Constants.SYNC_ACCOUNT_MOST_RECENT_AUTHORITY, new Bundle(), 60L * syncInterval); return null; } @Override protected void done(Void result) { } }.execute(); }
From source file:at.bitfire.davdroid.syncadapter.AccountDetailsFragment.java
void addAccount() { ServerInfo serverInfo = (ServerInfo) getArguments().getSerializable(KEY_SERVER_INFO); String accountName = editAccountName.getText().toString(); AccountManager accountManager = AccountManager.get(getActivity()); Account account = new Account(accountName, Constants.ACCOUNT_TYPE); Bundle userData = new Bundle(); userData.putString(Constants.ACCOUNT_KEY_BASE_URL, serverInfo.getBaseURL()); userData.putString(Constants.ACCOUNT_KEY_USERNAME, serverInfo.getUserName()); userData.putString(Constants.ACCOUNT_KEY_AUTH_PREEMPTIVE, Boolean.toString(serverInfo.isAuthPreemptive())); boolean syncContacts = false; for (ServerInfo.ResourceInfo addressBook : serverInfo.getAddressBooks()) if (addressBook.isEnabled()) { userData.putString(Constants.ACCOUNT_KEY_ADDRESSBOOK_PATH, addressBook.getPath()); ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1); syncContacts = true;//from ww w . j a va2 s.co m continue; } if (syncContacts) { ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1); ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true); } else ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 0); if (accountManager.addAccountExplicitly(account, serverInfo.getPassword(), userData)) { // account created, now create calendars ContentResolver.setIsSyncable(account, "com.android.calendar", 0); getActivity().finish(); } else Toast.makeText(getActivity(), "Couldn't create account (account with this name already existing?)", Toast.LENGTH_LONG).show(); }
From source file:com.quarterfull.newsAndroid.NewsReaderListActivity.java
/** * Check if the account is in the Android Account Manager. If not it will be added automatically *//*from ww w. ja v a2 s .c om*/ private void initAccountManager() { AccountManager mAccountManager = AccountManager.get(this); boolean isAccountThere = false; Account[] accounts = mAccountManager.getAccounts(); for (Account account : accounts) { if (account.type.intern().equals(AccountGeneral.ACCOUNT_TYPE)) { isAccountThere = true; } } //If the account is not in the Android Account Manager if (!isAccountThere) { //Then add the new account Account account = new Account(getString(R.string.app_name), AccountGeneral.ACCOUNT_TYPE); mAccountManager.addAccountExplicitly(account, "", new Bundle()); SyncIntervalSelectorActivity.SetAccountSyncInterval(this); } }
From source file:org.linphone.ContactsManager.java
public void initializeSyncAccount(Context context, ContentResolver contentResolver) { initializeContactManager(context, contentResolver); AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE); Account[] accounts = accountManager.getAccountsByType(context.getPackageName()); if (accounts != null && accounts.length == 0) { Account newAccount = new Account(context.getString(R.string.sync_account_name), context.getPackageName()); try {/*from ww w. j a va 2 s . c o m*/ accountManager.addAccountExplicitly(newAccount, null, null); mAccount = newAccount; } catch (Exception e) { Log.e(e); mAccount = null; } } else { mAccount = accounts[0]; } initializeContactManager(context, contentResolver); }
From source file:com.he5ed.lib.cloudprovider.auth.OAuth2Fragment.java
/** * Create a new user account or update the current user account * * @param user user information returned from server *///from w w w . j a va2 s . c o m private void addAccount(User user) { boolean accountExist = false; AccountManager am = AccountManager.get(getActivity()); // check if account already exist in AccountManager Account[] accounts = am.getAccountsByType(CloudProvider.ACCOUNT_TYPE); for (Account account : accounts) { if (account.name.equals(user.id)) { accountExist = true; break; } } Account account = new Account(user.id, CloudProvider.ACCOUNT_TYPE); Bundle userData = new Bundle(); // must be string value String accessToken = mTokenInfo.get(Authenticator.KEY_ACCESS_TOKEN); String refreshToken = mTokenInfo.get(Authenticator.KEY_REFRESH_TOKEN); String expiryDuration = mTokenInfo.get(Authenticator.KEY_EXPIRY); if (accountExist) { // update current account access token am.setAuthToken(account, CloudProvider.AUTH_TYPE, accessToken); if (refreshToken != null) am.setUserData(account, Authenticator.KEY_REFRESH_TOKEN, refreshToken); if (expiryDuration != null) am.setUserData(account, Authenticator.KEY_EXPIRY, expiryDuration); } else { // add new account into AccountManager if (refreshToken != null) userData.putString(Authenticator.KEY_REFRESH_TOKEN, refreshToken); if (expiryDuration != null) userData.putString(Authenticator.KEY_EXPIRY, expiryDuration); userData.putString(Authenticator.KEY_CLOUD_API, AuthHelper.getCloudApi(mCloudApi)); userData.putString(Authenticator.KEY_USERNAME, user.name); userData.putString(Authenticator.KEY_EMAIL, user.email); userData.putString(Authenticator.KEY_AVATAR_URL, user.avatarUrl); am.addAccountExplicitly(account, null, userData); am.setAuthToken(account, CloudProvider.AUTH_TYPE, accessToken); } // send result back to AccountManager Bundle result = new Bundle(); result.putString(AccountManager.KEY_ACCOUNT_NAME, user.id); result.putString(AccountManager.KEY_ACCOUNT_TYPE, CloudProvider.ACCOUNT_TYPE); ((AccountAuthenticatorActivity) getActivity()).setAccountAuthenticatorResult(result); getActivity().finish(); }