36_查询手机号码归属地&外部数据库的引入

来源:互联网 发布:淘宝商城女装大码 编辑:程序博客网 时间:2024/05/21 00:01

一、asset目录中放入 xxx.db (可以打包到apk文件中)



二、splash中初始化数据库(拷贝xxx.db到 SD卡中)

/**
* 拷贝号码归属地的数据库
*/
private void copyAddressDB() {

new Thread() {
public void run() {
// data/data/包名/files目录
File destFile = new File(getFilesDir(), "xxx.db");     //  "/data/data/com.itheima.mobilesafe/files/address.db"
if (destFile.exists() && destFile.length() > 0) {
Logger.i(TAG, "文件已经存在,不需要拷贝");
} else {
File file = AssetCopyUtils.copy(getApplicationContext(),
"address.jpg", destFile.getAbsolutePath());
Message msg = Message.obtain();
if (file == null) {// 拷贝失败.
msg.what = COPY_DB_ERROR;
} else {
msg.what = COPY_DB_SUCCESS;
}
handler.sendMessage(msg);
}
;
}
}.start();

}


附加:AssetCopyUtils 类

public class AssetCopyUtils {


/**
* 资产拷贝的工具类

* @param contex
*            上下文
* @param filename
*            文件名称
* @param destPath
*            拷贝的目标路径
* @return 文件对象.
*/
public static File copy(Context context, String fileName, String destPath) {
try {
InputStream is = context.getAssets().open(fileName);
File file = new File(destPath);
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = 0;


while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.flush();
fos.close();
is.close();
return file;
} catch (Exception e) {
e.printStackTrace();
return null;
}


}
}


三、Dao类中

public class AddressDao {


private static final String path = "/data/data/com.itheima.mobilesafe/files/address.db";


/**
* 获取号码的归属地信息.

* @param 要查询的电话号码
* @return
*/
public static String getAddress(String number) {
String address = number;// 如果查询不到号码归属地 就返回当前号码
SQLiteDatabase db = SQLiteDatabase.openDatabase(path, null,
SQLiteDatabase.OPEN_READONLY);


// 判断号码是否是手机号码.
// 13 15 14 18 + 9位的数字.
if (number.matches("^1[3458]\\d{9}$")) {// 手机号码
Cursor cursor = db
.rawQuery(
"select location from data2 where id =(select outkey from data1 where id = ?)",
new String[] { number.substring(0, 7) });
if (cursor.moveToNext()) {
address = cursor.getString(0);
}
cursor.close();
} else {// 其他号码
switch (number.length()) {
case 3:
address = "特殊号码";
break;


case 4:
address = "模拟器";
break;
case 7:
address = "本地号码";
break;
case 8:
address = "本地号码";
break;

default:
if(number.length()>=10){
Cursor curosr = null;
curosr = db.rawQuery("select location from data2 where area = ? ", new String[]{number.substring(1, 3)});//查询前三位
if(curosr.moveToNext()){
String info  = curosr.getString(0);
address = info.substring(0, info.length()-2);
}
curosr.close();
curosr = db.rawQuery("select location from data2 where area = ? ", new String[]{number.substring(1, 4)});//查询前四位
if(curosr.moveToNext()){
String info  = curosr.getString(0);
address = info.substring(0, info.length()-2);
}
curosr.close();
}

}


}
db.close();
return address;
}
}

0 0
原创粉丝点击