Example usage for android.accounts AccountManager get

List of usage examples for android.accounts AccountManager get

Introduction

In this page you can find the example usage for android.accounts AccountManager get.

Prototype

public static AccountManager get(Context context) 

Source Link

Document

Gets an AccountManager instance associated with a Context.

Usage

From source file:de.kollode.redminebrowser.sync.SyncHelper.java

void performSync(SyncResult syncResult, Account account) throws IOException {

    NotificationManager mNotificationManager = (NotificationManager) mContext
            .getSystemService(Context.NOTIFICATION_SERVICE);

    android.support.v4.app.NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext);
    mBuilder.setContentTitle("Projects").setContentText("Syncing in progress")
            .setSmallIcon(R.drawable.ic_launcher);

    final ContentResolver resolver = mContext.getContentResolver();
    ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);

    AccountManager accMgr = AccountManager.get(this.mContext);
    String serverUrl = accMgr.getUserData(account, "serverUrl");

    if (isOnline()) {

        final long startRemote = System.currentTimeMillis();

        int syncedProjects = 0;
        Log.i(sTag, "Remote syncing speakers");
        Log.i(sTag, serverUrl);//  w w w  .j a v a2s .com

        try {

            int offset = 0;
            int numberOfProjects;
            int limit = 100;
            boolean loadMore = true;

            do {
                String restQuery = "sort=updated_on:desc&limit=" + limit + "&offset=" + offset + "&key="
                        + accMgr.getPassword(account);

                Log.d(sTag, "REST URL: " + serverUrl + "/projects.json?" + restQuery);
                JSONObject projectsJson = getJsonFromUrl(serverUrl + "/projects.json?" + restQuery);

                numberOfProjects = projectsJson.getInt("total_count");
                mBuilder.setProgress(numberOfProjects, syncedProjects, false);
                mNotificationManager.notify(0, mBuilder.build());

                if (numberOfProjects < limit + offset) {
                    Log.d(sTag, "Enough Projects");
                    loadMore = false;
                } else {
                    Log.d(sTag, "More Projects");
                    offset += limit;
                }

                JSONArray projects = projectsJson.getJSONArray("projects");

                for (int i = 0; i < projects.length(); i++) {

                    JSONObject project = projects.getJSONObject(i);
                    Builder projectBuilder = ContentProviderOperation
                            .newInsert(Project.buildProjectsUri(account.name));

                    Log.d(sTag, project.toString());

                    try {
                        projectBuilder.withValue(Project.PARENT, project.getJSONObject("parent").getInt("id"));
                    } catch (Exception e) {

                    }

                    batch.add(projectBuilder.withValue(BaseColumns._ID, project.getInt("id"))
                            .withValue(Project.NAME, project.getString("name"))
                            .withValue(Project.IDENTIFIER, project.getString("identifier"))
                            .withValue(Project.UPDATED, System.currentTimeMillis())
                            .withValue(Project.CREATED, System.currentTimeMillis())
                            .withValue(Project.CREATED_ON, project.getString("created_on"))
                            .withValue(Project.UPDATED_ON, project.getString("updated_on")).build());

                    mBuilder.setProgress(numberOfProjects, syncedProjects++, false);
                    mNotificationManager.notify(0, mBuilder.build());
                }
            } while (loadMore && !this.isCanceled());

            try {
                // Apply all queued up batch operations for local data.
                resolver.applyBatch(RedmineTables.CONTENT_AUTHORITY, batch);
            } catch (RemoteException e) {
                throw new RuntimeException("Problem applying batch operation", e);
            } catch (OperationApplicationException e) {
                throw new RuntimeException("Problem applying batch operation", e);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (this.isCanceled()) {
            mBuilder.setContentText("Sync was canceled").setProgress(0, 0, false);
        } else {
            mBuilder.setContentText("Sync complete").setProgress(0, 0, false);
        }
        mNotificationManager.notify(0, mBuilder.build());

        syncResult.delayUntil = ((long) 60 * 60);

        Log.d(sTag, "Remote sync took " + (System.currentTimeMillis() - startRemote) + "ms");
        Log.d(sTag, "Number of projects: " + syncedProjects);
    }
}

From source file:com.afwsamples.testdpc.AddAccountActivity.java

private void addAccount(String accountName) {
    AccountManager accountManager = AccountManager.get(this);
    Bundle bundle = new Bundle();
    if (!TextUtils.isEmpty(accountName)) {
        bundle.putString(AccountManager.KEY_ACCOUNT_NAME, accountName);
    }// w  w  w .  j a  va  2  s.  c o m

    accountManager.addAccount(GOOGLE_ACCOUNT_TYPE, null, null, bundle, this, accountManagerFuture -> {
        try {
            Bundle result = accountManagerFuture.getResult();
            String accountNameAdded = result.getString(AccountManager.KEY_ACCOUNT_NAME);
            Log.d(TAG, "addAccount - accountNameAdded: " + accountNameAdded);
            if (mNextActivityIntent != null) {
                startActivity(mNextActivityIntent);
            }
            finish();
        } catch (OperationCanceledException | AuthenticatorException | IOException e) {
            Log.e(TAG, "addAccount - failed", e);
            Toast.makeText(AddAccountActivity.this, R.string.fail_to_add_account, Toast.LENGTH_LONG).show();
        }
    }, null);
}

From source file:com.ntsync.android.sync.activities.PaymentVerificationService.java

private static void runVerifier(final Context context, final ScheduledExecutorService sched) {
    SystemHelper.initSystem(context);//from   ww  w  . j  a  v a2s  . com
    // Check if PaymentData available -> when no cancel
    AccountManager acm = AccountManager.get(context);
    Account[] accounts = acm.getAccountsByType(Constants.ACCOUNT_TYPE);
    boolean foundPaymentData = false;
    for (Account account : accounts) {
        PaymentData paymentData = SyncUtils.getPayment(account, acm);
        if (paymentData != null) {
            if (SyncUtils.isPaymentVerificationStarted()) {
                return;
            }

            if (System.currentTimeMillis() > paymentData.paymentSaveDate + TIMEOUT_PENDING_PAYMENT) {
                sendNotification(context, account, R.string.shop_activity_pendingverification,
                        ShopActivity.class, false);
            }
            foundPaymentData = true;
            break;
        }
    }

    if (foundPaymentData) {
        // Check if user has to be notified

        // Start Service
        Intent verifService = new Intent(context, PaymentVerificationService.class);
        context.startService(verifService);
        LogHelper.logD(TAG, "Start PaymentVerificationService", null);
    } else {
        sched.shutdownNow();
    }
}

From source file:net.translatewiki.app.TranslateWikiApp.java

/** @return api instance for this application */
@Override/*from   w w  w.jav  a2 s  .c o m*/
public Account getCurrentAccount() {
    if (currentAccount == null) {
        AccountManager accountManager = AccountManager.get(this);
        Account[] allAccounts = accountManager.getAccountsByType(getString(R.string.account_type_identifier));
        if (allAccounts.length != 0) {
            currentAccount = allAccounts[0];
        }
    }
    return currentAccount;
}

From source file:com.github.riotopsys.shoppinglist.activity.ShoppingListPreview.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_shopping_list_preview);

    AccountUtils accountUtils = new AccountUtils();
    String account = accountUtils.getAccountName(this);

    if (account == null) {
        AccountManager am = AccountManager.get(this);
        am.getAuthTokenByFeatures(AppKeys.ACCOUNT_TYPE, AppKeys.OAUTH2_SCOPE, null, this, null, null,
                new AccountManagerCallback<Bundle>() {
                    @Override/*  w  ww  .  ja  v  a2 s  . com*/
                    public void run(AccountManagerFuture<Bundle> future) {
                        try {
                            Bundle bundle = future.getResult();
                            Log.i(TAG, "Got Bundle:\n" + " act name: "
                                    + bundle.getString(AccountManager.KEY_ACCOUNT_NAME) + "\n act type: "
                                    + bundle.getString(AccountManager.KEY_ACCOUNT_TYPE) + "\n auth token: "
                                    + bundle.getString(AccountManager.KEY_AUTHTOKEN));
                            AccountUtils accountUtils = new AccountUtils();
                            accountUtils.setAccountName(getBaseContext(),
                                    bundle.getString(AccountManager.KEY_ACCOUNT_NAME));
                            accountUtils.setToken(getBaseContext(),
                                    bundle.getString(AccountManager.KEY_AUTHTOKEN));
                        } catch (Exception e) {
                            Log.i(TAG, "getAuthTokenByFeatures() cancelled or failed:", e);
                            Toast.makeText(getBaseContext(), R.string.no_account, Toast.LENGTH_LONG).show();
                            finish();
                        }
                    }
                }, null);
    }

    mShoppingListCollection = new ShoppingListCollection();

    mShoppingListCollectionAdapter = new ShoppingListCollectionAdapter(this, getSupportFragmentManager(),
            mShoppingListCollection);

    //      mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mShoppingListCollectionAdapter);

    Intent startingIntent = getIntent();
    if (startingIntent != null) {
        Uri data = startingIntent.getData();
        if (data != null) {
            UUID guid = UUID.fromString(data.getLastPathSegment());
            Intent i = new Intent(this, ServerInterfaceService.class);
            i.putExtra(AppKeys.SERVER_TASK_KEY, ServerTask.SUBSCRIBE);
            i.putExtra(AppKeys.GUID_KEY, guid);
            startService(i);
        }
    }

    IConfigurations config = new Configurations();

    GCMRegistrar.checkDevice(this);
    GCMRegistrar.checkManifest(this);
    final String regId = GCMRegistrar.getRegistrationId(this);
    if (regId.equals("")) {
        GCMRegistrar.register(this, config.getGCMSenderID());
    } else {
        Log.v(TAG, "Already registered");
    }

}

From source file:com.rukman.emde.smsgroups.syncadapter.SyncAdapter.java

public SyncAdapter(Context context, boolean autoInitialize) {
    super(context, autoInitialize);
    mAccountManager = AccountManager.get(context);
}

From source file:com.nextgis.maplibui.mapui.LayerFactoryUI.java

public void createNewNGWLayer(final Context context, final LayerGroup layerGroup) {
    if (context instanceof NGActivity) {
        AccountManager accountManager = AccountManager.get(context);
        Connections connections = SelectNGWResourceDialog.fillConnections(context, accountManager);
        if (connections.getChildrenCount() == 1) {
            startNGWResourceActivity(context, (Connection) connections.getChild(0), layerGroup);
        } else {//from  w  w  w . ja va2s.c om
            NGActivity fragmentActivity = (NGActivity) context;
            final SelectNGWResourceDialog newFragment = new SelectNGWResourceDialog();
            newFragment.setLayerGroup(layerGroup)
                    .setTypeMask(Connection.NGWResourceTypePostgisLayer | Connection.NGWResourceTypeVectorLayer
                            | Connection.NGWResourceTypeRasterLayer | Connection.NGWResourceTypeWMSClient
                            | Connection.NGWResourceTypeWebMap)
                    .setConnectionListener(new NGWResourcesListAdapter.OnConnectionListener() {
                        @Override
                        public void onConnectionSelected(Connection connection) {
                            startNGWResourceActivity(context, connection, layerGroup);
                            newFragment.dismiss();
                        }

                        @Override
                        public void onAddConnection() {
                            newFragment.onAddAccount(context);
                        }
                    }).setTitle(context.getString(R.string.choose_layers))
                    .setTheme(fragmentActivity.getThemeId())
                    .show(fragmentActivity.getSupportFragmentManager(), "create_ngw_layer");
        }
    }
}

From source file:edu.mit.mobile.android.locast.sync.AbsLocastAccountSyncService.java

@Override
public void onCreate() {
    super.onCreate();

    mProvider = (SyncableProvider) getContentResolver().acquireContentProviderClient(getAuthority())
            .getLocalContentProvider();/*from   www. j av  a 2  s .  c  o m*/

    mSyncAdapter = new LocastSyncAdapter(this, mProvider);

    AccountManager.get(this).addOnAccountsUpdatedListener(mSyncAdapter, null, true);
}

From source file:com.manning.androidhacks.hack023.authenticator.AuthenticatorActivity.java

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    mAccountManager = AccountManager.get(this);
    checkMaximumNumberOfAccounts();//from   ww w.jav a  2 s  .com

    final Intent intent = getIntent();

    mUser = intent.getStringExtra(PARAM_USER);
    mAuthTokenType = intent.getStringExtra(PARAM_AUTHTOKEN_TYPE);
    mRequestNewAccount = mUsername == null;
    mConfirmCredentials = intent.getBooleanExtra(PARAM_CONFIRMCREDENTIALS, false);

    Log.i(TAG, "    request new: " + mRequestNewAccount);
    requestWindowFeature(Window.FEATURE_LEFT_ICON);
    setContentView(R.layout.login);
    getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, android.R.drawable.ic_dialog_alert);

    findViews();
    initFields();
}