Search in sources :

Example 1 with Phonenumber

use of com.google.i18n.phonenumbers.Phonenumber in project actor-platform by actorapp.

the class ProfileFragment method onCreateView.

@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    uid = getArguments().getInt(EXTRA_UID);
    final UserVM user = users().get(uid);
    ArrayList<UserPhone> phones = user.getPhones().get();
    ArrayList<UserEmail> emails = user.getEmails().get();
    String about = user.getAbout().get();
    final String userName = user.getNick().get();
    final View res = inflater.inflate(R.layout.fragment_profile, container, false);
    //
    // Style Background
    //
    res.findViewById(R.id.container).setBackgroundColor(style.getMainBackgroundColor());
    res.findViewById(R.id.avatarContainer).setBackgroundColor(style.getToolBarColor());
    //
    // User Avatar
    //
    avatarView = (AvatarView) res.findViewById(R.id.avatar);
    avatarView.init(Screen.dp(48), 22);
    avatarView.bind(user.getAvatar().get(), user.getName().get(), user.getId());
    avatarView.setOnClickListener(v -> {
        startActivity(ViewAvatarActivity.viewAvatar(user.getId(), getActivity()));
    });
    //
    // User Name
    //
    TextView nameText = (TextView) res.findViewById(R.id.name);
    nameText.setTextColor(style.getProfileTitleColor());
    bind(nameText, user.getName());
    //
    // User Last Seen
    //
    TextView lastSeen = (TextView) res.findViewById(R.id.lastSeen);
    lastSeen.setTextColor(style.getProfileSubtitleColor());
    bind(lastSeen, user);
    //
    // Fab
    //
    FloatingActionButton fab = (FloatingActionButton) res.findViewById(R.id.fab);
    fab.setBackgroundTintList(new ColorStateList(new int[][] { new int[] { android.R.attr.state_pressed }, StateSet.WILD_CARD }, new int[] { ActorSDK.sharedActor().style.getFabPressedColor(), ActorSDK.sharedActor().style.getFabColor() }));
    fab.setRippleColor(ActorSDK.sharedActor().style.getFabPressedColor());
    fab.setOnClickListener(v -> startActivity(new Intent(getActivity(), ComposeActivity.class)));
    //
    // Remove Contact
    //
    final View removeContact = res.findViewById(R.id.addContact);
    final TextView addContactTitle = (TextView) removeContact.findViewById(R.id.addContactTitle);
    addContactTitle.setText(getString(R.string.profile_contacts_added));
    addContactTitle.setTextColor(style.getTextPrimaryColor());
    removeContact.setOnClickListener(v -> {
        execute(ActorSDK.sharedActor().getMessenger().removeContact(user.getId()));
    });
    bind(user.isContact(), (isContact, valueModel) -> {
        if (isContact) {
            removeContact.setVisibility(View.VISIBLE);
            //fab
            fab.setImageResource(R.drawable.ic_message_white_24dp);
            fab.setOnClickListener(view -> startActivity(Intents.openPrivateDialog(user.getId(), true, getActivity())));
        } else {
            removeContact.setVisibility(View.GONE);
            //fab
            fab.setImageResource(R.drawable.ic_person_add_white_24dp);
            fab.setOnClickListener(view -> execute(ActorSDK.sharedActor().getMessenger().addContact(user.getId())));
        }
    });
    //
    // New Message
    //
    View newMessageView = res.findViewById(R.id.newMessage);
    ImageView newMessageIcon = (ImageView) newMessageView.findViewById(R.id.newMessageIcon);
    TextView newMessageTitle = (TextView) newMessageView.findViewById(R.id.newMessageText);
    {
        Drawable drawable = getResources().getDrawable(R.drawable.ic_chat_black_24dp);
        drawable.mutate().setColorFilter(style.getSettingsIconColor(), PorterDuff.Mode.SRC_IN);
        newMessageIcon.setImageDrawable(drawable);
        newMessageTitle.setTextColor(style.getTextPrimaryColor());
    }
    newMessageView.setOnClickListener(v -> {
        startActivity(Intents.openPrivateDialog(user.getId(), true, getActivity()));
    });
    //
    // Voice Call
    //
    View voiceCallDivider = res.findViewById(R.id.voiceCallDivider);
    View voiceCallView = res.findViewById(R.id.voiceCall);
    if (ActorSDK.sharedActor().isCallsEnabled() && !user.isBot()) {
        ImageView voiceViewIcon = (ImageView) voiceCallView.findViewById(R.id.actionIcon);
        TextView voiceViewTitle = (TextView) voiceCallView.findViewById(R.id.actionText);
        Drawable drawable = getResources().getDrawable(R.drawable.ic_phone_white_24dp);
        drawable.mutate().setColorFilter(style.getSettingsIconColor(), PorterDuff.Mode.SRC_IN);
        voiceViewIcon.setImageDrawable(drawable);
        voiceViewTitle.setTextColor(style.getTextPrimaryColor());
        voiceCallView.setOnClickListener(v -> {
            execute(ActorSDK.sharedActor().getMessenger().doCall(user.getId()));
        });
    } else {
        voiceCallView.setVisibility(View.GONE);
        voiceCallDivider.setVisibility(View.GONE);
    }
    //
    // Video Call
    //
    View videoCallDivider = res.findViewById(R.id.videoCallDivider);
    View videoCallView = res.findViewById(R.id.videoCall);
    if (ActorSDK.sharedActor().isCallsEnabled() && !user.isBot()) {
        ImageView voiceViewIcon = (ImageView) videoCallView.findViewById(R.id.videoCallIcon);
        TextView voiceViewTitle = (TextView) videoCallView.findViewById(R.id.videoCallText);
        Drawable drawable = getResources().getDrawable(R.drawable.ic_videocam_white_24dp);
        drawable.mutate().setColorFilter(style.getSettingsIconColor(), PorterDuff.Mode.SRC_IN);
        voiceViewIcon.setImageDrawable(drawable);
        voiceViewTitle.setTextColor(style.getTextPrimaryColor());
        videoCallView.setOnClickListener(v -> {
            execute(ActorSDK.sharedActor().getMessenger().doVideoCall(user.getId()));
        });
    } else {
        videoCallView.setVisibility(View.GONE);
        videoCallDivider.setVisibility(View.GONE);
    }
    //
    // Contact Information
    //
    final LinearLayout contactsContainer = (LinearLayout) res.findViewById(R.id.contactsContainer);
    String aboutString = user.getAbout().get();
    boolean isFirstContact = aboutString == null || aboutString.isEmpty();
    //
    // About
    //
    bind(user.getAbout(), new ValueChangedListener<String>() {

        private View userAboutRecord;

        @Override
        public void onChanged(final String newUserAbout, Value<String> valueModel) {
            if (newUserAbout != null && newUserAbout.length() > 0) {
                if (userAboutRecord == null) {
                    userAboutRecord = buildRecordBig(newUserAbout, R.drawable.ic_info_outline_black_24dp, true, false, inflater, contactsContainer);
                } else {
                    ((TextView) userAboutRecord.findViewById(R.id.value)).setText(newUserAbout);
                }
                if (recordFieldWithIcon != null) {
                    recordFieldWithIcon.findViewById(R.id.recordIcon).setVisibility(View.INVISIBLE);
                }
            }
        }
    });
    if (!ActorSDK.sharedActor().isOnClientPrivacyEnabled() || user.isInPhoneBook().get()) {
        for (int i = 0; i < phones.size(); i++) {
            final UserPhone userPhone = phones.get(i);
            // Formatting Phone Number
            String _phoneNumber;
            try {
                Phonenumber.PhoneNumber number = PhoneNumberUtil.getInstance().parse("+" + userPhone.getPhone(), "us");
                _phoneNumber = PhoneNumberUtil.getInstance().format(number, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
            } catch (NumberParseException e) {
                e.printStackTrace();
                _phoneNumber = "+" + userPhone.getPhone();
            }
            final String phoneNumber = _phoneNumber;
            String phoneTitle = userPhone.getTitle();
            // Trying to localize this
            if (phoneTitle.toLowerCase().equals("mobile phone")) {
                phoneTitle = getString(R.string.settings_mobile_phone);
            }
            View view = buildRecord(phoneTitle, phoneNumber, R.drawable.ic_import_contacts_black_24dp, isFirstContact, false, inflater, contactsContainer);
            if (isFirstContact) {
                recordFieldWithIcon = view;
            }
            view.setOnClickListener(v -> {
                new AlertDialog.Builder(getActivity()).setItems(new CharSequence[] { getString(R.string.phone_menu_call).replace("{0}", phoneNumber), getString(R.string.phone_menu_sms).replace("{0}", phoneNumber), getString(R.string.phone_menu_share).replace("{0}", phoneNumber), getString(R.string.phone_menu_copy) }, (dialog, which) -> {
                    if (which == 0) {
                        startActivity(new Intent(Intent.ACTION_DIAL).setData(Uri.parse("tel:+" + userPhone.getPhone())));
                    } else if (which == 1) {
                        startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("sms:+" + userPhone.getPhone())));
                    } else if (which == 2) {
                        startActivity(new Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, getString(R.string.settings_share_text).replace("{0}", phoneNumber).replace("{1}", user.getName().get())));
                    } else if (which == 3) {
                        ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clip = ClipData.newPlainText("Phone number", phoneNumber);
                        clipboard.setPrimaryClip(clip);
                        Snackbar.make(res, R.string.toast_phone_copied, Snackbar.LENGTH_SHORT).show();
                    }
                }).show().setCanceledOnTouchOutside(true);
            });
            view.setOnLongClickListener(v -> {
                ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText("Phone number", "+" + userPhone.getPhone());
                clipboard.setPrimaryClip(clip);
                Snackbar.make(res, R.string.toast_phone_copied, Snackbar.LENGTH_SHORT).show();
                return true;
            });
            isFirstContact = false;
        }
        for (int i = 0; i < emails.size(); i++) {
            final UserEmail userEmail = emails.get(i);
            View view = buildRecord(userEmail.getTitle(), userEmail.getEmail(), R.drawable.ic_import_contacts_black_24dp, isFirstContact, false, inflater, contactsContainer);
            if (isFirstContact) {
                recordFieldWithIcon = view;
            }
            view.setOnClickListener(v -> {
                new AlertDialog.Builder(getActivity()).setItems(new CharSequence[] { getString(R.string.email_menu_email).replace("{0}", userEmail.getEmail()), getString(R.string.phone_menu_copy) }, (dialog, which) -> {
                    if (which == 0) {
                        startActivity(new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", userEmail.getEmail(), null)));
                    } else if (which == 1) {
                        ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clip = ClipData.newPlainText("Email", userEmail.getEmail());
                        clipboard.setPrimaryClip(clip);
                        Snackbar.make(res, R.string.toast_email_copied, Snackbar.LENGTH_SHORT).show();
                    }
                }).show().setCanceledOnTouchOutside(true);
            });
            view.setOnLongClickListener(v -> {
                ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText("Email", "+" + userEmail.getEmail());
                clipboard.setPrimaryClip(clip);
                Snackbar.make(res, R.string.toast_email_copied, Snackbar.LENGTH_SHORT).show();
                return true;
            });
            isFirstContact = false;
        }
    }
    //
    // Username
    //
    final boolean finalIsFirstContact = isFirstContact;
    bind(user.getNick(), new ValueChangedListener<String>() {

        private View userNameRecord;

        @Override
        public void onChanged(final String newUserName, Value<String> valueModel) {
            if (newUserName != null && newUserName.length() > 0) {
                if (userNameRecord == null) {
                    userNameRecord = buildRecord(getString(R.string.nickname), "@" + newUserName, R.drawable.ic_import_contacts_black_24dp, finalIsFirstContact, false, inflater, contactsContainer);
                } else {
                    ((TextView) userNameRecord.findViewById(R.id.value)).setText(newUserName);
                }
                userNameRecord.setOnLongClickListener(v -> {
                    ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData clip = ClipData.newPlainText("Username", newUserName);
                    clipboard.setPrimaryClip(clip);
                    Snackbar.make(res, R.string.toast_nickname_copied, Snackbar.LENGTH_SHORT).show();
                    return true;
                });
                if (finalIsFirstContact) {
                    recordFieldWithIcon = userNameRecord;
                }
            }
        }
    });
    //
    // Settings
    //
    {
        //
        // Notifications
        //
        View notificationContainer = res.findViewById(R.id.notificationsCont);
        View notificationPickerContainer = res.findViewById(R.id.notificationsPickerCont);
        ((TextView) notificationContainer.findViewById(R.id.settings_notifications_title)).setTextColor(style.getTextPrimaryColor());
        final SwitchCompat notificationEnable = (SwitchCompat) res.findViewById(R.id.enableNotifications);
        Peer peer = Peer.user(user.getId());
        notificationEnable.setChecked(messenger().isNotificationsEnabled(peer));
        if (messenger().isNotificationsEnabled(peer)) {
            ViewUtils.showView(notificationPickerContainer, false);
        } else {
            ViewUtils.goneView(notificationPickerContainer, false);
        }
        notificationEnable.setOnCheckedChangeListener((buttonView, isChecked) -> {
            messenger().changeNotificationsEnabled(Peer.user(user.getId()), isChecked);
            if (isChecked) {
                ViewUtils.showView(notificationPickerContainer, false);
            } else {
                ViewUtils.goneView(notificationPickerContainer, false);
            }
        });
        notificationContainer.setOnClickListener(v -> notificationEnable.setChecked(!notificationEnable.isChecked()));
        ImageView iconView = (ImageView) res.findViewById(R.id.settings_notification_icon);
        Drawable drawable = DrawableCompat.wrap(getResources().getDrawable(R.drawable.ic_list_black_24dp));
        drawable.mutate();
        DrawableCompat.setTint(drawable, style.getSettingsIconColor());
        iconView.setImageDrawable(drawable);
        ((TextView) notificationPickerContainer.findViewById(R.id.settings_notifications_picker_title)).setTextColor(style.getTextPrimaryColor());
        notificationPickerContainer.setOnClickListener(view -> {
            Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
            intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);
            intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
            intent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
            Uri currentSound = null;
            String defaultPath = null;
            Uri defaultUri = Settings.System.DEFAULT_NOTIFICATION_URI;
            if (defaultUri != null) {
                defaultPath = defaultUri.getPath();
            }
            String path = messenger().getPreferences().getString("userNotificationSound_" + uid);
            if (path == null) {
                path = defaultPath;
            }
            if (path != null && !path.equals("none")) {
                if (path.equals(defaultPath)) {
                    currentSound = defaultUri;
                } else {
                    currentSound = Uri.parse(path);
                }
            }
            intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, currentSound);
            startActivityForResult(intent, SOUND_PICKER_REQUEST_CODE);
        });
        //
        // Block
        //
        View blockContainer = res.findViewById(R.id.blockCont);
        final TextView blockTitle = (TextView) blockContainer.findViewById(R.id.settings_block_title);
        blockTitle.setTextColor(style.getTextPrimaryColor());
        bind(user.getIsBlocked(), (val, valueModel) -> {
            blockTitle.setText(val ? R.string.profile_settings_unblock : R.string.profile_settings_block);
        });
        blockContainer.setOnClickListener(v -> {
            if (!user.getIsBlocked().get()) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setMessage(getString(R.string.profile_settings_block_confirm).replace("{user}", user.getName().get())).setPositiveButton(R.string.dialog_yes, (dialog, which) -> {
                    execute(messenger().blockUser(user.getId()));
                    dialog.dismiss();
                }).setNegativeButton(R.string.dialog_cancel, (dialog, which) -> {
                    dialog.dismiss();
                }).show();
            } else {
                execute(messenger().unblockUser(user.getId()));
            }
        });
        ImageView blockIconView = (ImageView) res.findViewById(R.id.settings_block_icon);
        Drawable blockDrawable = DrawableCompat.wrap(getResources().getDrawable(R.drawable.ic_block_white_24dp));
        drawable.mutate();
        DrawableCompat.setTint(blockDrawable, style.getSettingsIconColor());
        blockIconView.setImageDrawable(blockDrawable);
    }
    //
    // Scroll Coordinate
    //
    final ScrollView scrollView = ((ScrollView) res.findViewById(R.id.scrollContainer));
    scrollView.getViewTreeObserver().addOnScrollChangedListener(() -> updateBar(scrollView.getScrollY()));
    updateBar(scrollView.getScrollY());
    return res;
}
Also used : AlertDialog(android.support.v7.app.AlertDialog) BaseFragment(im.actor.sdk.controllers.BaseFragment) LinearLayout(android.widget.LinearLayout) Bundle(android.os.Bundle) ViewAvatarActivity(im.actor.sdk.controllers.fragment.preview.ViewAvatarActivity) DrawableCompat(android.support.v4.graphics.drawable.DrawableCompat) ActorSDKMessenger.messenger(im.actor.sdk.util.ActorSDKMessenger.messenger) Uri(android.net.Uri) ImageView(android.widget.ImageView) ColorDrawable(android.graphics.drawable.ColorDrawable) Drawable(android.graphics.drawable.Drawable) Screen(im.actor.sdk.util.Screen) ColorStateList(android.content.res.ColorStateList) PhoneNumberUtil(com.google.i18n.phonenumbers.PhoneNumberUtil) ClipboardManager(android.content.ClipboardManager) View(android.view.View) Intents(im.actor.sdk.controllers.Intents) FloatingActionButton(android.support.design.widget.FloatingActionButton) UserPhone(im.actor.core.viewmodel.UserPhone) SwitchCompat(android.support.v7.widget.SwitchCompat) PorterDuff(android.graphics.PorterDuff) AppCompatActivity(android.support.v7.app.AppCompatActivity) ViewGroup(android.view.ViewGroup) StateSet(android.util.StateSet) TextView(android.widget.TextView) UserEmail(im.actor.core.viewmodel.UserEmail) Peer(im.actor.core.entity.Peer) Snackbar(android.support.design.widget.Snackbar) ValueChangedListener(im.actor.runtime.mvvm.ValueChangedListener) Context(android.content.Context) Intent(android.content.Intent) MenuItem(android.view.MenuItem) ArrayList(java.util.ArrayList) ClipData(android.content.ClipData) ViewUtils(im.actor.sdk.util.ViewUtils) MenuInflater(android.view.MenuInflater) Menu(android.view.Menu) AvatarView(im.actor.sdk.view.avatar.AvatarView) Settings(android.provider.Settings) ActionBar(android.support.v7.app.ActionBar) ActorSDK(im.actor.sdk.ActorSDK) ComposeActivity(im.actor.sdk.controllers.compose.ComposeActivity) LayoutInflater(android.view.LayoutInflater) ActorSDKMessenger.users(im.actor.sdk.util.ActorSDKMessenger.users) Color(android.graphics.Color) UserVM(im.actor.core.viewmodel.UserVM) R(im.actor.sdk.R) AlertDialog(android.support.v7.app.AlertDialog) ScrollView(android.widget.ScrollView) RingtoneManager(android.media.RingtoneManager) NumberParseException(com.google.i18n.phonenumbers.NumberParseException) Activity(android.app.Activity) Phonenumber(com.google.i18n.phonenumbers.Phonenumber) Value(im.actor.runtime.mvvm.Value) ColorStateList(android.content.res.ColorStateList) UserEmail(im.actor.core.viewmodel.UserEmail) Uri(android.net.Uri) UserPhone(im.actor.core.viewmodel.UserPhone) FloatingActionButton(android.support.design.widget.FloatingActionButton) TextView(android.widget.TextView) ImageView(android.widget.ImageView) ClipboardManager(android.content.ClipboardManager) Peer(im.actor.core.entity.Peer) ColorDrawable(android.graphics.drawable.ColorDrawable) Drawable(android.graphics.drawable.Drawable) Intent(android.content.Intent) ImageView(android.widget.ImageView) View(android.view.View) TextView(android.widget.TextView) AvatarView(im.actor.sdk.view.avatar.AvatarView) ScrollView(android.widget.ScrollView) UserVM(im.actor.core.viewmodel.UserVM) ScrollView(android.widget.ScrollView) NumberParseException(com.google.i18n.phonenumbers.NumberParseException) ClipData(android.content.ClipData) LinearLayout(android.widget.LinearLayout) Phonenumber(com.google.i18n.phonenumbers.Phonenumber) SwitchCompat(android.support.v7.widget.SwitchCompat)

Example 2 with Phonenumber

use of com.google.i18n.phonenumbers.Phonenumber in project qksms by moezbhatti.

the class PhoneNumberUtils method formatNumber.

/**
     * Format a phone number.
     * <p>
     * If the given number doesn't have the country code, the phone will be
     * formatted to the default country's convention.
     *
     * @param phoneNumber
     *            the number to be formatted.
     * @param defaultCountryIso
     *            the ISO 3166-1 two letters country code whose convention will
     *            be used if the given number doesn't have the country code.
     * @return the formatted number, or null if the given number is not valid.
     *
     */
@SuppressLint("Override")
public static String formatNumber(String phoneNumber, String defaultCountryIso) {
    // Do not attempt to format numbers that start with a hash or star symbol.
    if (phoneNumber.startsWith("#") || phoneNumber.startsWith("*")) {
        return phoneNumber;
    }
    PhoneNumberUtil util = PhoneNumberUtil.getInstance();
    String result = null;
    try {
        Phonenumber.PhoneNumber pn = util.parseAndKeepRawInput(phoneNumber, defaultCountryIso);
        result = util.formatInOriginalFormat(pn, defaultCountryIso);
    } catch (NumberParseException e) {
    }
    return result;
}
Also used : PhoneNumberUtil(com.google.i18n.phonenumbers.PhoneNumberUtil) NumberParseException(com.google.i18n.phonenumbers.NumberParseException) Phonenumber(com.google.i18n.phonenumbers.Phonenumber) SuppressLint(android.annotation.SuppressLint)

Example 3 with Phonenumber

use of com.google.i18n.phonenumbers.Phonenumber in project actor-platform by actorapp.

the class ValidateCodeFragment method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    authType = getArguments().getString("authType");
    isSign = getArguments().getBoolean(AUTH_TYPE_SIGN);
    keyboardHelper = new KeyboardHelper(getActivity());
    View v = inflater.inflate(R.layout.fragment_validate_code, container, false);
    v.setBackgroundColor(ActorSDK.sharedActor().style.getMainBackgroundColor());
    TextView buttonConfirm = (TextView) v.findViewById(R.id.button_confirm_sms_code_text);
    buttonConfirm.setTypeface(Fonts.medium());
    buttonConfirm.setTextColor(ActorSDK.sharedActor().style.getTextPrimaryInvColor());
    StateListDrawable states = SelectorFactory.get(ActorSDK.sharedActor().style.getMainColor(), getActivity());
    buttonConfirm.setBackgroundDrawable(states);
    ((TextView) v.findViewById(R.id.button_edit_phone)).setTypeface(Fonts.medium());
    ((TextView) v.findViewById(R.id.button_edit_phone)).setTextColor(ActorSDK.sharedActor().style.getMainColor());
    TextView sendHint = (TextView) v.findViewById(R.id.sendHint);
    sendHint.setTextColor(ActorSDK.sharedActor().style.getTextSecondaryColor());
    String authId = getArguments().getString("authId", "");
    if (authType.equals(AUTH_TYPE_PHONE)) {
        String phoneNumber = "+" + authId;
        try {
            Phonenumber.PhoneNumber number = PhoneNumberUtil.getInstance().parse(phoneNumber, null);
            phoneNumber = PhoneNumberUtil.getInstance().format(number, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
        } catch (NumberParseException e) {
            e.printStackTrace();
        }
        sendHint.setText(Html.fromHtml(getString(R.string.auth_code_phone_hint).replace("{0}", "<b>" + phoneNumber + "</b>")));
    } else if (authType.equals(AUTH_TYPE_EMAIL)) {
        sendHint.setText(Html.fromHtml(getString(R.string.auth_code_email_hint).replace("{0}", "<b>" + authId + "</b>")));
    }
    codeEnterEditText = (EditText) v.findViewById(R.id.et_sms_code_enter);
    codeEnterEditText.setTextColor(ActorSDK.sharedActor().style.getTextPrimaryColor());
    codeEnterEditText.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        //                if (s.length() == 6) {
        //                    sendCode();
        //                }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });
    codeEnterEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_GO) {
                sendCode();
                return true;
            }
            return false;
        }
    });
    codeEnterEditText.setText(((AuthActivity) getActivity()).getCurrentCode());
    onClick(v, R.id.button_confirm_sms_code, new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            sendCode();
        }
    });
    Button editAuth = (Button) v.findViewById(R.id.button_edit_phone);
    if (authType.equals(AUTH_TYPE_EMAIL)) {
        editAuth.setText(getString(R.string.auth_code_wrong_email));
    }
    onClick(v, R.id.button_edit_phone, new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            new AlertDialog.Builder(getActivity()).setMessage(authType.equals(AUTH_TYPE_EMAIL) ? R.string.auth_code_email_change : R.string.auth_code_phone_change).setPositiveButton(R.string.auth_code_change_yes, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (isSign) {
                        startSignIn();
                    } else {
                        if (authType.equals(AUTH_TYPE_EMAIL)) {
                            switchToEmail();
                        } else if (authType.equals(AUTH_TYPE_PHONE)) {
                            switchToPhone();
                        }
                    }
                }
            }).setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            }).show().setCanceledOnTouchOutside(true);
        }
    });
    v.findViewById(R.id.divider).setBackgroundColor(style.getDividerColor());
    return v;
}
Also used : DialogInterface(android.content.DialogInterface) StateListDrawable(android.graphics.drawable.StateListDrawable) TextView(android.widget.TextView) View(android.view.View) KeyEvent(android.view.KeyEvent) Button(android.widget.Button) NumberParseException(com.google.i18n.phonenumbers.NumberParseException) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) TextView(android.widget.TextView) KeyboardHelper(im.actor.sdk.util.KeyboardHelper) Phonenumber(com.google.i18n.phonenumbers.Phonenumber)

Example 4 with Phonenumber

use of com.google.i18n.phonenumbers.Phonenumber in project actor-platform by actorapp.

the class AndroidPhoneBook method loadPhoneBook.

public static ArrayList<PhoneBookContact> loadPhoneBook(Context context, String isoCountry) {
    if (DISABLE_PHONE_BOOK) {
        return new ArrayList<>();
    }
    Log.d(TAG, "Loading phone book");
    long start = SystemClock.uptimeMillis();
    HashSet<Long> addedPhones = new HashSet<>();
    HashSet<String> addedEmails = new HashSet<>();
    ArrayList<PhoneBookContact> records = new ArrayList<>();
    HashMap<Long, PhoneBookContact> recordsMap = new HashMap<>();
    ContentResolver cr = context.getContentResolver();
    if (cr == null) {
        return new ArrayList<>();
    }
    //Check have permission for this
    if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_CONTACTS) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
        Log.d("Permissions", "contacts - no permission :c");
        return new ArrayList<>();
    }
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME }, null, null, ContactsContract.Contacts.SORT_KEY_PRIMARY);
    if (cur == null) {
        return new ArrayList<>();
    }
    int idIndex = cur.getColumnIndex(ContactsContract.Contacts._ID);
    int nameIndex = cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
    int index = 0;
    while (cur.moveToNext()) {
        if (index++ == READ_ITEM_DELAY_BATCH) {
            if (READ_ITEM_DELAY > 0) {
                try {
                    Thread.sleep(READ_ITEM_DELAY);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        long id = cur.getLong(idIndex);
        String name = cur.getString(nameIndex);
        if (name == null || name.trim().length() == 0)
            continue;
        PhoneBookContact record = new PhoneBookContact(id, name.trim(), new ArrayList<>(), new ArrayList<>());
        records.add(record);
        recordsMap.put(id, record);
    }
    cur.close();
    cur = null;
    // Loading phones
    cur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[] { ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.CONTACT_ID, ContactsContract.CommonDataKinds.Phone.NUMBER }, null, null, ContactsContract.CommonDataKinds.Phone._ID + " desc");
    if (cur == null) {
        return new ArrayList<>();
    }
    final int idContactIndex = cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
    final int idPhoneIndex = cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID);
    final int idNumberIndex = cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
    while (cur.moveToNext()) {
        if (index++ == READ_ITEM_DELAY_BATCH) {
            if (READ_ITEM_DELAY > 0) {
                try {
                    Thread.sleep(READ_ITEM_DELAY);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        long contactId = cur.getLong(idContactIndex);
        long phoneId = cur.getLong(idPhoneIndex);
        String rawPhone = cur.getString(idNumberIndex);
        PhoneBookContact record = recordsMap.get(contactId);
        if (record == null || rawPhone == null) {
            continue;
        }
        if (PHONE_UTIL == null) {
            synchronized (initSync) {
                if (PHONE_UTIL == null) {
                    PHONE_UTIL = PhoneNumberUtil.getInstance();
                }
            }
        }
        try {
            final Phonenumber.PhoneNumber phonenumber = PHONE_UTIL.parse(rawPhone, isoCountry);
            rawPhone = phonenumber.getCountryCode() + "" + phonenumber.getNationalNumber();
        } catch (final NumberParseException e) {
            rawPhone = rawPhone.replaceAll("[^\\d]", "");
        }
        long phone = -1;
        try {
            phone = Long.parseLong(rawPhone);
        } catch (Exception e) {
            // Logger.d(TAG, "Can't parse number", e);
            continue;
        }
        if (addedPhones.contains(phone)) {
            continue;
        }
        addedPhones.add(phone);
        record.getPhones().add(new PhoneBookPhone(phoneId, phone));
    }
    cur.close();
    cur = null;
    // Loading emails
    cur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, new String[] { ContactsContract.CommonDataKinds.Email._ID, ContactsContract.CommonDataKinds.Email.CONTACT_ID, ContactsContract.CommonDataKinds.Email.ADDRESS }, null, null, ContactsContract.CommonDataKinds.Email._ID + " desc");
    if (cur == null) {
        return new ArrayList<PhoneBookContact>();
    }
    final int idEmailContactIndex = cur.getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID);
    final int idEmailIdIndex = cur.getColumnIndex(ContactsContract.CommonDataKinds.Email._ID);
    final int idEmailIndex = cur.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS);
    while (cur.moveToNext()) {
        if (index++ == READ_ITEM_DELAY_BATCH) {
            if (READ_ITEM_DELAY > 0) {
                try {
                    Thread.sleep(READ_ITEM_DELAY);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        long contactId = cur.getLong(idEmailContactIndex);
        long emailId = cur.getLong(idEmailIdIndex);
        String rawEmail = cur.getString(idEmailIndex);
        PhoneBookContact record = recordsMap.get(contactId);
        if (record == null) {
            continue;
        }
        if (rawEmail == null) {
            continue;
        }
        rawEmail = rawEmail.toLowerCase();
        if (addedEmails.contains(rawEmail)) {
            continue;
        }
        addedEmails.add(rawEmail);
        record.getEmails().add(new PhoneBookEmail(emailId, rawEmail));
    }
    cur.close();
    // Filtering records without contacts
    ArrayList<PhoneBookContact> res = new ArrayList<>();
    for (PhoneBookContact rec : records) {
        if (rec.getPhones().size() > 0 || rec.getEmails().size() > 0) {
            res.add(rec);
        }
    }
    Log.d(TAG, "Phone book loaded in " + (SystemClock.uptimeMillis() - start) + " ms in " + (index) + " iterations");
    return res;
}
Also used : PhoneBookContact(im.actor.core.entity.PhoneBookContact) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) NumberParseException(com.google.i18n.phonenumbers.NumberParseException) ContentResolver(android.content.ContentResolver) PhoneBookPhone(im.actor.core.entity.PhoneBookPhone) NumberParseException(com.google.i18n.phonenumbers.NumberParseException) PhoneBookEmail(im.actor.core.entity.PhoneBookEmail) Phonenumber(com.google.i18n.phonenumbers.Phonenumber) HashSet(java.util.HashSet)

Example 5 with Phonenumber

use of com.google.i18n.phonenumbers.Phonenumber in project qksms by moezbhatti.

the class PhoneNumberUtils method formatNumberToE164.

/**
     * Format the given phoneNumber to the E.164 representation.
     * <p>
     * The given phone number must have an area code and could have a country
     * code.
     * <p>
     * The defaultCountryIso is used to validate the given number and generate
     * the E.164 phone number if the given number doesn't have a country code.
     *
     * @param phoneNumber
     *            the phone number to format
     * @param defaultCountryIso
     *            the ISO 3166-1 two letters country code
     * @return the E.164 representation, or null if the given phone number is
     *         not valid.
     *
     */
@SuppressLint("Override")
public static String formatNumberToE164(String phoneNumber, String defaultCountryIso) {
    PhoneNumberUtil util = PhoneNumberUtil.getInstance();
    String result = null;
    try {
        Phonenumber.PhoneNumber pn = util.parse(phoneNumber, defaultCountryIso);
        if (util.isValidNumber(pn)) {
            result = util.format(pn, PhoneNumberUtil.PhoneNumberFormat.E164);
        }
    } catch (NumberParseException e) {
    }
    return result;
}
Also used : PhoneNumberUtil(com.google.i18n.phonenumbers.PhoneNumberUtil) NumberParseException(com.google.i18n.phonenumbers.NumberParseException) Phonenumber(com.google.i18n.phonenumbers.Phonenumber) SuppressLint(android.annotation.SuppressLint)

Aggregations

NumberParseException (com.google.i18n.phonenumbers.NumberParseException)5 Phonenumber (com.google.i18n.phonenumbers.Phonenumber)5 PhoneNumberUtil (com.google.i18n.phonenumbers.PhoneNumberUtil)3 SuppressLint (android.annotation.SuppressLint)2 View (android.view.View)2 TextView (android.widget.TextView)2 Activity (android.app.Activity)1 ClipData (android.content.ClipData)1 ClipboardManager (android.content.ClipboardManager)1 ContentResolver (android.content.ContentResolver)1 Context (android.content.Context)1 DialogInterface (android.content.DialogInterface)1 Intent (android.content.Intent)1 ColorStateList (android.content.res.ColorStateList)1 Cursor (android.database.Cursor)1 Color (android.graphics.Color)1 PorterDuff (android.graphics.PorterDuff)1 ColorDrawable (android.graphics.drawable.ColorDrawable)1 Drawable (android.graphics.drawable.Drawable)1 StateListDrawable (android.graphics.drawable.StateListDrawable)1