<pre name="code" class="java">package com.example.phonenumber;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
public class MainActivity extends Activity {
Button verifyb = null;
TextView result = null;
Context mcontext = null;
public boolean isPhoneNumberValid(String phoneNumber)
{
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
String countryCode = Locale.getDefault().getCountry();
try
{
PhoneNumber numberProto = phoneUtil.parse(phoneNumber, countryCode);
return phoneUtil.isValidNumber(numberProto);
}
catch (NumberParseException e)
{
System.err.println("NumberParseException was thrown: " + e.toString());
}
return false;
}
public static boolean isPhoneNumberValid2(String phoneNumber) {
boolean isValid = false;
/*
* 可接受的电话格式有:
*/
String expression = "(\\+[0-9]+[\\- \\.]*)?"
+ "(\\([0-9]+\\)[\\- \\.]*)?"
+ "([0-9][0-9\\- \\.][0-9\\- \\.]+[0-9])";
CharSequence inputStr = phoneNumber;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
if(matcher.matches() ) {
isValid = true;
}
return isValid;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mcontext = this;
setContentView(R.layout.activity_main);
result = (TextView)findViewById(R.id.result);
verifyb = (Button)findViewById(R.id.verifb);
verifyb.setOnClickListener(new Button.OnClickListener(){//创建监听
public void onClick(View v) {
//用EditText前,请先:import android.widget.EditText;
//获取文本框1的文本
String str1="";
EditText editText1 =(EditText)findViewById(R.id.phonenumber);
str1=editText1.getText().toString();
//boolean varid = PhoneNumberUtils.isGlobalPhoneNumber(str1);
//boolean varid = isPhoneNumberValid(str1);
boolean varid = isPhoneNumberValid2(str1);
if(varid){
str1 = "true";
}else{
str1 = "false";
}
result.setText(str1);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
参考资料:
https://github.com/googlei18n/libphonenumber/blob/master/README.md
http://www.programcreek.com/java-api-examples/index.php?api=com.android.i18n.phonenumbers.PhoneNumberUtil
http://www.itstrike.cn/Question/690f4f22-2c59-4dfe-99aa-30e5c4514322.html
https://github.com/googlei18n/libphonenumber
http://www.tuicool.com/articles/iMVn2e
http://stackoverflow.com/questions/6358380/phone-number-validation-android
http://www.javased.com/index.php?source_dir=android_external_libphonenumber/java/src/com/android/i18n/phonenumbers/PhoneNumberUtil.java