Android Studio第一月手機獲取
阿新 • • 發佈:2018-12-20
獲取手機號:
然後
public class MainActivity extends AppCompatActivity {
private EditText input; private Button query; private TextView info; private final int UPDATE_PHONE_INFO = 0; private final int GET_PHONE_INFO_ERROR = 1; //thread //ctrl + p 檢視方法需要引數 @SuppressLint("HandlerLeak") private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case UPDATE_PHONE_INFO: info.setText((String) msg.obj); break; case GET_PHONE_INFO_ERROR: info.setText((String) msg.obj); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); input = findViewById(R.id.input); input.setText("18679906337"); //快速提取變數 //ctrl + alt + v 區域性 //ctrl + alt + f 全域性 query = findViewById(R.id.query);//shift + f6 快捷重構 info = findViewById(R.id.info); query.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { //切換到子執行緒中請求資料 requestData(input.getText().toString()); } }).start(); } }); } private void s() { //執行緒 //Thread; //執行緒池 //Executor; //new Thread().run(); new Thread(){ @Override public void run() { super.run(); requestData(""); } } //開啟 執行 .start(); } private String apiUrl = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel="; //重定向 private void requestData(String phoneNum) { //做網路操作,必須在子執行緒中做 //查詢手機號 //java對http協議的簡單封裝 HttpUrlConnection try { //請求地址 URL url = new URL(apiUrl + phoneNum); //連線 ctrl + h 檢視繼承結構 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();// //請求方法 urlConnection.setRequestMethod("GET"); //連線超時時間 urlConnection.setConnectTimeout(5000); //讀取超時時間 urlConnection.setReadTimeout(5000); //獲取返回結果: 狀態碼 //響應狀態碼 (anr) NetworkOnMainThreadException int responseCode = urlConnection.getResponseCode(); if(responseCode == 200) {//請求成功 //獲取結果 String result = stream2String(urlConnection.getInputStream(), "gbk"); //展示 //info.setText(result); //ctrl + q 檢視文件 Message message = mHandler.obtainMessage(UPDATE_PHONE_INFO, result); mHandler.sendMessage(message); } else { //info.setText("請求返回錯誤: " + responseCode); mHandler.sendMessage(mHandler.obtainMessage(GET_PHONE_INFO_ERROR, "請求返回錯誤: " + responseCode)); } urlConnection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private String stream2String(InputStream inputStream, String charsetName) throws IOException { StringBuilder stringBuilder = new StringBuilder(); InputStreamReader isr = new InputStreamReader(inputStream, charsetName); BufferedReader br = new BufferedReader(isr); for (String tmp = br.readLine(); tmp != null; tmp = br.readLine()) { stringBuilder.append(tmp); } return stringBuilder.toString(); }
}