Android phone number attribution to the query _android

Source: Internet
Author: User
Tags urlencode stringbuffer

A simple demo, from aggregation data to apply for mobile phone number attribution to the data interface;

Enter the query number in the EditText, get the number and use HttpURLConnection to get the JSON data in the child thread, then parse;

After data acquisition is complete, update the UI in the main thread to show the number attribution information.

Layout file

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= 
"http://schemas.android.com/apk/" Res/android " 
  android:layout_width=" match_parent " 
  android:layout_height=" match_parent " 
  android:o" rientation= "vertical" >   
 
   
  <edittext  
    android:id= "@+id/et_querylocation" 
    Wrap_content " 
    android:layout_width=" match_parent " 
    android:textcolor=" #000000 " 
    android:hint=" input number " />  
   
  <button  
    android:onclick= "Query" 
    android:textsize= "24sp" 
    android:layout_width= " Wrap_content " 
    android:layout_height=" wrap_content " 
    android:text=" query "/> 
   
  <textview  
    Android:layout_width= "Match_parent" 
    android:layout_height= "wrap_content" 
    android:id= "@+id/tv_" Phonelocation " 
    android:textsize=" 20sp " 
    android:textcolor=" #000000 "/> 
 

Java code

Package com.example.phonehome; 
Import Java.io.BufferedReader; 
Import Java.io.DataOutputStream; 
Import java.io.IOException; 
Import Java.io.InputStream; 
Import Java.io.InputStreamReader; 
Import java.io.UnsupportedEncodingException; 
Import java.net.HttpURLConnection; 
Import Java.net.URL; 
Import Java.net.URLEncoder; 
Import Java.util.HashMap; 
 
Import Java.util.Map; 
 
Import Org.json.JSONObject; 
Import android.app.Activity; 
Import Android.os.Bundle; 
Import Android.os.Handler; 
Import Android.text.TextUtils; 
Import Android.view.View; 
Import Android.widget.EditText; 
Import Android.widget.TextView; 
 
Import Android.widget.Toast; 
  public class Mainactivity extends activity {private EditText et_phone; 
  Private TextView Tv_phone; 
  Private final static int START = 0; 
  private final static int = 1; 
  private string phone;//to query number//number information private static string province; 
  private static String city; 
  private static String company; private static StRing card; 
   public static final String Def_chatset = "UTF-8"; 
   public static final int def_conn_timeout = 30000; 
    
   public static final int def_read_timeout = 30000; 
   
   public static final String Appkey = "requested app KEY";  
       Handler Handler = new Handler () {public void Handlemessage (Android.os.Message msg) {, when query data starts and completes in child threads. Switch (msg.what) {case START:Toast.makeText (mainactivity.this, "Querying, Please Wait", Toast.length_short) 
        . Show (); 
         
      Break Case FINISH://Display the number information found in TextView (the UI cannot be updated in child threads) Tv_phone.settext (province + "+ City +" + company +) 
        "+ card); 
      Break 
      Default:break; 
   } 
     }; 
    
  }; 
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
  Initview (); 
    //button Store event, get query number after query public void query (View v) {phone = Et_phone.gettext (). toString (). Trim (); If(! Textutils.isempty (phone) {new Thread () {public void run () {///start query HANDLER.OBTAINM 
          Essage (START). Sendtotarget (); 
          Getrequest (phone); 
        Results Handler.obtainmessage (FINISH). Sendtotarget (); 
      }; 
    }.start (); 
    }else {toast.maketext (mainactivity.this, "Enter number cannot be empty", Toast.length_short). Show (); 
    }//Cell phone attribution query public static void Getrequest (String phone) {string, result =null; String url = "Http://apis.juhe.cn/mobile/get";//Request interface address MAP params = new HashMap ()//Request parameter Params.put ("Phone", pho NE)//need to query the mobile phone number or mobile phone number before the 7-bit params.put ("key", appkey);//Apply Appkey (Apply detailed page query) params.put ("Dtype", ""); Returns the format of the data, XML or JS 
      On, the default JSON try {//Get JSON data, and parse result =net (URL, params, "got"); 
      Jsonobject object = new Jsonobject (result); 
      Jsonobject ob = new Jsonobject (object.get ("result"). ToString () + ""); Province = ob.getstring ("ProvincE "); 
      City = ob.getstring ("city"); 
      Company = ob.getstring ("Company"); 
    Card = ob.getstring ("card"); 
    catch (Exception e) {e.printstacktrace (); }/** * * @param strurl Request address * @param params request parameter * @param method request * @return Network Request String * Throws Exception */public static string net (String strURL, Map params,string method) throws Exception {Httpur 
    Lconnection conn = null; 
    BufferedReader reader = null; 
    String rs = null; 
      try {stringbuffer sb = new StringBuffer (); if (Method==null | | method.equals ("get")) {strURL = strurl+ "?" 
      +urlencode (params); 
      URL url = new URL (strurl); 
      conn = (httpurlconnection) url.openconnection (); 
      if (Method==null | | method.equals ("get")) {Conn.setrequestmethod (' get '); 
        }else{Conn.setrequestmethod ("POST"); 
      Conn.setdooutput (TRUE); }//conn.setrequestproperty ("User-agent", useragent); 
      Conn.setusecaches (FALSE); 
      Conn.setconnecttimeout (def_conn_timeout); 
      Conn.setreadtimeout (def_read_timeout); 
      Conn.setinstancefollowredirects (FALSE); 
      Conn.connect (); if (params!= null && method.equals ("POST") {try {dataoutputstream out = new Dataoutputstrea 
          M (Conn.getoutputstream ()); 
        Out.writebytes (UrlEncode (params)); 
        catch (Exception e) {//Todo:handle Exception e.printstacktrace (); 
      } InputStream is = Conn.getinputstream (); 
      reader = new BufferedReader (new InputStreamReader (IS, def_chatset)); 
      String strread = null; 
      while ((Strread = Reader.readline ())!= null) {sb.append (strread); 
    rs = sb.tostring (); 
    catch (IOException e) {e.printstacktrace (); 
      finally {if (reader!= null) {reader.close (); } if (conn!= null) {Conn.disconnect (); 
  } return RS; ///Convert MAP type to request parameter public static String UrlEncode (map<string,string> data) {StringBuilder SB = new Strin 
    Gbuilder (); For (Map.entry I:data.entryset ()) {try {sb.append (I.getkey ()). Append ("="). Append (Urlencoder.encode 
      Etvalue () + "", "UTF-8"). Append ("&"); 
      catch (Unsupportedencodingexception e) {e.printstacktrace (); 
  } return sb.tostring (); 
    private void Initview () {Setcontentview (r.layout.activity_main); 
    Et_phone = (edittext) Findviewbyid (r.id.et_querylocation); 
  Tv_phone = (TextView) Findviewbyid (r.id.tv_phonelocation);  } 
 
}

The above is the entire content of this article, I hope to help you learn.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.