类android.util.Patterns源码实例Demo

下面列出了怎么用android.util.Patterns的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: evercam-android   文件: AccountUtils.java
/**
 * Retrieves the user profile information in a manner supported by
 * Gingerbread devices.
 *
 * @param context the context from which to retrieve the user's email address
 *                and name
 * @return a list of the possible user's email address and name
 */

private static UserProfile getUserProfileOnGingerbreadDevice(Context context) {
    // Other that using Patterns (API level 8) this works on devices down to
    // API level 5
    final Matcher valid_email_address = Patterns.EMAIL_ADDRESS.matcher("");
    final Account[] accounts = AccountManager.get(context).getAccountsByType(GoogleAuthUtil
            .GOOGLE_ACCOUNT_TYPE);
    UserProfile user_profile = new UserProfile();
    // As far as I can tell, there is no way to get the real name or phone
    // number from the Google account
    for (Account account : accounts) {
        if (valid_email_address.reset(account.name).matches())
            user_profile.addPossibleEmail(account.name);
    }
    // Gets the phone number of the device is the device has one
    if (context.getPackageManager().hasSystemFeature(Context.TELEPHONY_SERVICE)) {
        final TelephonyManager telephony = (TelephonyManager) context.getSystemService
                (Context.TELEPHONY_SERVICE);
        user_profile.addPossiblePhoneNumber(telephony.getLine1Number());
    }

    return user_profile;
}
 
源代码2 项目: mobikul-standalone-pos   文件: Customer.java
@Bindable
public String getEmail() {
    if (email == null) {
        return "";
    } else if (Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
        Log.d(TAG, "getEmail: " + getCustomerId());
        DataBaseController.getInstanse().checkEmailExist(getContext(), email, new DataBaseCallBack() {
            @Override
            public void onSuccess(Object responseData, String successMsg) {
                if (((Customer) responseData) != null && ((Customer) responseData).getCustomerId() != getCustomerId()) {
                    isEmailExist = true;
                } else {
                    isEmailExist = false;
                }
                Log.d(TAG, "onSuccess: " + responseData);
            }

            @Override
            public void onFailure(int errorCode, String errorMsg) {
                isEmailExist = false;
            }
        });
    }
    return email;
}
 
源代码3 项目: Android-Tutorials   文件: LoginCredentials.java
public boolean isValid() {
    if (TextUtils.isEmpty(username)) {
        return false;
    }

    if (!Patterns.EMAIL_ADDRESS.matcher(username).matches()) {
        return false;
    }

    if (TextUtils.isEmpty(password)) {
        return false;
    }

    if (password.length() < 5) {
        return false;
    }

    return true;
}
 
源代码4 项目: Android-Tutorials   文件: LoginInteractor.java
private boolean hasError(LoginCredentials loginCredentials) {
    String username = loginCredentials.getUsername();
    String password = loginCredentials.getPassword();

    if (TextUtils.isEmpty(username)) {
        loginListener.onFailed("The email is empty");
        return true;
    }

    if (!Patterns.EMAIL_ADDRESS.matcher(username).matches()) {
        loginListener.onFailed("The email is invalid");
        return true;
    }

    if (TextUtils.isEmpty(password)) {
        loginListener.onFailed("The password is empty");
        return true;
    }

    if (password.length() < 5) {
        loginListener.onFailed("Password is weak");
        return true;
    }

    return false;
}
 
源代码5 项目: tindroid   文件: UiUtils.java
static Credential parseCredential(String cred) {
    final PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
    final String country = Locale.getDefault().getCountry();
    if (Patterns.PHONE.matcher(cred).matches()) {
        // Looks like a phone number.
        try {
            // Normalize phone number format
            cred = phoneUtil.format(phoneUtil.parse(cred, country), PhoneNumberUtil.PhoneNumberFormat.E164);
            // Exception not thrown, we have a phone number.
            return new Credential(Credential.METH_PHONE, cred);
        } catch (NumberParseException ignored) {
            return null;
        }
    }

    // Not a phone number. Try parsing as email.
    if (Patterns.EMAIL_ADDRESS.matcher(cred).matches()) {
        return new Credential(Credential.METH_EMAIL, cred);
    }

    return null;
}
 
@Override
protected void onResume() {
    super.onResume();

    Core core = LinphoneManager.getCore();
    if (core != null) {
        reloadLinphoneAccountCreatorConfig();
    }

    getAccountCreator().addListener(mListener);

    if (getResources().getBoolean(R.bool.pre_fill_email_in_assistant)) {
        Account[] accounts = AccountManager.get(this).getAccountsByType("com.google");
        for (Account account : accounts) {
            if (Patterns.EMAIL_ADDRESS.matcher(account.name).matches()) {
                String possibleEmail = account.name;
                mEmail.setText(possibleEmail);
                break;
            }
        }
    }
}
 
源代码7 项目: Android-RTEditor   文件: ConverterTextToHtml.java
private static void linkifyText(final String text, final StringBuffer outputBuffer) {
    String prepared = replaceAll(text, BITCOIN_URI_PATTERN, "<a href=\"$0\">$0</a>");
    Matcher m = Patterns.WEB_URL.matcher(prepared);
    while (m.find()) {
        int start = m.start();
        if (start == 0 || (start != 0 && text.charAt(start - 1) != '@')) {
            if (m.group().indexOf(':') > 0) { // With no URI-schema we may get "http:/" links with the second / missing
                m.appendReplacement(outputBuffer, "<a href=\"$0\">$0</a>");
            } else {
                m.appendReplacement(outputBuffer, "<a href=\"http://$0\">$0</a>");
            }
        } else {
            m.appendReplacement(outputBuffer, "$0");
        }
    }
    m.appendTail(outputBuffer);
}
 
源代码8 项目: SABS   文件: ContentBlocker57.java
@Override
public boolean enableBlocker() {
    //contentBlocker56.setUrlBlockLimit(15_000);
    if (contentBlocker56.enableBlocker()) {
        SharedPreferences sharedPreferences = App.get().getApplicationContext().getSharedPreferences("dnsAddresses", Context.MODE_PRIVATE);
        if (sharedPreferences.contains("dns1") && sharedPreferences.contains("dns2")) {
            String dns1 = sharedPreferences.getString("dns1", null);
            String dns2 = sharedPreferences.getString("dns2", null);
            if (dns1 != null && dns2 != null
                    && Patterns.IP_ADDRESS.matcher(dns1).matches()
                    && Patterns.IP_ADDRESS.matcher(dns2).matches()) {
                this.setDns(dns1, dns2);
            }
            Log.d(TAG, "Previous dns addresses has been applied. " + dns1 + " " + dns2);
        }
        return true;
    }
    return false;
}
 
源代码9 项目: aard2-android   文件: MainActivity.java
@Override
public void onWindowFocusChanged(boolean hasFocus) {
    ClipboardManager cm = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
    ClipData clipData = cm.getPrimaryClip();
    if (clipData == null) {
        return;
    }
    int count = clipData.getItemCount();
    for (int i = 0; i < count; i++) {
        ClipData.Item item = clipData.getItemAt(i);
        CharSequence text = item.getText();
        if (text != null && text.length() > 0) {
            if (Patterns.WEB_URL.matcher(text).find()) {
                Log.d(TAG, "Text contains web url, not pasting: " + text);
                return;
            }
            viewPager.setCurrentItem(0);
            cm.setPrimaryClip(ClipData.newPlainText(null, ""));
            appSectionsPagerAdapter.tabLookup.setQuery(text.toString());
            break;
        }
    }
}
 
源代码10 项目: o2oa   文件: AndroidShareDialog.java
public AndroidShareDialog(Context context, int theme, String msgText, final String imgUri) {
    super(context, theme);
    this.msgText = msgText;

    if(TextUtils.isEmpty(imgUri)){
        this.mImgPath = null;// getAppLauncherPath();
    }else{
        if (Patterns.WEB_URL.matcher(imgUri).matches()) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        mImgPath = getImagePath(imgUri, getFileCache());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } else {
            this.mImgPath = imgUri;
        }
    }
}
 
源代码11 项目: XERUNG   文件: VerifyOTP.java
private ArrayList<String> getUserEmail(){

		ArrayList<String> email = new ArrayList<String>();

		Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
		Account[] accounts = AccountManager.get(VerifyOTP.this).getAccounts();
		for (Account account : accounts) {
			if (emailPattern.matcher(account.name).matches()) {
				String possibleEmail = account.name;
				if(possibleEmail != null)
					if(possibleEmail.length() !=0 ){
						email.add(possibleEmail);
					}
			}
		}		
		return email;

	}
 
源代码12 项目: XERUNG   文件: VerifyOTP.java
private ArrayList<String> getUserEmail(){

		ArrayList<String> email = new ArrayList<String>();

		Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
		Account[] accounts = AccountManager.get(VerifyOTP.this).getAccounts();
		for (Account account : accounts) {
			if (emailPattern.matcher(account.name).matches()) {
				String possibleEmail = account.name;
				if(possibleEmail != null)
					if(possibleEmail.length() !=0 ){
						email.add(possibleEmail);
					}
			}
		}		
		return email;

	}
 
源代码13 项目: argus-android   文件: EmailSignupProvider.java
@Override
protected View inflateView(ViewGroup parentView) {
    if (context != null) {
        getValidationEngine()
                .addEmailValidation(new RegexValidation(Patterns.EMAIL_ADDRESS.pattern(),
                        context.getString(
                                R.string.invalid_email)));
    }

    View signUpView = LayoutInflater.from(context)
            .inflate(R.layout.signup_email, parentView, false);
    usernameEt = (EditText) signUpView.findViewById(R.id.username);
    emailEt = (EditText) signUpView.findViewById(R.id.email);
    passwordEt = (EditText) signUpView.findViewById(R.id.password);
    welcomeTv = (TextView) signUpView.findViewById(R.id.tv_welcome_text);

    theme = Argus.getInstance().getArgusTheme();

    themeHelper.applyTheme(signUpView, theme);
    return signUpView;
}
 
源代码14 项目: android-proguards   文件: DesignerNewsLogin.java
@SuppressLint("NewApi")
private void setupAccountAutocomplete() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS) ==
            PackageManager.PERMISSION_GRANTED) {
        permissionPrimer.setVisibility(View.GONE);
        final Account[] accounts = AccountManager.get(this).getAccounts();
        final Set<String> emailSet = new HashSet<>();
        for (Account account : accounts) {
            if (Patterns.EMAIL_ADDRESS.matcher(account.name).matches()) {
                emailSet.add(account.name);
            }
        }
        username.setAdapter(new ArrayAdapter<>(this,
                R.layout.account_dropdown_item, new ArrayList<>(emailSet)));
    } else {
        if (shouldShowRequestPermissionRationale(Manifest.permission.GET_ACCOUNTS)) {
            setupPermissionPrimer();
        } else {
            permissionPrimer.setVisibility(View.GONE);
            shouldPromptForPermission = true;
        }
    }
}
 
源代码15 项目: SendBird-Android   文件: WebUtils.java
/**
 * Extract urls from string.
 * @param input
 * @return
 */
public static List<String> extractUrls(String input)
{
    List<String> result = new ArrayList<String>();

    String[] words = input.split("\\s+");


    Pattern pattern = Patterns.WEB_URL;
    for(String word : words)
    {
        if(pattern.matcher(word).find())
        {
            if(!word.toLowerCase().contains("http://") && !word.toLowerCase().contains("https://"))
            {
                word = "http://" + word;
            }
            result.add(word);
        }
    }

    return result;
}
 
源代码16 项目: memoir   文件: ConverterTextToHtml.java
private static void linkifyText(final String text, final StringBuffer outputBuffer) {
    String prepared = replaceAll(text, BITCOIN_URI_PATTERN, "<a href=\"$0\">$0</a>");
    Matcher m = Patterns.WEB_URL.matcher(prepared);
    while (m.find()) {
        int start = m.start();
        if (start == 0 || (start != 0 && text.charAt(start - 1) != '@')) {
            if (m.group().indexOf(':') > 0) { // With no URI-schema we may get "http:/" links with the second / missing
                m.appendReplacement(outputBuffer, "<a href=\"$0\">$0</a>");
            } else {
                m.appendReplacement(outputBuffer, "<a href=\"http://$0\">$0</a>");
            }
        } else {
            m.appendReplacement(outputBuffer, "$0");
        }
    }
    m.appendTail(outputBuffer);
}
 
@Override
public boolean onSingleTapConfirmed(MotionEvent event) {
    final String linkText = getLinkText(tex, spannable, event);
    LinkType linkType = LinkType.NONE;

    if (Patterns.PHONE.matcher(linkText).matches()) {
        linkType = LinkType.PHONE;
    } else if (Patterns.WEB_URL.matcher(linkText).matches()) {
        linkType = LinkType.WEB_URL;
    } else if (Patterns.EMAIL_ADDRESS.matcher(linkText).matches()) {
        linkType = LinkType.EMAIL_ADDRESS;
    }

    if (listener != null) {
        listener.onLinkClicked(linkText, linkType);
    }

    return false;
}
 
源代码18 项目: candybar   文件: UrlHelper.java
public static Type getType(String url) {
    if (url == null) return Type.INVALID;
    if (!URLUtil.isValidUrl(url)) {
        if (Patterns.EMAIL_ADDRESS.matcher(url).matches()) {
            return Type.EMAIL;
        }
        return Type.INVALID;
    }

    if (url.contains("behance.")) {
        return Type.BEHANCE;
    } else if (url.contains("dribbble.")) {
        return Type.DRIBBBLE;
    } else if (url.contains("facebook.")) {
        return Type.FACEBOOK;
    } else if (url.contains("github.")) {
        return Type.GITHUB;
    } else if (url.contains("instagram.")) {
        return Type.INSTAGRAM;
    } else if (url.contains("pinterest.")) {
        return Type.PINTEREST;
    } else if (url.contains("twitter.")) {
        return Type.TWITTER;
    } else if (url.contains("t.me/") || url.contains("telegram.me/")) {
        return Type.TELEGRAM;
    } else {
        return Type.UNKNOWN;
    }
}
 
源代码19 项目: LB-Launcher   文件: AutoInstallsLayout.java
protected Intent parseIntent(XmlResourceParser parser) {
    final String url = getAttributeValue(parser, ATTR_URL);
    if (TextUtils.isEmpty(url) || !Patterns.WEB_URL.matcher(url).matches()) {
        if (LOGD) Log.d(TAG, "Ignoring shortcut, invalid url: " + url);
        return null;
    }
    return new Intent(Intent.ACTION_VIEW, null).setData(Uri.parse(url));
}
 
源代码20 项目: JumpGo   文件: UrlUtils.java
/**
 * Attempts to determine whether user input is a URL or search
 * terms.  Anything with a space is passed to search if canBeSearch is true.
 * <p/>
 * Converts to lowercase any mistakenly uppercased schema (i.e.,
 * "Http://" converts to "http://"
 *
 * @param canBeSearch If true, will return a search url if it isn't a valid
 *                    URL. If false, invalid URLs will return null
 * @return Original or modified URL
 */
@NonNull
public static String smartUrlFilter(@NonNull String url, boolean canBeSearch, String searchUrl) {
    String inUrl = url.trim();
    boolean hasSpace = inUrl.indexOf(' ') != -1;
    Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
    if (matcher.matches()) {
        // force scheme to lowercase
        String scheme = matcher.group(1);
        String lcScheme = scheme.toLowerCase();
        if (!lcScheme.equals(scheme)) {
            inUrl = lcScheme + matcher.group(2);
        }
        if (hasSpace && Patterns.WEB_URL.matcher(inUrl).matches()) {
            inUrl = inUrl.replace(" ", "%20");
        }
        return inUrl;
    }
    if (!hasSpace) {
        if (Patterns.WEB_URL.matcher(inUrl).matches()) {
            return URLUtil.guessUrl(inUrl);
        }
    }
    if (canBeSearch) {
        return URLUtil.composeSearchUrl(inUrl,
            searchUrl, QUERY_PLACE_HOLDER);
    }
    return "";
}
 
源代码21 项目: zulip-android   文件: LoginActivity.java
private boolean isInputValid() {
    boolean isValid = true;

    if (mPassword.length() == 0) {
        isValid = false;
        mPassword.setError(getString(R.string.password_required));
    }

    if (mUserName.length() == 0) {
        isValid = false;
        mUserName.setError(getString(R.string.username_required));
    }

    if (mServerEditText.length() == 0) {
        isValid = false;
        mServerEditText.setError(getString(R.string.server_domain_required));
    } else {
        String serverString = mServerEditText.getText().toString();
        if (!serverString.contains("://")) {
            serverString = "https://" + serverString;
        }

        if (!Patterns.WEB_URL.matcher(serverString).matches()) {
            mServerEditText.setError(getString(R.string.invalid_domain));
            isValid = false;
        }
    }
    return isValid;
}
 
源代码22 项目: physical-web   文件: BroadcastActivity.java
private String findUrlInText(String text) {
    List<String> urls = new ArrayList<>();
    Matcher m = Patterns.WEB_URL.matcher(text);
    while (m.find()) {
        String url = m.group();
        urls.add(url);
    }
    if (urls.size() > 0) {
        return urls.get(0);
    }
    return null;
}
 
源代码23 项目: sharelock-android   文件: SettingsActivity.java
@Override
protected void onStop() {
    super.onStop();
    final String urlString = endpointEditText.getText().toString();
    if (Patterns.WEB_URL.matcher(urlString).matches()) {
        SharedPreferences preferences = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
        preferences.edit()
                .putString(LinkAPIClient.SHARELOCK_ENDPOINT_KEY, urlString)
                .apply();
    }
}
 
源代码24 项目: zulip-android   文件: LoginActivity.java
private boolean isUrlValid(String url) {
    if (BuildConfig.DEBUG) {
        return Patterns.WEB_URL.matcher(String.valueOf(url)).matches() ||
                Patterns.IP_ADDRESS.matcher(url).matches();
    } else {
        return Patterns.WEB_URL.matcher(String.valueOf(url)).matches();
    }
}
 
源代码25 项目: android-chromium   文件: IntentHelper.java
/**
 * Triggers a send email intent.  If no application has registered to receive these intents,
 * this will fail silently.
 *
 * @param context The context for issuing the intent.
 * @param email The email address to send to.
 * @param subject The subject of the email.
 * @param body The body of the email.
 * @param chooserTitle The title of the activity chooser.
 * @param fileToAttach The file name of the attachment.
 */
@CalledByNative
static void sendEmail(Context context, String email, String subject, String body,
        String chooserTitle, String fileToAttach) {
    Set<String> possibleEmails = new HashSet<String>();

    if (!TextUtils.isEmpty(email)) {
        possibleEmails.add(email);
    } else {
        Pattern emailPattern = Patterns.EMAIL_ADDRESS;
        Account[] accounts = AccountManager.get(context).getAccounts();
        for (Account account : accounts) {
            if (emailPattern.matcher(account.name).matches()) {
                possibleEmails.add(account.name);
            }
        }
    }

    Intent send = new Intent(Intent.ACTION_SEND);
    send.setType("message/rfc822");
    if (possibleEmails.size() != 0) {
        send.putExtra(Intent.EXTRA_EMAIL,
                possibleEmails.toArray(new String[possibleEmails.size()]));
    }
    send.putExtra(Intent.EXTRA_SUBJECT, subject);
    send.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(body));
    if (!TextUtils.isEmpty(fileToAttach)) {
        File fileIn = new File(fileToAttach);
        send.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(fileIn));
    }

    try {
        Intent chooser = Intent.createChooser(send, chooserTitle);
        // we start this activity outside the main activity.
        chooser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(chooser);
    } catch (android.content.ActivityNotFoundException ex) {
        // If no app handles it, do nothing.
    }
}
 
源代码26 项目: comfortreader   文件: BroadcastReceiverWebLink.java
private boolean isValid(String urlString) {
    try {
        URL url = new URL(urlString);
        return URLUtil.isValidUrl(urlString) && Patterns.WEB_URL.matcher(urlString).matches();
    } catch (MalformedURLException e) {

    }

    return false;
}
 
源代码27 项目: Beedio   文件: WebConnect.java
public void connect() {
    String text = textBox.getText().toString();
    if (Patterns.WEB_URL.matcher(text).matches()) {
        if (!text.startsWith("http")) {
            text = "http://" + text;
        }
        activity.getBrowserManager().newWindow(text);
    } else {
        text = "https://google.com/search?q=" + text;
        activity.getBrowserManager().newWindow(text);
    }
}
 
源代码28 项目: EmailAutoCompleteTextView   文件: AccountUtil.java
/**
 * Returns true if the given string is an email.
 */
private static boolean isEmail(String account) {

    if (TextUtils.isEmpty(account)) {
        return false;
    }

    final Pattern emailPattern = Patterns.EMAIL_ADDRESS;
    final Matcher matcher = emailPattern.matcher(account);
    return matcher.matches();
}
 
源代码29 项目: attendee-checkin   文件: CheckinHolder.java
@Override
public void bind(Checkin checkin, ImageLoader imageLoader) {
    mName.setText(checkin.getAttendeeName());
    Context context = mDescription.getContext();
    long timestamp = checkin.getTimestamp();
    if (System.currentTimeMillis() - timestamp * 1000 < 60 * 1000) {
        mDescription.setText(R.string.just_now);
    } else {
        mDescription.setText(
                DateUtils.getRelativeDateTimeString(context, timestamp * 1000,
                        DateUtils.MINUTE_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, 0));
    }
    // Load the icon
    ImageLoader.ImageContainer container = (ImageLoader.ImageContainer) mIcon.getTag();
    if (container != null) {
        container.cancelRequest();
    }
    String imageUrl = checkin.getAttendeeImageUrl();
    if (!TextUtils.isEmpty(imageUrl) && Patterns.WEB_URL.matcher(imageUrl).matches()) {
        mIcon.setTag(imageLoader.get(imageUrl,
                new RoundedImageListener(mIcon, R.drawable.ic_person,
                        R.drawable.ic_person)));
    } else {
        mIcon.setImageResource(R.drawable.ic_person);
    }
    if (mWillAnimate && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mCheckin.setImageResource(R.drawable.checkin_anim);
    } else {
        mCheckin.setImageResource(R.drawable.checkin);
    }
}
 
源代码30 项目: green_android   文件: Socks5SocketFactory.java
InetAddress getDirectInetAddress() throws IOException {
    if (mTarget != null) {
        final String hn = mTarget.getHostName();
        if (hn != null && Patterns.IP_ADDRESS.matcher(hn).matches())
            return InetAddress.getByName(hn);
    }
    throw new IOException();
}