我们都知道每个手机号码,都应该有这样的属性:号码、归属地、运营商等。本文将利用阿里提供的开放接口来获取手机号码的归属地。这个工程也简单地运用了mvp的风格来构建工程结构。(点击:工程地址(码云git) 可以下载或查看工程源码)
java
res
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/darker_gray"
android:gravity="center_vertical"
android:orientation="vertical"
tools:context="com.exmple.phonesearch.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:padding="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="手机号码归属地查询"
android:textColor="#ffffff"
android:textSize="14sp" />
RelativeLayout>
<EditText
android:id="@+id/et_phone_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:background="@android:color/background_light"
android:hint="11位手机号"
android:inputType="phone"
android:maxLength="11"
android:maxLines="1" />
<Button
android:id="@+id/btn_search"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:background="@color/colorPrimary"
android:text="查 询"
android:textColor="#ffffff"
android:textSize="18sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp"
android:gravity="center_vertical"
android:orientation="vertical"
android:background="@android:color/background_light">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp">
<TextView
android:id="@+id/tv_phone_num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="40dp"
android:text="手机号:" />
RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp">
<TextView
android:id="@+id/tv_province"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:text="省份:"
android:layout_centerVertical="true"/>
RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp">
<TextView
android:id="@+id/tv_catName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="40dp"
android:text="运营商:" />
RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp">
<TextView
android:id="@+id/tv_carrier"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="40dp"
android:text="运营者:" />
RelativeLayout>
LinearLayout>
LinearLayout>
MainActivity.java
package com.exmple.phonesearch;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.exmple.phonesearch.model.Phone;
import com.exmple.phonesearch.mvp.MvpMainView;
import com.exmple.phonesearch.mvp.impl.MainPresenter;
import com.exmple.phonesearch.view.LoadingDialog;
public class MainActivity extends AppCompatActivity implements View.OnClickListener,MvpMainView{
private EditText mEtPhoneInput;
private Button mBtnSearch;
private TextView mTvProvince;
private TextView mTvCatName;
private TextView mTvCarrier;
private TextView mTvPhoneNum;
private MainPresenter mainPresenter;
private LoadingDialog loadingDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEtPhoneInput = (EditText) findViewById(R.id.et_phone_input);
mBtnSearch = (Button) findViewById(R.id.btn_search);
mTvPhoneNum = (TextView) findViewById(R.id.tv_phone_num);
mTvProvince = (TextView) findViewById(R.id.tv_province);
mTvCatName = (TextView) findViewById(R.id.tv_catName);
mTvCarrier = (TextView) findViewById(R.id.tv_carrier);
mBtnSearch.setOnClickListener(this);
mainPresenter = new MainPresenter(this);
mainPresenter.attach(this);
}
private boolean isEmpty(){
return mEtPhoneInput.getText().toString().isEmpty();
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn_search){
if (!isEmpty()){
mainPresenter.searchPhoneInfo(mEtPhoneInput.getText().toString());
mEtPhoneInput.setText("");
}
}
}
@Override
public void showLoading() {
if (loadingDialog == null){
loadingDialog = new LoadingDialog(this);
loadingDialog.setMessage("正在查询...");
} else {
loadingDialog.setMessage("正在查询...");
}
loadingDialog.show();
}
@Override
public void cancelLoading() {
if (loadingDialog != null && loadingDialog.isShowing()){
loadingDialog.cancel();
}
}
@Override
public void showToast(String msg) {
Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
}
@Override
public void updateView() {
Phone phone = mainPresenter.getPhone();
mTvPhoneNum.setText("手机号码:"+phone.getTelString());
mTvProvince.setText("省份:"+phone.getProvince());
mTvCatName.setText("运营商:"+phone.getCatName());
mTvCarrier.setText("运营者:"+phone.getCarrier());
}
}
当然以上的都不算是这个工程的的核心代码(下面将贴出工程中最重要的三个文件)
一、HttpUtil.java 对于http的请求,用到了okhttp框架(添加依赖即可)
compile 'com.squareup.okhttp3:okhttp:3.9.0'
package com.exmple.phonesearch.business;
import android.os.Handler;
import android.os.Looper;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by eric on 2017/12/12.
*/
public class HttpUtil {
private OkHttpClient client = new OkHttpClient();
private String mUrl;
private Map mParam;
private HttpResponse mHttpResponse;
private Handler mHandler = new Handler(Looper.getMainLooper());
public HttpUtil(HttpResponse response){
this.mHttpResponse = response;
}
public interface HttpResponse{
void onSuccess(Object obj);
void onFail(String error);
}
public void sendPostHttp(String url, Map param){
sendHttp(url,param,true);
}
public void sendGetHttp(String url, Map param){
sendHttp(url,param,false);
}
private void sendHttp(String url, Map param, boolean isPost){
this.mUrl = url;
this.mParam = param;
run(isPost);
}
private void run(boolean isPost){
Request request = createRequest(isPost);
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
if (mHttpResponse != null){
mHandler.post(new Runnable() {
@Override
public void run() {
mHttpResponse.onFail("请求错误");
}
});
}
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
if (mHttpResponse != null){
mHandler.post(new Runnable() {
@Override
public void run() {
if (!response.isSuccessful()){
mHttpResponse.onFail("请求失败");
} else {
try {
mHttpResponse.onSuccess(response.body().string());
} catch (IOException e) {
e.printStackTrace();
mHttpResponse.onFail("结果转换失败");
}
}
}
});
}
}
});
}
private Request createRequest(boolean isPost){
Request request;
if (isPost){
MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder();
requestBodyBuilder.setType(MultipartBody.FORM);
Iterator> iterator = mParam.entrySet().iterator();
while ((iterator.hasNext())){
Map.Entry entry = iterator.next();
requestBodyBuilder.addFormDataPart(entry.getKey(),entry.getValue());
}
request = new Request.Builder().url(mUrl)
.post(requestBodyBuilder.build())
.build();
} else {
String urlString = mUrl+"?"+MapParamToString(mParam);
request = new Request.Builder().url(urlString)
.build();
}
return request;
}
private String MapParamToString(Map param){
StringBuilder stringBuilder = new StringBuilder();
Iterator> iterator = param.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry entry = iterator.next();
stringBuilder.append(entry.getKey()+"="+entry.getValue()+"&");
}
String str = stringBuilder.toString().substring(0,stringBuilder.length()-1);
return str;
}
}
二、MvpMainView.java 这个接口类用于连接View层(MainActivity.java)和逻辑处理层(MainPresenter.java)
package com.exmple.phonesearch.mvp;
/**
* Created by eric on 2017/12/12.
*/
public interface MvpMainView extends MvpLoadingVIew{
void showToast(String msg);
void updateView();
}
三、MainPresenter.java 数据处理层(会用到Gson这个框架来处理json,添加依赖即可)
compile 'com.google.code.gson:gson:2.2.4'
package com.exmple.phonesearch.mvp.impl;
import android.util.Log;
import com.exmple.phonesearch.business.HttpUtil;
import com.exmple.phonesearch.model.Phone;
import com.exmple.phonesearch.mvp.MvpMainView;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;
/**
* Created by eric on 2017/12/12.
*/
public class MainPresenter extends BasePresenter {
private static final String mUrl = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm";
private MvpMainView mvpMainView;
private Phone phone;
private Gson gson = new Gson();
public MainPresenter(MvpMainView mvpMainView){
this.mvpMainView = mvpMainView;
}
public Phone getPhone() {
return phone;
}
public void searchPhoneInfo(String phoneString){
if (phoneString.length() != 11){
mvpMainView.showToast("手机号码不正确");
return;
}
mvpMainView.showLoading();
//http request method
sendHttp(phoneString);
}
private void sendHttp(String phoneString){
Map map = new HashMap();
map.put("tel",phoneString);
HttpUtil httpUtil = new HttpUtil(new HttpUtil.HttpResponse() {
@Override
public void onSuccess(Object obj) {
String json = obj.toString();
Log.d("---", "onSuccess: "+json);
int index = json.indexOf("{");
json = json.substring(index,json.length());
phone = gson.fromJson(json,Phone.class);
mvpMainView.cancelLoading();
mvpMainView.updateView();
}
@Override
public void onFail(String error) {
mvpMainView.showToast(error);
mvpMainView.cancelLoading();
}
});
httpUtil.sendGetHttp(mUrl,map);
}
}
小结:这个工程的逻辑还是很清晰的,view层通过点击按钮->数据处理层->网络请求层->数据转发->更新UI
点击:工程地址(码云git) 可以下载或查看工程源码