Exemplo n.º 1
0
  private void loadThirdPartyResources() {
    ImPluginHelper helper = ImPluginHelper.getInstance(this);
    helper.loadAvailablePlugins();
    ArrayList<ImPlugin> pluginList = helper.getPluginObjects();
    ArrayList<ImPluginInfo> infoList = helper.getPluginsInfo();
    int N = pluginList.size();
    PackageManager pm = getPackageManager();
    for (int i = 0; i < N; i++) {
      ImPlugin plugin = pluginList.get(i);
      ImPluginInfo pluginInfo = infoList.get(i);

      try {
        Resources packageRes = pm.getResourcesForApplication(pluginInfo.mPackageName);

        Map<Integer, Integer> resMap = plugin.getResourceMap();
        int[] smileyIcons = plugin.getSmileyIconIds();

        BrandingResources res =
            new BrandingResources(packageRes, resMap, smileyIcons, mDefaultBrandingResources);
        mBrandingResources.put(pluginInfo.mProviderName, res);
      } catch (NameNotFoundException e) {
        Log.e(LOG_TAG, "Failed to load third party resources.", e);
      }
    }
  }
Exemplo n.º 2
0
  @SuppressWarnings("deprecation")
  private boolean cursorUnlocked() {
    try {
      mApp = ImApp.getApplication(this);
      mHandler = new MyHandler(this);
      ImPluginHelper.getInstance(this).loadAvailablePlugins();

      mProviderCursor =
          managedQuery(
              Imps.Provider.CONTENT_URI_WITH_ACCOUNT,
              PROVIDER_PROJECTION,
              Imps.Provider.CATEGORY + "=?" /* selection */,
              new String[] {ImApp.IMPS_CATEGORY} /* selection args */,
              Imps.Provider.DEFAULT_SORT_ORDER);

      mProviderCursor.moveToFirst();

      return true;

    } catch (Exception e) {
      Log.e(ImApp.LOG_TAG, e.getMessage(), e);
      // needs to be unlocked
      return false;
    }
  }
  private void showNewAccountListDialog() {

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(R.string.account_select_type);

    List<String> listProviders = helper.getProviderNames();

    mAccountList = new String[listProviders.size() + 1];

    int i = 0;

    for (String providerName : listProviders) mAccountList[i++] = providerName;

    mAccountList[i] = getString(R.string.google_account);

    builder.setItems(
        mAccountList,
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int pos) {

            if (pos > helper.getProviderNames().size() - 1) // google accounts based on xmpp
            {
              showGoogleAccountListDialog();
            } else {
              // otherwise support the actual plugin-type
              showSetupAccountForm(mAccountList[pos], null, null);
            }
          }
        });
    AlertDialog dialog = builder.create();
    dialog.show();
  }
  @Override
  protected void onCreate(Bundle icicle) {

    ((ImApp) getApplication()).setAppTheme(this);

    super.onCreate(icicle);

    ThemeableActivity.setBackgroundImage(this);

    mApp = ImApp.getApplication(this);
    mHandler = new MyHandler(this);
    mSignInHelper = new SignInHelper(this);

    ImPluginHelper.getInstance(this).loadAvailablePlugins();

    mProviderCursor =
        managedQuery(
            Imps.Provider.CONTENT_URI_WITH_ACCOUNT,
            PROVIDER_PROJECTION,
            Imps.Provider.CATEGORY
                + "=?"
                + " AND "
                + Imps.Provider.ACTIVE_ACCOUNT_USERNAME
                + " NOT NULL" /* selection */,
            new String[] {ImApp.IMPS_CATEGORY} /* selection args */,
            Imps.Provider.DEFAULT_SORT_ORDER);
    Intent intent = getIntent();

    if (ImApp.ACTION_QUIT.equals(intent.getAction())) {
      signOutAndKillProcess();
      return;
    }

    mAdapter = new ProviderAdapter(this, mProviderCursor);
    setListAdapter(mAdapter);

    ViewGroup godfatherView = (ViewGroup) this.getWindow().getDecorView();
    FontUtils.setRobotoFont(this, godfatherView);

    registerForContextMenu(getListView());

    View emptyView = getLayoutInflater().inflate(R.layout.empty_account_view, godfatherView, false);
    emptyView.setVisibility(View.GONE);
    ((ViewGroup) getListView().getParent()).addView(emptyView);

    getListView().setEmptyView(emptyView);
    emptyView.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View arg0) {

            if (getListView().getCount() == 0) {
              showNewAccountListDialog();
            }
          }
        });
  }
  public void showSetupAccountForm(String providerType, String username, String token) {
    long providerId = helper.createAdditionalProvider(providerType); // xmpp
    ((ImApp) getApplication()).resetProviderSettings(); // clear cached provider list

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_INSERT);

    intent.setData(ContentUris.withAppendedId(Imps.Provider.CONTENT_URI, providerId));
    intent.addCategory(ImApp.IMPS_CATEGORY);

    if (username != null) intent.putExtra("newuser", username);

    if (token != null) intent.putExtra("newpass", token);

    startActivity(intent);
  }
Exemplo n.º 6
0
  private void doOnResume() {

    if (mApp == null) {
      mApp = ImApp.getApplication(this);
      mHandler = new MyHandler(this);
      ImPluginHelper.getInstance(this).loadAvailablePlugins();
    }

    mApp.setAppTheme(this);
    mHandler.registerForBroadcastEvents();

    int countSignedIn = accountsSignedIn();
    int countAvailable = accountsAvailable();
    int countConfigured = accountsConfigured();

    if (countAvailable == 1) {
      // If just one account is available for auto-signin, go there immediately after service starts
      // trying
      // to connect.
      mSignInHelper.setSignInListener(
          new SignInHelper.Listener() {
            public void connectedToService() {}

            public void stateChanged(int state, long accountId) {
              if (state == ImConnection.LOGGING_IN) {
                mSignInHelper.goToAccount(accountId);
              }
            }
          });
    } else {
      mSignInHelper.setSignInListener(null);
    }

    if (countSignedIn == 0 && countAvailable > 0 && !mDidAutoLaunch && mDoSignIn) {
      mDidAutoLaunch = true;
      signInAll();
      showAccounts();
    } else if (countSignedIn == 1) {
      showActiveAccount();
    } else if (countConfigured > 0) {
      showAccounts();
    }
    // Otherwise, stay on Getting Started view
  }
public class AccountListActivity extends SherlockListActivity
    implements View.OnCreateContextMenuListener {

  private static final String TAG = ImApp.LOG_TAG;

  private static final int ID_SIGN_IN = Menu.FIRST + 1;
  private static final int ID_SIGN_OUT = Menu.FIRST + 2;
  private static final int ID_EDIT_ACCOUNT = Menu.FIRST + 3;
  private static final int ID_REMOVE_ACCOUNT = Menu.FIRST + 4;
  //    private static final int ID_SIGN_OUT_ALL = Menu.FIRST + 5;
  private static final int ID_ADD_ACCOUNT = Menu.FIRST + 6;
  private static final int ID_VIEW_CONTACT_LIST = Menu.FIRST + 7;

  private ProviderAdapter mAdapter;
  private Cursor mProviderCursor;
  private ImApp mApp;
  private SimpleAlertHandler mHandler;

  private SignInHelper mSignInHelper;

  private static final String[] PROVIDER_PROJECTION = {
    Imps.Provider._ID,
    Imps.Provider.NAME,
    Imps.Provider.FULLNAME,
    Imps.Provider.CATEGORY,
    Imps.Provider.ACTIVE_ACCOUNT_ID,
    Imps.Provider.ACTIVE_ACCOUNT_USERNAME,
    Imps.Provider.ACTIVE_ACCOUNT_PW,
    Imps.Provider.ACTIVE_ACCOUNT_LOCKED,
    Imps.Provider.ACTIVE_ACCOUNT_KEEP_SIGNED_IN,
    Imps.Provider.ACCOUNT_PRESENCE_STATUS,
    Imps.Provider.ACCOUNT_CONNECTION_STATUS
  };

  static final int PROVIDER_ID_COLUMN = 0;
  static final int PROVIDER_NAME_COLUMN = 1;
  static final int PROVIDER_FULLNAME_COLUMN = 2;
  static final int PROVIDER_CATEGORY_COLUMN = 3;
  static final int ACTIVE_ACCOUNT_ID_COLUMN = 4;
  static final int ACTIVE_ACCOUNT_USERNAME_COLUMN = 5;
  static final int ACTIVE_ACCOUNT_PW_COLUMN = 6;
  static final int ACTIVE_ACCOUNT_LOCKED = 7;
  static final int ACTIVE_ACCOUNT_KEEP_SIGNED_IN = 8;
  static final int ACCOUNT_PRESENCE_STATUS = 9;
  static final int ACCOUNT_CONNECTION_STATUS = 10;

  @Override
  protected void onCreate(Bundle icicle) {

    ((ImApp) getApplication()).setAppTheme(this);

    super.onCreate(icicle);

    ThemeableActivity.setBackgroundImage(this);

    mApp = ImApp.getApplication(this);
    mHandler = new MyHandler(this);
    mSignInHelper = new SignInHelper(this);

    ImPluginHelper.getInstance(this).loadAvailablePlugins();

    mProviderCursor =
        managedQuery(
            Imps.Provider.CONTENT_URI_WITH_ACCOUNT,
            PROVIDER_PROJECTION,
            Imps.Provider.CATEGORY
                + "=?"
                + " AND "
                + Imps.Provider.ACTIVE_ACCOUNT_USERNAME
                + " NOT NULL" /* selection */,
            new String[] {ImApp.IMPS_CATEGORY} /* selection args */,
            Imps.Provider.DEFAULT_SORT_ORDER);
    Intent intent = getIntent();

    if (ImApp.ACTION_QUIT.equals(intent.getAction())) {
      signOutAndKillProcess();
      return;
    }

    mAdapter = new ProviderAdapter(this, mProviderCursor);
    setListAdapter(mAdapter);

    ViewGroup godfatherView = (ViewGroup) this.getWindow().getDecorView();
    FontUtils.setRobotoFont(this, godfatherView);

    registerForContextMenu(getListView());

    View emptyView = getLayoutInflater().inflate(R.layout.empty_account_view, godfatherView, false);
    emptyView.setVisibility(View.GONE);
    ((ViewGroup) getListView().getParent()).addView(emptyView);

    getListView().setEmptyView(emptyView);
    emptyView.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View arg0) {

            if (getListView().getCount() == 0) {
              showNewAccountListDialog();
            }
          }
        });
  }

  private void reloadList() {
    //   mProviderCursor.close();
    mProviderCursor =
        managedQuery(
            Imps.Provider.CONTENT_URI_WITH_ACCOUNT,
            PROVIDER_PROJECTION,
            Imps.Provider.CATEGORY
                + "=?"
                + " AND "
                + Imps.Provider.ACTIVE_ACCOUNT_USERNAME
                + " NOT NULL" /* selection */,
            new String[] {ImApp.IMPS_CATEGORY} /* selection args */,
            Imps.Provider.DEFAULT_SORT_ORDER);
    mAdapter = new ProviderAdapter(this, mProviderCursor);
    setListAdapter(mAdapter);
  }

  @Override
  protected void onPause() {
    mHandler.unregisterForBroadcastEvents();

    super.onPause();
  }

  @Override
  protected void onDestroy() {
    mSignInHelper.stop();
    super.onDestroy();
  }

  @Override
  protected void onResume() {

    ((ImApp) getApplication()).setAppTheme(this);
    mHandler.registerForBroadcastEvents();
    super.onResume();
  }

  private void signInAccountAtPosition(int position) {
    Intent intent = null;
    mProviderCursor.moveToPosition(position);

    if (mProviderCursor.isNull(ACTIVE_ACCOUNT_ID_COLUMN)) {
      showNewAccountListDialog();

    } else {
      int state = mProviderCursor.getInt(ACCOUNT_CONNECTION_STATUS);
      long accountId = mProviderCursor.getLong(ACTIVE_ACCOUNT_ID_COLUMN);

      if (state == Imps.ConnectionStatus.OFFLINE) {
        boolean isKeepSignedIn = mProviderCursor.getInt(ACTIVE_ACCOUNT_KEEP_SIGNED_IN) != 0;
        boolean isAccountEditible = mProviderCursor.getInt(ACTIVE_ACCOUNT_LOCKED) == 0;
        if (isKeepSignedIn) {
          signIn(accountId);
        } else if (isAccountEditible) {
          intent = getEditAccountIntent();
        }
      } else if (state == Imps.ConnectionStatus.CONNECTING) {
        gotoAccount();
      } else {
        intent = getViewChatsIntent();
      }
    }

    if (intent != null) {
      startActivity(intent);
    }
  }

  private void signIn(long accountId) {
    if (accountId == 0) {
      Log.w(TAG, "signIn: account id is 0, bail");
      return;
    }

    boolean isAccountEditible = mProviderCursor.getInt(ACTIVE_ACCOUNT_LOCKED) == 0;
    if (isAccountEditible && mProviderCursor.isNull(ACTIVE_ACCOUNT_PW_COLUMN)) {
      // no password, edit the account
      if (Log.isLoggable(TAG, Log.DEBUG)) log("no pw for account " + accountId);
      Intent intent = getEditAccountIntent();
      startActivity(intent);
      return;
    }

    // Remember that the user signed in.
    setKeepSignedIn(accountId, true);

    long providerId = mProviderCursor.getLong(PROVIDER_ID_COLUMN);
    String password = mProviderCursor.getString(ACTIVE_ACCOUNT_PW_COLUMN);
    boolean isActive = false; // TODO(miron)
    mSignInHelper.signIn(password, providerId, accountId, isActive);
  }

  protected void gotoAccount() {
    long accountId = mProviderCursor.getLong(ACTIVE_ACCOUNT_ID_COLUMN);

    Intent intent = new Intent(this, ChatListActivity.class);
    // clear the back stack of the account setup
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, accountId);
    startActivity(intent);
    finish();
  }

  boolean isSigningIn(Cursor cursor) {
    int connectionStatus = cursor.getInt(ACCOUNT_CONNECTION_STATUS);
    return connectionStatus == Imps.ConnectionStatus.CONNECTING;
  }

  private boolean isSignedIn(Cursor cursor) {
    int connectionStatus = cursor.getInt(ACCOUNT_CONNECTION_STATUS);
    return connectionStatus == Imps.ConnectionStatus.ONLINE;
  }

  private boolean allAccountsSignedOut() {
    if (!mProviderCursor.moveToFirst()) {
      return false;
    }
    do {
      if (isSignedIn(mProviderCursor)) {
        return false;
      }
    } while (mProviderCursor.moveToNext());

    return true;
  }

  private void signOutAndKillPrompt() {
    DialogInterface.OnClickListener confirmListener =
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton) {
            mHandler.sendEmptyMessage(HANDLE_COMPLETE_EXIT);
          }
        };

    new AlertDialog.Builder(this)
        .setTitle(R.string.confirm)
        .setMessage(R.string.signout_kill_confirm_message)
        .setPositiveButton(R.string.yes, confirmListener) // default button
        .setNegativeButton(R.string.no, null)
        .setCancelable(true)
        .show();
  }

  private void signOutAndKillProcess() {

    if (ImApp.getApplication().hasActiveConnections()) {
      if (!mProviderCursor.moveToFirst()) return;
      do {
        long accountId = mProviderCursor.getLong(ACTIVE_ACCOUNT_ID_COLUMN);
        signOut(accountId);
      } while (mProviderCursor.moveToNext());

      try {
        Thread.sleep(3000);
      } catch (Exception e) {
      } // wait a second for account to log out
    }

    ImApp.getApplication().forceStopImService();
  }

  private void signOutAll() {
    DialogInterface.OnClickListener confirmListener =
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton) {

            if (!mProviderCursor.moveToFirst()) return;
            do {
              long accountId = mProviderCursor.getLong(ACTIVE_ACCOUNT_ID_COLUMN);
              signOut(accountId);
            } while (mProviderCursor.moveToNext());
          }
        };

    new AlertDialog.Builder(this)
        .setTitle(R.string.confirm)
        .setMessage(R.string.signout_all_confirm_message)
        .setPositiveButton(R.string.yes, confirmListener) // default button
        .setNegativeButton(R.string.no, null)
        .setCancelable(true)
        .show();
  }

  private void signOut(final long accountId) {
    if (accountId == 0) {
      Log.w(TAG, "signOut: account id is 0, bail");
      return;
    }

    // Remember that the user signed out and do not auto sign in until they
    // explicitly do so
    setKeepSignedIn(accountId, false);

    // Sign out
    mApp.callWhenServiceConnected(
        mHandler,
        new Runnable() {
          public void run() {
            try {
              IImConnection conn = mApp.getConnectionByAccount(accountId);
              if (conn != null) {
                conn.logout();
              }
            } catch (RemoteException ex) {
              Log.e(TAG, "signOut failed", ex);
            }
          }
        });
  }

  private void setKeepSignedIn(final long accountId, boolean signin) {
    Uri mAccountUri = ContentUris.withAppendedId(Imps.Account.CONTENT_URI, accountId);
    ContentValues values = new ContentValues();
    values.put(Imps.Account.KEEP_SIGNED_IN, signin);
    getContentResolver().update(mAccountUri, values, null, null);
  }

  @Override
  public boolean onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    menu.findItem(R.id.menu_sign_out_all).setVisible(!allAccountsSignedOut());
    return true;
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getSupportMenuInflater();
    inflater.inflate(R.menu.accounts_menu, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.menu_sign_out_all:
        signOutAll();
        return true;
      case R.id.menu_new_account:
        showNewAccountListDialog();
        return true;
      case R.id.menu_settings:
        Intent sintent = new Intent(this, SettingActivity.class);
        startActivityForResult(sintent, 1);
        return true;
      case R.id.menu_exit:
        signOutAndKillPrompt();

        return true;
    }
    return super.onOptionsItemSelected(item);
  }

  private String[] mAccountList;
  private String mNewUser;

  private ImPluginHelper helper = ImPluginHelper.getInstance(this);

  private void showNewAccountListDialog() {

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(R.string.account_select_type);

    List<String> listProviders = helper.getProviderNames();

    mAccountList = new String[listProviders.size() + 1];

    int i = 0;

    for (String providerName : listProviders) mAccountList[i++] = providerName;

    mAccountList[i] = getString(R.string.google_account);

    builder.setItems(
        mAccountList,
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int pos) {

            if (pos > helper.getProviderNames().size() - 1) // google accounts based on xmpp
            {
              showGoogleAccountListDialog();
            } else {
              // otherwise support the actual plugin-type
              showSetupAccountForm(mAccountList[pos], null, null);
            }
          }
        });
    AlertDialog dialog = builder.create();
    dialog.show();
  }

  private Handler mHandlerGoogleAuth =
      new Handler() {

        @Override
        public void handleMessage(Message msg) {

          super.handleMessage(msg);

          Log.d(TAG, "Got handler callback from auth: " + msg.what);
        }
      };

  private void showGoogleAccountListDialog() {

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(R.string.account_select_type);

    Account[] accounts = AccountManager.get(this).getAccountsByType(GTalkOAuth2.TYPE_GOOGLE_ACCT);

    mAccountList = new String[accounts.length];

    for (int i = 0; i < mAccountList.length; i++) mAccountList[i] = accounts[i].name;

    builder.setItems(
        mAccountList,
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int pos) {

            mNewUser = mAccountList[pos];
            Thread thread =
                new Thread() {
                  public void run() {
                    // get the oauth token

                    // don't store anything just make sure it works!
                    String password =
                        GTalkOAuth2.NAME
                            + ':'
                            + GTalkOAuth2.getGoogleAuthTokenAllow(
                                mNewUser,
                                getApplicationContext(),
                                AccountListActivity.this,
                                mHandlerGoogleAuth);

                    // use the XMPP type plugin for google accounts, and the .NAME "X-GOOGLE-TOKEN"
                    // as the password
                    showSetupAccountForm(helper.getProviderNames().get(0), mNewUser, password);
                  }
                };
            thread.start();
          }
        });
    AlertDialog dialog = builder.create();
    dialog.show();
  }

  public void showSetupAccountForm(String providerType, String username, String token) {
    long providerId = helper.createAdditionalProvider(providerType); // xmpp
    ((ImApp) getApplication()).resetProviderSettings(); // clear cached provider list

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_INSERT);

    intent.setData(ContentUris.withAppendedId(Imps.Provider.CONTENT_URI, providerId));
    intent.addCategory(ImApp.IMPS_CATEGORY);

    if (username != null) intent.putExtra("newuser", username);

    if (token != null) intent.putExtra("newpass", token);

    startActivity(intent);
  }

  @Override
  public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    AdapterView.AdapterContextMenuInfo info;
    try {
      info = (AdapterView.AdapterContextMenuInfo) menuInfo;
    } catch (ClassCastException e) {
      Log.e(TAG, "bad menuInfo", e);
      return;
    }

    Cursor providerCursor = (Cursor) getListAdapter().getItem(info.position);
    menu.setHeaderTitle(providerCursor.getString(PROVIDER_FULLNAME_COLUMN));

    if (providerCursor.isNull(ACTIVE_ACCOUNT_ID_COLUMN)) {
      menu.add(0, ID_ADD_ACCOUNT, 0, R.string.menu_edit_account);
      menu.add(0, ID_REMOVE_ACCOUNT, 0, R.string.menu_remove_account)
          .setIcon(android.R.drawable.ic_menu_delete);
      return;
    }

    long providerId = providerCursor.getLong(PROVIDER_ID_COLUMN);
    boolean isLoggingIn = isSigningIn(providerCursor);
    boolean isLoggedIn = isSignedIn(providerCursor);

    BrandingResources brandingRes = mApp.getBrandingResource(providerId);
    menu.add(
        0,
        ID_VIEW_CONTACT_LIST,
        0,
        brandingRes.getString(BrandingResourceIDs.STRING_MENU_CONTACT_LIST));
    if (isLoggedIn) {
      menu.add(0, ID_SIGN_OUT, 0, R.string.menu_sign_out)
          .setIcon(android.R.drawable.ic_menu_close_clear_cancel);
    } else if (isLoggingIn) {
      menu.add(0, ID_SIGN_OUT, 0, R.string.menu_cancel_signin)
          .setIcon(android.R.drawable.ic_menu_close_clear_cancel);
    } else {
      menu.add(0, ID_SIGN_IN, 0, R.string.sign_in)
      // TODO .setIcon(info.guardianproject.otr.app.internal.R.drawable.ic_menu_login)
      ;
    }

    boolean isAccountEditable = providerCursor.getInt(ACTIVE_ACCOUNT_LOCKED) == 0;
    if (isAccountEditable && !isLoggingIn && !isLoggedIn) {
      menu.add(0, ID_EDIT_ACCOUNT, 0, R.string.menu_edit_account)
          .setIcon(android.R.drawable.ic_menu_edit);
      menu.add(0, ID_REMOVE_ACCOUNT, 0, R.string.menu_remove_account)
          .setIcon(android.R.drawable.ic_menu_delete);
    }
  }

  @SuppressWarnings("deprecation")
  @Override
  public boolean onContextItemSelected(android.view.MenuItem item) {
    AdapterView.AdapterContextMenuInfo info;
    try {
      info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    } catch (ClassCastException e) {
      Log.e(TAG, "bad menuInfo", e);
      return false;
    }
    long providerId = info.id;
    Cursor providerCursor = (Cursor) getListAdapter().getItem(info.position);
    long accountId = providerCursor.getLong(ACTIVE_ACCOUNT_ID_COLUMN);

    switch (item.getItemId()) {
      case ID_EDIT_ACCOUNT:
        {
          startActivity(getEditAccountIntent());
          return true;
        }

      case ID_REMOVE_ACCOUNT:
        {
          Uri accountUri = ContentUris.withAppendedId(Imps.Account.CONTENT_URI, accountId);
          getContentResolver().delete(accountUri, null, null);
          Uri providerUri = ContentUris.withAppendedId(Imps.Provider.CONTENT_URI, providerId);
          getContentResolver().delete(providerUri, null, null);
          // Requery the cursor to force refreshing screen
          providerCursor.requery();
          return true;
        }

      case ID_VIEW_CONTACT_LIST:
        {
          Intent intent = getViewContactsIntent();
          startActivity(intent);
          return true;
        }
      case ID_ADD_ACCOUNT:
        {
          showNewAccountListDialog();

          return true;
        }

      case ID_SIGN_IN:
        {
          signIn(accountId);
          return true;
        }

      case ID_SIGN_OUT:
        {
          // TODO: progress bar
          signOut(accountId);
          return true;
        }
    }

    return false;
  }

  @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
    signInAccountAtPosition(position);
  }

  /*
  Intent getCreateAccountIntent() {
      Intent intent = new Intent();
      intent.setAction(Intent.ACTION_INSERT);

      long providerId = mProviderCursor.getLong(PROVIDER_ID_COLUMN);
      intent.setData(ContentUris.withAppendedId(Imps.Provider.CONTENT_URI, providerId));
      intent.addCategory(getProviderCategory(mProviderCursor));
      return intent;
  }*/

  Intent getEditAccountIntent() {
    Intent intent =
        new Intent(
            Intent.ACTION_EDIT,
            ContentUris.withAppendedId(
                Imps.Account.CONTENT_URI, mProviderCursor.getLong(ACTIVE_ACCOUNT_ID_COLUMN)));
    intent.addCategory(ImApp.IMPS_CATEGORY);
    return intent;
  }

  Intent getViewContactsIntent() {
    Intent intent = new Intent(this, ContactListActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(
        ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID,
        mProviderCursor.getLong(ACTIVE_ACCOUNT_ID_COLUMN));
    return intent;
  }

  Intent getViewChatsIntent() {
    Intent intent = new Intent(this, ChatListActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(
        ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID,
        mProviderCursor.getLong(ACTIVE_ACCOUNT_ID_COLUMN));
    return intent;
  }

  /*
  private String getProviderCategory(Cursor cursor) {
      return cursor.getString(PROVIDER_CATEGORY_COLUMN);
  }*/

  static void log(String msg) {
    Log.d(TAG, "[LandingPage]" + msg);
  }

  private class ProviderListItemFactory implements LayoutInflater.Factory {
    public View onCreateView(String name, Context context, AttributeSet attrs) {
      if (name != null && name.equals(ProviderListItem.class.getName())) {
        return new ProviderListItem(context, AccountListActivity.this);
      }
      return null;
    }
  }

  private final class ProviderAdapter extends CursorAdapter {
    private LayoutInflater mInflater;

    @SuppressWarnings("deprecation")
    public ProviderAdapter(Context context, Cursor c) {
      super(context, c);
      mInflater = LayoutInflater.from(context).cloneInContext(context);
      mInflater.setFactory(new ProviderListItemFactory());
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
      // create a custom view, so we can manage it ourselves. Mainly, we want to
      // initialize the widget views (by calling getViewById()) in newView() instead of in
      // bindView(), which can be called more often.
      ProviderListItem view =
          (ProviderListItem) mInflater.inflate(R.layout.account_view, parent, false);
      view.init(cursor);
      return view;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
      ((ProviderListItem) view).bindView(cursor);
    }
  }

  private static final int HANDLE_COMPLETE_EXIT = -999;

  private final class MyHandler extends SimpleAlertHandler {

    public MyHandler(Activity activity) {
      super(activity);
    }

    @Override
    public void handleMessage(Message msg) {
      if (msg.what == ImApp.EVENT_CONNECTION_DISCONNECTED) {
        promptDisconnectedEvent(msg);
      } else if (msg.what == HANDLE_COMPLETE_EXIT) {
        signOutAndKillProcess();
      }
      super.handleMessage(msg);
    }
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    Intent intent = getIntent();
    finish();
    startActivity(intent);
  }
}