zoukankan      html  css  js  c++  java
  • 归属地查询(联网+本地)

      1 package com.highxin.number_location;
      2 
      3 
      4 import java.io.File;
      5 import java.io.FileOutputStream;
      6 import java.io.IOException;
      7 import java.io.InputStream;
      8 import java.util.regex.Matcher;
      9 import java.util.regex.Pattern;
     10 import org.apache.http.HttpResponse;
     11 import org.apache.http.ParseException;
     12 import org.apache.http.client.ClientProtocolException;
     13 import org.apache.http.client.methods.HttpGet;
     14 import org.apache.http.impl.client.DefaultHttpClient;
     15 import org.apache.http.util.EntityUtils;
     16 import android.app.Activity;
     17 import android.database.Cursor;
     18 import android.database.sqlite.SQLiteDatabase;
     19 import android.os.Bundle;
     20 import android.os.Handler;
     21 import android.os.Message;
     22 import android.text.Editable;
     23 import android.text.TextWatcher;
     24 import android.view.View;
     25 import android.view.View.OnClickListener;
     26 import android.widget.Button;
     27 import android.widget.EditText;
     28 import android.widget.TextView;
     29 import android.widget.Toast;
     30 
     31 public class MainActivity extends Activity implements Runnable {
     32     private SQLiteDatabase database;
     33     private final String DATABASE_PATH = android.os.Environment
     34             .getExternalStorageDirectory().getAbsolutePath()
     35             + "/mobilelocation";
     36     private String number;
     37     private String city;
     38     private String location;
     39     private final String DATABASE_FILENAME = "mobilelocation.db";
     40     private TextView tv;
     41     private String baseURL = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
     42     String myurl="";
     43     String myresult="";
     44     String temp="";
     45     Thread t;
     46     private Handler mHandler = new Handler() {
     47 
     48         @Override
     49         public void handleMessage(Message msg) {
     50             super.handleMessage(msg);
     51             myresult = filterHtml(temp);
     52             tv.setText(myresult);
     53         }
     54         
     55     };
     56     @Override
     57     protected void onCreate(Bundle savedInstanceState) {
     58         super.onCreate(savedInstanceState);
     59         setContentView(R.layout.activity_main);
     60         final EditText et = (EditText) findViewById(R.id.et_number);
     61         Button bt = (Button) findViewById(R.id.bt_srarch);
     62         //ImageView iv = (ImageView) findViewById(R.id.iv_delete);
     63         tv =(TextView) findViewById(R.id.tv_loaction);
     64         
     65         
     66         
     67         database = openDatabase();
     68         et.addTextChangedListener(new TextWatcher() {
     69             
     70             @Override
     71             public void onTextChanged(CharSequence s, int start, int before, int count) {
     72                 // TODO Auto-generated method stub
     73                 
     74             }
     75             
     76             @Override
     77             public void beforeTextChanged(CharSequence s, int start, int count,
     78                     int after) {
     79                 // TODO Auto-generated method stub
     80                 
     81             }
     82             
     83             @Override
     84             public void afterTextChanged(Editable s) {
     85                 if(!isNumeric(s.toString()) || s.length()>11   ) {
     86                     Toast.makeText(MainActivity.this, "您输入的号码有误,请查证后再输!!", Toast.LENGTH_SHORT).show();
     87                     return;
     88                     }
     89                 if(s.length()<7){
     90                     return;
     91                 }
     92                 if(s.length()>=7 && s.length()<=11) {
     93                     s= (Editable) s.subSequence(0, 7);
     94                 }
     95                 
     96                 // TODO Auto-generated method stub
     97                 Cursor cursor = database.rawQuery(
     98                         "select city,location from location_data where number=?",
     99                         new String[]
    100                         {s.toString()});
    101                 if (cursor.getCount() > 0)
    102                 {
    103                     //  必须使用moveToFirst方法将记录指针移动到第1条记录的位置
    104                     cursor.moveToFirst();
    105                     city = cursor.getString(cursor.getColumnIndex("city"));
    106                     location = cursor.getString(cursor.getColumnIndex("location"));
    107                     //将结果显示到TextView中
    108                     tv.setText(et.getText()+"
    "+city.toString()+"
    "+location.toString());
    109                 }
    110                 else {
    111                     //将结果显示到TextView中
    112                     tv.setText("");
    113                     Toast.makeText(MainActivity.this, "点击查询进行联网搜索", Toast.LENGTH_SHORT).show();
    114                 }    
    115             }
    116         });
    117         bt.setOnClickListener(new OnClickListener() {    
    118             @Override
    119             public void onClick(View v) {
    120                 String result ="";
    121                 number = et.getText().toString();
    122                 String b="";
    123                 myurl = baseURL+"?mobileCode="+number+"&userID="+b;
    124                 t = new Thread(MainActivity.this);
    125                 t.start();
    126                 System.out.println(myurl);
    127             }
    128         });
    129     }
    130     
    131        private String OpenHttpConnection(String url)
    132         {
    133            String result = null;
    134            HttpGet httpGet = new HttpGet(url);
    135            HttpResponse httpResponse = null;
    136         try {
    137             httpResponse = new DefaultHttpClient().execute(httpGet);
    138         } catch (ClientProtocolException e1) {
    139             e1.printStackTrace();
    140         } catch (IOException e1) {
    141             e1.printStackTrace();
    142         }
    143            if (httpResponse.getStatusLine().getStatusCode() == 200)
    144            {
    145                 //第三步,使用getEntity方法活得返回结果
    146                 try {
    147                     result = EntityUtils.toString(httpResponse.getEntity());
    148                 } catch (ParseException e) {
    149                     e.printStackTrace();
    150                 } catch (IOException e) {
    151                     e.printStackTrace();
    152                 }
    153             }
    154             return result;     
    155         }
    156         
    157     private SQLiteDatabase openDatabase() {
    158         try
    159         {
    160             // 获得dictionary.db文件的绝对路径
    161             String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;
    162             File dir = new File(DATABASE_PATH);
    163             // 如果/sdcard/dictionary目录中存在,创建这个目录
    164             if (!dir.exists())
    165                 dir.mkdir();
    166             // 如果在/sdcard/dictionary目录中不存在
    167             // dictionary.db文件,则从res
    aw目录中复制这个文件到
    168             // SD卡的目录(/sdcard/dictionary)
    169             if (!(new File(databaseFilename)).exists())
    170             {
    171                 // 获得封装dictionary.db文件的InputStream对象
    172                 InputStream is = getResources().openRawResource(
    173                         R.raw.mobilelocation);
    174                 FileOutputStream fos = new FileOutputStream(databaseFilename);
    175                 byte[] buffer = new byte[50000];
    176                 int count = 0;
    177                 // 开始复制dictionary.db文件
    178                 while ((count = is.read(buffer)) > 0)
    179                 {
    180                     fos.write(buffer, 0, count);
    181                 }
    182                 //关闭文件流
    183                 fos.close();
    184                 is.close();
    185             }
    186             // 打开/sdcard/dictionary目录中的dictionary.db文件
    187             SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(
    188                     databaseFilename, null);
    189             return database;
    190         }
    191         catch (Exception e)
    192         {
    193         }
    194         //如果打开出错,则返回null
    195         return null;
    196     }
    197     //判断字符串是否为数字
    198     public boolean isNumeric(String str){ 
    199            Pattern pattern = Pattern.compile("[0-9]*"); 
    200            Matcher isNum = pattern.matcher(str);
    201            if( !isNum.matches() ){
    202                return false; 
    203            } 
    204            return true; 
    205         }
    206     //过滤掉<>中的无用信息
    207     private String filterHtml(String source) {
    208         if (null == source) {
    209             return "";
    210         }
    211         return source.replaceAll("</?[^>]+>", "").trim();
    212     }
    213     @Override
    214     public void run() {
    215         temp=OpenHttpConnection(myurl);    
    216         mHandler.sendEmptyMessage(0);
    217     }
    218 }
     1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     2     android:orientation="vertical"
     3     android:layout_width="match_parent"
     4     android:layout_height="match_parent">
     5     <RelativeLayout
     6         android:id="@+id/search"
     7         android:layout_width="match_parent"
     8         android:layout_height="wrap_content" >
     9         <EditText
    10         android:id="@+id/et_number"
    11         android:layout_marginTop="1dp"
    12         android:layout_width="match_parent"
    13         android:layout_height="wrap_content"
    14         android:background="@android:drawable/edit_text"
    15         android:hint="请输入手机号"
    16         android:layout_alignParentLeft="true"
    17         android:layout_toLeftOf="@+id/bt_search"
    18         android:ems="11"
    19         android:singleLine="true" />
    20            <!-- <ImageView 
    21              android:id="@+id/iv_delete"
    22              android:layout_width="10dp"
    23              android:layout_height="10dp"
    24              android:scaleType="centerCrop"
    25              android:src="@drawable/delete"
    26              android:visibility="invisible"  
    27                /> -->
    28            <Button 
    29         android:id="@+id/bt_srarch"
    30         android:layout_width="wrap_content"
    31         android:layout_height="wrap_content"
    32         android:layout_alignParentRight="true"
    33         android:layout_alignParentTop="true"  
    34         android:text="搜索"
    35         />
    36         
    37     </RelativeLayout>
    38 
    39     
    40     <TextView
    41         android:id="@+id/tv_loaction"
    42         android:layout_width="wrap_content"
    43         android:layout_height="wrap_content"
    44         android:text="" />
    45 
    46 </LinearLayout>
     <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
          <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
          <uses-permission android:name="android.permission.INTERNET"/>

     上面的写法虽然能获取到数据,但思路不是很清晰,下面是推荐的写法:

    java.nei.HttpURLConnection类是另外一种访问HTTP资源的方式。HTTPURLConnection类具有完全的访问能力,可以取代HttpGet和HttpHost类。

     1 private String getData(){
     2         String t="";
     3         try
     4         {
     5             InputStream is = getNetInputStream(myurl);
     6             InputStreamReader isr = new InputStreamReader(is, "utf-8");
     7             BufferedReader br = new BufferedReader(isr);
     8             String s = null;
     9             while ((s = br.readLine()) != null)
    10             {
    11                 String[] data = s.split(">");
    12                 if (data.length > 1)
    13                 {
    14                     
    15                     t = data[1];
    16                     
    17                 }
    18             }
    19             is.close();
    20         }
    21         catch (Exception e)
    22         {
    23             // TODO: handle exception
    24         }
    25         
    26         return t;
    27     }
    28     private InputStream getNetInputStream(String urlStr)
    29     {
    30         try
    31         {
    32             URL url = new URL(urlStr);
    33             URLConnection conn = url.openConnection();
    34             conn.connect();
    35             InputStream is = conn.getInputStream();
    36             return is;
    37         }
    38         catch (Exception e)
    39         {
    40 
    41         }
    42         return null;
    43     }


    完整源码为:

      1 package com.highxin.number_location;
      2 
      3 
      4 import java.io.BufferedReader;
      5 import java.io.File;
      6 import java.io.FileOutputStream;
      7 import java.io.IOException;
      8 import java.io.InputStream;
      9 import java.io.InputStreamReader;
     10 import java.net.URL;
     11 import java.net.URLConnection;
     12 import java.util.regex.Matcher;
     13 import java.util.regex.Pattern;
     14 import org.apache.http.HttpResponse;
     15 import org.apache.http.ParseException;
     16 import org.apache.http.client.ClientProtocolException;
     17 import org.apache.http.client.methods.HttpGet;
     18 import org.apache.http.impl.client.DefaultHttpClient;
     19 import org.apache.http.util.EntityUtils;
     20 import android.app.Activity;
     21 import android.database.Cursor;
     22 import android.database.sqlite.SQLiteDatabase;
     23 import android.os.Bundle;
     24 import android.os.Handler;
     25 import android.os.Message;
     26 import android.text.Editable;
     27 import android.text.TextWatcher;
     28 import android.util.Log;
     29 import android.view.View;
     30 import android.view.View.OnClickListener;
     31 import android.widget.Button;
     32 import android.widget.EditText;
     33 import android.widget.TextView;
     34 import android.widget.Toast;
     35 
     36 public class MainActivity extends Activity implements Runnable {
     37     private SQLiteDatabase database;
     38     private final String DATABASE_PATH = android.os.Environment
     39             .getExternalStorageDirectory().getAbsolutePath()
     40             + "/mobilelocation";
     41     private String number;
     42     private String city;
     43     private String location;
     44     private final String DATABASE_FILENAME = "mobilelocation.db";
     45     private TextView tv;
     46     private String baseURL = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
     47     String myurl="";
     48     String myresult="";
     49     String temp="";
     50     Thread t;
     51     private Handler mHandler = new Handler() {
     52 
     53         @Override
     54         public void handleMessage(Message msg) {
     55             super.handleMessage(msg);
     56             myresult = filterHtml(temp);
     57             tv.setText(myresult.substring(0, myresult.length()-8));
     58         }
     59         
     60     };
     61     @Override
     62     protected void onCreate(Bundle savedInstanceState) {
     63         super.onCreate(savedInstanceState);
     64         setContentView(R.layout.activity_main);
     65         final EditText et = (EditText) findViewById(R.id.et_number);
     66         Button bt = (Button) findViewById(R.id.bt_srarch);
     67         //ImageView iv = (ImageView) findViewById(R.id.iv_delete);
     68         tv =(TextView) findViewById(R.id.tv_loaction);
     69         
     70         
     71         
     72         database = openDatabase();
     73         et.addTextChangedListener(new TextWatcher() {
     74             
     75             @Override
     76             public void onTextChanged(CharSequence s, int start, int before, int count) {
     77                 // TODO Auto-generated method stub
     78                 
     79             }
     80             
     81             @Override
     82             public void beforeTextChanged(CharSequence s, int start, int count,
     83                     int after) {
     84                 // TODO Auto-generated method stub
     85                 
     86             }
     87             
     88             @Override
     89             public void afterTextChanged(Editable s) {
     90                 if(!isNumeric(s.toString()) || s.length()>11   ) {
     91                     Toast.makeText(MainActivity.this, "您输入的号码有误,请查证后再输!!", Toast.LENGTH_SHORT).show();
     92                     return;
     93                     }
     94                 if(s.length()<7){
     95                     return;
     96                 }
     97                 if(s.length()>=7 && s.length()<=11) {
     98                     s= (Editable) s.subSequence(0, 7);
     99                 }
    100                 
    101                 // TODO Auto-generated method stub
    102                 Cursor cursor = database.rawQuery(
    103                         "select city,location from location_data where number=?",
    104                         new String[]
    105                         {s.toString()});
    106                 if (cursor.getCount() > 0)
    107                 {
    108                     //  必须使用moveToFirst方法将记录指针移动到第1条记录的位置
    109                     cursor.moveToFirst();
    110                     city = cursor.getString(cursor.getColumnIndex("city"));
    111                     location = cursor.getString(cursor.getColumnIndex("location"));
    112                     //将结果显示到TextView中
    113                     tv.setText(et.getText()+"
    "+city.toString()+"
    "+location.toString());
    114                 }
    115                 else {
    116                     //将结果显示到TextView中
    117                     tv.setText("");
    118                     Toast.makeText(MainActivity.this, "点击查询进行联网搜索,请先确保数据连接开启", Toast.LENGTH_SHORT).show();
    119                 }    
    120             }
    121         });
    122         bt.setOnClickListener(new OnClickListener() {    
    123             @Override
    124             public void onClick(View v) {
    125                 String result ="";
    126                 number = et.getText().toString();
    127                 String b="";
    128                 myurl = baseURL+"?mobileCode="+number+"&userID="+b;
    129                 t = new Thread(MainActivity.this);
    130                 t.start();
    131                 System.out.println(myurl);
    132             }
    133         });
    134     }
    135     
    136 //       private String OpenHttpConnection(String url)
    137 //        {
    138 //           String result = null;
    139 //           HttpGet httpGet = new HttpGet(url);
    140 //           HttpResponse httpResponse = null;
    141 //        try {
    142 //            httpResponse = new DefaultHttpClient().execute(httpGet);
    143 //        } catch (ClientProtocolException e1) {
    144 //            e1.printStackTrace();
    145 //        } catch (IOException e1) {
    146 //            e1.printStackTrace();
    147 //        }
    148 //           if (httpResponse.getStatusLine().getStatusCode() == 200)
    149 //           {
    150 //                //第三步,使用getEntity方法活得返回结果
    151 //                try {
    152 //                    result = EntityUtils.toString(httpResponse.getEntity());
    153 //                } catch (ParseException e) {
    154 //                    e.printStackTrace();
    155 //                } catch (IOException e) {
    156 //                    e.printStackTrace();
    157 //                }
    158 //            }
    159 //            return result;     
    160 //        }
    161         
    162     private SQLiteDatabase openDatabase() {
    163         try
    164         {
    165             // 获得dictionary.db文件的绝对路径
    166             String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;
    167             File dir = new File(DATABASE_PATH);
    168             // 如果/sdcard/dictionary目录中存在,创建这个目录
    169             if (!dir.exists())
    170                 dir.mkdir();
    171             // 如果在/sdcard/dictionary目录中不存在
    172             // dictionary.db文件,则从res
    aw目录中复制这个文件到
    173             // SD卡的目录(/sdcard/dictionary)
    174             if (!(new File(databaseFilename)).exists())
    175             {
    176                 // 获得封装dictionary.db文件的InputStream对象
    177                 InputStream is = getResources().openRawResource(
    178                         R.raw.mobilelocation);
    179                 FileOutputStream fos = new FileOutputStream(databaseFilename);
    180                 byte[] buffer = new byte[50000];
    181                 int count = 0;
    182                 // 开始复制dictionary.db文件
    183                 while ((count = is.read(buffer)) > 0)
    184                 {
    185                     fos.write(buffer, 0, count);
    186                 }
    187                 //关闭文件流
    188                 fos.close();
    189                 is.close();
    190             }
    191             // 打开/sdcard/dictionary目录中的dictionary.db文件
    192             SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(
    193                     databaseFilename, null);
    194             return database;
    195         }
    196         catch (Exception e)
    197         {
    198         }
    199         //如果打开出错,则返回null
    200         return null;
    201     }
    202     //判断字符串是否为数字
    203     public boolean isNumeric(String str){ 
    204            Pattern pattern = Pattern.compile("[0-9]*"); 
    205            Matcher isNum = pattern.matcher(str);
    206            if( !isNum.matches() ){
    207                return false; 
    208            } 
    209            return true; 
    210         }
    211     //过滤掉<>中的无用信息
    212     private String filterHtml(String source) {
    213         if (null == source) {
    214             return "";
    215         }
    216         return source.replaceAll("</?[^>]+>", "").trim();
    217     }
    218     private String getData(){
    219         String t="";
    220         try
    221         {
    222             InputStream is = getNetInputStream(myurl);
    223             InputStreamReader isr = new InputStreamReader(is, "utf-8");
    224             BufferedReader br = new BufferedReader(isr);
    225             String s = null;
    226             while ((s = br.readLine()) != null)
    227             {
    228                 String[] data = s.split(">");
    229                 if (data.length > 1)
    230                 {
    231                     
    232                     t = data[1];
    233                     
    234                 }
    235             }
    236             is.close();
    237         }
    238         catch (Exception e)
    239         {
    240             // TODO: handle exception
    241         }
    242         
    243         return t;
    244     }
    245     private InputStream getNetInputStream(String urlStr)
    246     {
    247         try
    248         {
    249             URL url = new URL(urlStr);
    250             URLConnection conn = url.openConnection();
    251             conn.connect();
    252             InputStream is = conn.getInputStream();
    253             return is;
    254         }
    255         catch (Exception e)
    256         {
    257 
    258         }
    259         return null;
    260     }
    261     @Override
    262     public void run() {
    263         temp=getData();    
    264         mHandler.sendEmptyMessage(0);
    265     }
    266 }

     源码下载地址:http://files.cnblogs.com/hixin/Number_Location.rar

    安装包下载:http://files.cnblogs.com/hixin/%E5%BD%92%E5%B1%9E%E5%9C%B0%E6%9F%A5%E8%AF%A2.apk

  • 相关阅读:
    C#字符串的比较
    C#字符串分割
    [Android] Android 卡片式控件CardView的优雅使用
    [Android] Android Studio 使用config.gradle统一管理项目的依赖库
    [Android] Android Studio 修改Gradle使用国内源
    [Android] Sqlite 数据库操作 工具封装类
    [Android] Android 去掉界面标题栏的方法
    [Android] Android RecycleView和ListView 自定义Adapter封装类
    [Android] Android 让UI控件固定于底部的几种方法
    [Android] Android读取Asset下文件的最简单的方法总结(用于MediaPlayer中)
  • 原文地址:https://www.cnblogs.com/hixin/p/4154067.html
Copyright © 2011-2022 走看看