GVKun编程网logo

[android] 手机卫士接收打电话广播显示号码归属地(来电播报归属地)

11

在这篇文章中,我们将带领您了解[android]手机卫士接收打电话广播显示号码归属地的全貌,包括来电播报归属地的相关情况。同时,我们还将为您介绍有关android之访问WebService显示手机号码

在这篇文章中,我们将带领您了解[android] 手机卫士接收打电话广播显示号码归属地的全貌,包括来电播报归属地的相关情况。同时,我们还将为您介绍有关android 之访问WebService显示手机号码归属地、Android 基础-2.0 拔打电话号码、android 手机号码归属地查询 代码、Android 简单几步实现手机号码归属地查询,可监听文本框的变化自动查询的知识,以帮助您更好地理解这个主题。

本文目录一览:

[android] 手机卫士接收打电话广播显示号码归属地(来电播报归属地)

[android] 手机卫士接收打电话广播显示号码归属地(来电播报归属地)

使用广播接收者接收打电话的意图,显示号码归属地

 

新建一个类OutCallReceiver继承系统的broadcastReceiver

重写onReceive()方法

调用getResultData()方法,获取到String电话号码,查询数据库获取到归属地

package com.qingguow.mobilesafe.receiver;

import com.qingguow.mobilesafe.utils.NumberQueryAddressUtil;

 android.content.broadcastReceiver;
 android.content.Context;
 android.content.Intent;
 android.widget.Toast;
/**
 * 接收打电话广播
 * @author taoshihan
 *
 */
public class OutcallReceiver extends broadcastReceiver {

    @Override
    void onReceive(Context arg0,Intent arg1) {
        String phone=getResultData();
        String address=NumberQueryAddressUtil.queryAddress(phone);
        System.out.println("111"+address);
        Toast.makeText(arg0,address,1).show();
    }

}

 

 

清单文件中定义<receiver>节点,和<intent-filter>节点,设置<action>节点名称,android:name=”android.intent.action.NEW_OUTGOING_CALL”

需要权限,android.permission.PROCESS_OUTGOING_CALLS

 代码注册广播

此时的广播接收者,只要一打电话就会被调用,用户体验不好,我们使用代码注册广播接收者,用设置中心的开启监听电话来电的部分来控制这个广播

 

在服务里面调用registerReceiver()方法,注册广播,参数:broadcastReceiver对象,IntentFilter对象

获取IntentFilter对象,调用IntentFilter对象的addAction()方法,参数:android.intent.action.NEW_OUTGOING_CALL

 

在服务里面解除注册广播,调用unregisterReceiver()方法,参数:broadcastReceiver对象

 

 com.qingguow.mobilesafe.service;

 com.qingguow.mobilesafe.receiver.OutcallReceiver;
 android.app.Service;
 android.content.IntentFilter;
 android.os.IBinder;
 android.telephony.PhonestateListener;
 android.telephony.TelephonyManager;
 android.widget.Toast;


 * 来电显示
 * 
 *  taoshihan
 * 
 class AddressService  Service {
    private TelephonyManager tm;
     MyPhonestateListener phonestateListener;
     OutcallReceiver outcallReceiver;
    @Override
    public IBinder onBind(Intent arg0) {
        // Todo Auto-generated method stub
        return null;
    }
    
     * 服务创建
     */
    @Override
     onCreate() {
        super.onCreate();
        tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        phonestateListener = new MyPhonestateListener();
        tm.listen(phonestateListener,PhonestateListener.LISTEN_CALL_STATE);
        
        注册广播
        outcallReceiver= OutcallReceiver();
        IntentFilter filter= IntentFilter();
        filter.addAction("android.intent.action.NEW_OUTGOING_CALL");
        registerReceiver(outcallReceiver,filter);
    }

    private class MyPhonestateListener  PhonestateListener {
        @Override
        void onCallStateChanged(int state,String incomingNumber) {
            .onCallStateChanged(state,incomingNumber);
            switch (state) {
            case TelephonyManager.CALL_STATE_RINGING:
                String info = NumberQueryAddressUtil
                        .queryAddress(incomingNumber);
                Toast.makeText(getApplicationContext(),info,1)">).show();
                break;
            default:
                ;
            }
        }
    }
    
     * 服务销毁
      onDestroy() {
        .onDestroy();
        取消监听
        tm.listen(phonestateListener,PhonestateListener.LISTEN_NONE);
        phonestateListener=;
        解除注册广播
        unregisterReceiver(outcallReceiver);
        outcallReceiver=;
    }
}

 

android 之访问WebService显示手机号码归属地

android 之访问WebService显示手机号码归属地

 发送XML

 通过URL封装路径打开一个HttpURLConnection

 设置请求方式,Content-Type和Content-Length

XML文件的Content-Type为:text/xml; charset=UTF-8

使用HttpURLConnection获取输出流输出数据


 WebService

 WebService是发布在网络上的API,可以通过发送XML调用,WebService返回结果也是XML数据

 WebService没有语言限制,只要可以发送XML数据和接收XML数据即可

 http://www.webxml.com.cn 网站上提供了一些WebService服务,我们可以对其进行调用

 http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?op=getMobileCodeInfo 中提供了电话归属地查询的使用说明

内容如下:

SOAP 1.2

以下是 SOAP 1.2 请求和响应示例。所显示的占位符需替换为实际值。

POST /WebServices/MobileCodeWS.asmx HTTP/1.1
Host: webservice.webxml.com.cn
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <getMobileCodeInfo xmlns="http://WebXml.com.cn/">
      <mobileCode>string</mobileCode>
      <userID>string</userID>
    </getMobileCodeInfo>
  </soap12:Body>
</soap12:Envelope>
HTTP/1.1 200 OK
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <getMobileCodeInfoResponse xmlns="http://WebXml.com.cn/">
      <getMobileCodeInfoResult>string</getMobileCodeInfoResult>
    </getMobileCodeInfoResponse>
  </soap12:Body>
</soap12:Envelope>

HTTP GET

以下是 HTTP GET 请求和响应示例。所显示的占位符需替换为实际值。

GET /WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode=string&userID=string HTTP/1.1
Host: webservice.webxml.com.cn
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://WebXml.com.cn/">string</string>

HTTP POST

以下是 HTTP POST 请求和响应示例。所显示的占位符需替换为实际值。

POST /WebServices/MobileCodeWS.asmx/getMobileCodeInfo HTTP/1.1
Host: webservice.webxml.com.cn
Content-Type: application/x-www-form-urlencoded
Content-Length: length

mobileCode=string&userID=string
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://WebXml.com.cn/">string</string>


下面为具体实例及代码:

界面显示:

向WebService发送的XML文件: send.xml(放置在SRC路径下)

<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <getMobileCodeInfo xmlns="http://WebXml.com.cn/">
      <mobileCode>$number</mobileCode>
      <userID></userID>
    </getMobileCodeInfo>
  </soap12:Body>
</soap12:Envelope>

布局文件man.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/phoneET"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="phone" >

        <requestFocus />
    </EditText>

    <Button
        android:onClick="onClick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="归属地查询" />

    <TextView
        android:id="@+id/locationTV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25sp"
/>

</LinearLayout>

功能清单文件AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.itheima.webservice"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />
    <uses-permission android:name="android.permission.INTERNET"/>
      <instrumentation
        android:name="android.test.InstrumentationTestRunner" 
        android:targetPackage="com.itheima.webservice"
        />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
    <uses-library android:name="android.test.runner" />
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity:

package com.itheima.webservice;

import com.itheima.webservice.service.NumberService;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private EditText phoneET;
	private TextView locationTV;
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        phoneET = (EditText) findViewById(R.id.phoneET);
       locationTV = (TextView) findViewById(R.id.locationTV);
        
        
    }
	
	public void onClick(View view){
		try {
			NumberService service = new NumberService();
			String num = phoneET.getText().toString();
			String loacation = service.getLocation(num);
			locationTV.setText(loacation);
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), "查无此号", 1).show();
		}
	}
    
    
}

NumberService
:

package com.itheima.webservice.service;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

import com.itheima.webservice.util.StreamUtil;

public class NumberService {

	public String getLocation(String number) throws Exception {
		// 读取本地准备好的文件, 用输入的号码替换原来的占位符
				InputStream in = NumberService.class.getClassLoader().getResourceAsStream("send.xml");
				byte[] data = StreamUtil.load(in);
				String content = new String(data);
				content = content.replace("$number", number);
				
				// 创建连接对象, 设置请求头, 按照Webservice服务端提供的要求来设置
				URL url = new URL("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx");
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setConnectTimeout(5000);
				conn.setRequestProperty("Host", "webservice.webxml.com.cn");
				conn.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
				conn.setRequestProperty("Content-Length", content.getBytes().length + "");
				conn.setRequestMethod("POST");
				
				// 输出数据
				conn.setDoOutput(true);
				conn.getOutputStream().write(content.getBytes());
			
				
//				// 获取服务端传回的数据, 解析XML, 得到结果
				XmlPullParser parser = Xml.newPullParser();
				parser.setInput(conn.getInputStream(), "UTF-8");
				
				for (int type = parser.getEventType();type!=XmlPullParser.END_DOCUMENT;type=parser.next()) 
				  if(type==XmlPullParser.START_TAG&&parser.getName().equals("getMobileCodeInfoResult")){
					  return parser.nextText();
				  }
				return "没有找到此号码";
	}

}

读取输入流工具类StreamUtil:

package com.itheima.webservice.util;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class StreamUtil {
   public static byte[] load(InputStream in ) throws IOException{
	   ByteArrayOutputStream baos = new ByteArrayOutputStream();
	   byte b [] = new byte[1024];
	   int len = -1;
	   while((len=in.read(b))!=-1){
		   baos.write(b,0,len);
	   }
	   baos.close();
	   return baos.toByteArray();
   }
}





原文链接: http://blog.csdn.net/t12x3456/article/details/7686448

Android 基础-2.0 拔打电话号码

Android 基础-2.0 拔打电话号码

1、添加权限

在AndroidManifest.xml 添加打电话权限

<uses-permission android:name="android.permission.CALL_PHONE"/>

2、自动布局设置页面

分享图片

分享图片

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">


    <TextView
        android:id="@+id/tv_phone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="10dp"
        android:text="@string/textPhone"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/et_phone"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="10dp"
        android:hint="@string/textPhoneHint"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tv_phone" />

    <Button
        android:id="@+id/btn_call"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="16dp"
        android:text="@string/textPhoneButton"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/et_phone" />


</androidx.constraintlayout.widget.ConstraintLayout>
View Code

页面效果

分享图片

3、给Activity添加拔打代码

分享图片

分享图片

public class MainActivity extends  BaseActivity {

    private Button eBtCall;
    private EditText mEtPhone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        eBtCall = findViewById(R.id.btn_call);
        mEtPhone = findViewById(R.id.et_phone);
        eBtCall.setonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                performCodeWithPermission("拔打电话权限",new PermissionCallback() {
                    @Override
                    public void hasPermission() {
                        Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:" + mEtPhone.getText()));
                        startActivity(intent);
                    }

                    @Override
                    public void nopermission() {

                    }
                },Manifest.permission.CALL_PHONE);
            }
        });
    }
}
View Code

4、这里要注意,安卓在6.0之后是动态申请系统权限,因而封装一个权限的BaseActivity类,专门用于处理权限相关的。

分享图片

分享图片

package com.jiangys.telephonedial;

import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

/**
 * @author Admin
 * @version $Rev$
 * @des ${Todo}
 * @updateAuthor $Author$
 * @updateDes ${Todo}
 */
public class BaseActivity extends AppCompatActivity {
    //**************** Android M Permission (Android 6.0权限控制代码封装)
    private int permissionRequestCode = 88;
    private PermissionCallback permissionRunnable;

    public interface PermissionCallback {
        void hasPermission();

        void nopermission();
    }

    /**
     * Android M运行时权限请求封装
     *
     * @param permissionDes 权限描述
     * @param runnable      请求权限回调
     * @param permissions   请求的权限(数组类型),直接从Manifest中读取相应的值,比如Manifest.permission.WRITE_CONTACTS
     */
    public void performCodeWithPermission(@NonNull String permissionDes,PermissionCallback runnable,@NonNull String... permissions) {
        if (permissions == null || permissions.length == 0)
            return;
        //        this.permissionrequestCode = requestCode;
        this.permissionRunnable = runnable;
        if ((Build.VERSION.SDK_INT < Build.VERSION_CODES.M) || checkPermissionGranted(permissions)) {
            if (permissionRunnable != null) {
                permissionRunnable.hasPermission();
                permissionRunnable = null;
            }
        } else {
            //permission has not been granted.
            requestPermission(permissionDes,permissionRequestCode,permissions);
        }

    }

    private boolean checkPermissionGranted(String[] permissions) {
        boolean flag = true;
        for (String p : permissions) {
            if (ActivityCompat.checkSelfPermission(this,p) != PackageManager.PERMISSION_GRANTED) {
                flag = false;
                break;
            }
        }
        return flag;
    }

    private void requestPermission(String permissionDes,final int requestCode,final String[] permissions) {
        if (shouldShowRequestPermissionRationale(permissions)) {
            /*1. 第一次请求权限时,用户拒绝了,下一次:shouldShowRequestPermissionRationale()  返回 true,应该显示一些为什么需要这个权限的说明
            2.第二次请求权限时,用户拒绝了,并选择了“不在提醒”的选项时:shouldShowRequestPermissionRationale()  返回 false
            3. 设备的策略禁止当前应用获取这个权限的授权:shouldShowRequestPermissionRationale()  返回 false*/
            // Provide an additional rationale to the user if the permission was not granted
            // and the user would benefit from additional context for the use of the permission.
            // For example,if the request has been denied prevIoUsly.

            //            Snackbar.make(getwindow().getDecorView(),requestName,//                    Snackbar.LENGTH_INDEFINITE)
            //                    .setAction(R.string.common_ok,new View.OnClickListener() {
            //                        @Override
            //                        public void onClick(View view) {
            //                            ActivityCompat.requestPermissions(BaseAppCompatActivity.this,//                                    permissions,//                                    requestCode);
            //                        }
            //                    })
            //                    .show();
            //如果用户之前拒绝过此权限,再提示一次准备授权相关权限
            new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage(permissionDes)
                    .setPositiveButton("授权",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog,int which) {
                            ActivityCompat.requestPermissions(BaseActivity.this,permissions,requestCode);
                        }
                    }).show();

        } else {
            // Contact permissions have not been granted yet. Request them directly.
            ActivityCompat.requestPermissions(BaseActivity.this,requestCode);
        }
    }

    private boolean shouldShowRequestPermissionRationale(String[] permissions) {
        boolean flag = false;
        for (String p : permissions) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,p)) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode,@NonNull String[] permissions,@NonNull int[] grantResults) {
        if (requestCode == permissionRequestCode) {
            if (verifyPermissions(grantResults)) {
                if (permissionRunnable != null) {
                    permissionRunnable.hasPermission();
                    permissionRunnable = null;
                }
            } else {
                Toast.makeText(this,"暂无权限执行相关操作!",Toast.LENGTH_SHORT).show();
                if (permissionRunnable != null) {
                    permissionRunnable.nopermission();
                    permissionRunnable = null;
                }
            }
        } else {
            super.onRequestPermissionsResult(requestCode,grantResults);
        }

    }

    public boolean verifyPermissions(int[] grantResults) {
        // At least one result must be checked.
        if (grantResults.length < 1) {
            return false;
        }

        // Verify that each required permission has been granted,otherwise return false.
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
    //********************** END Android M Permission ****************************************
}
View Code

android 手机号码归属地查询 代码

android 手机号码归属地查询 代码

  手机号码归属地查询,涉及 android 数据库操作

\



  源码下载


转载:http://www.adobex.com/android/source/details/00000269.htm

Android 简单几步实现手机号码归属地查询,可监听文本框的变化自动查询

Android 简单几步实现手机号码归属地查询,可监听文本框的变化自动查询

手机号码归属地查询需要用到一个数据库文件,我们可以用小米公司的数据库文件

第一步:数据库文件存储在

data/data/包名/files/数据库文件名.db";下
那么我们要如何在用户安装我们的程序的时候。将数据库文件拷贝到改目录下呢
我们可以将数据库文件放在assets目录下,在程序启动时,将其拷贝到该目录下即可,
数据库文件链接http://pan.baidu.com/s/1pJAa8Kb
将里面的addrees.db拷贝到assets目录下注意,image
assets 应该跟java res在同一级目录中,否则会报找不到数据库文件的错误
拷贝功能函数的实现如下
private void copyDBM() {
Log.i(TAG,"copyDBM");
/*只需拷贝一次*/
try {
//getFilesDir()得到根目录
File file = new File(getFilesDir(), "address.db");
if (file.exists() && file.length() > 0) {
/*已存在,不需要拷贝*/
Log.i(TAG,"不需要拷贝");
} else {
Log.i(TAG,"需要拷贝");
InputStream is = getAssets().open("address.db");
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
}
is.close();
fileOutputStream.close();
}

} catch (IOException e) {
e.printStackTrace();
}

}
查询数据库的工具类如下
package com.zaizai.safty.db.dao;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
* 查询数据库类
* Created by zaizai on 2015/11/4.
*/
public class NumberAddressQueryUtils {

/**
* 传一个号码,返回一个归属地字符串
*
* @param number
* @return
*/
private static String path = "data/data/com.zaizai.safty/files/address.db";
private static SQLiteDatabase database;


public static String queryNumber(String number) {
String address = number;
/*手机号码正则表达式匹配\d代表0到9的数字 ^1[345678]\d{9}*/
if (number.matches("^1[345678]\\d{9}$")) {
/*手机号码*/

//path 把数据库文件拷贝到data/data/<pagename>/files/address.db
database = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
Cursor cursor = database.rawQuery("select location from data2 where id = (select outkey from data1 where id = ?)", new String[]{number.substring(0, 7)});
while (cursor.moveToNext()) {
String location = cursor.getString(0);
address = location;
}
cursor.close();
} else {
// 其他的电话号码
switch (number.length()) {
case 3:
// 110
if ("110".equals(number))
address = "匪警号码";
if ("120".equals(number))
address = "急救电话";
if ("119".equals(number))
address = "火警电话";
break;
case 4:
// 5554
address = "模拟器";
break;
case 5:
// 10086
address = "客服电话";
break;
case 7:
//
address = "本地号码";
break;

case 8:
address = "本地号码";
break;

default:
// /处理长途电话 10
if (number.length() > 10 && number.startsWith("0")) {
// 010-59790386
Cursor cursor = database.rawQuery(
"select location from data2 where area = ?",
new String[]{number.substring(1, 3)});

while (cursor.moveToNext()) {
String location = cursor.getString(0);
address = location.substring(0, location.length() - 2);
}
cursor.close();

// 0855-59790386
cursor = database.rawQuery(
"select location from data2 where area = ?",
new String[]{number.substring(1, 4)});
while (cursor.moveToNext()) {
String location = cursor.getString(0);
address = location.substring(0, location.length() - 2);

}
}

break;
}
}

return address;
}
}

activity代码如下

package com.zaizai.safty;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.zaizai.safty.db.dao.NumberAddressQueryUtils;

import static com.zaizai.safty.R.id.et_phone;

/**
* Created by zaizai on 2015/11/4.
*/
public class NumberAddressQueryActivity extends AppCompatActivity {

private static final String TAG = "zaizai";
private EditText etPhone;
private TextView etResult;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_number_adderss_query);

etPhone = (EditText) findViewById(et_phone);
etResult = (TextView) findViewById(R.id.tv_result);
etPhone.addTextChangedListener(new TextWatcher() {
/**
* 文本变化前回调
* @param s
* @param start
* @param count
* @param after
*/
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {

}

/**
* 文本变化时回调
* @param s
* @param start
* @param before
* @param count
*/
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s != null && s.length() >= 3) {
/*查询数据库,并且显示结果*/
String address = NumberAddressQueryUtils.queryNumber(s.toString());
etResult.setText(address);
}

}

/**
* 文本变化后回调
* @param s
*/

@Override
public void afterTextChanged(Editable s) {

}
});
}

/**
* 点击查询号码归属地
*
* @param view
*/
public void numberAddressQuery(View view) {
String phone = etPhone.getText().toString().trim();
if (TextUtils.isEmpty(phone)) {
Toast.makeText(NumberAddressQueryActivity.this, "号码为空", Toast.LENGTH_LONG).show();
return;
} else {


String address = NumberAddressQueryUtils.queryNumber(phone);
etResult.setText(address);
/*去数据库查询号码归属地*/
//1、网络查询 2、本地数据库查询
/*工具类查询数据库*/

Log.i(TAG, "您要查询的电话号码" + phone);
}
}
}
布局文件如下
<?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:orientation="vertical">

<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="55dip"
android:background="@android:color/holo_green_dark"
android:gravity="center"
android:text="号码归属地的查询"
android:textColor="@android:color/black"
android:textSize="22sp" />

<EditText
android:id="@+id/et_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:ems="10"
android:inputType="phone" />

<Button
android:id="@+id/number_address_qurey"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="numberAddressQuery"
android:text="查询" />

<TextView
android:id="@+id/tv_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示结果" />


</LinearLayout>

今天的关于[android] 手机卫士接收打电话广播显示号码归属地来电播报归属地的分享已经结束,谢谢您的关注,如果想了解更多关于android 之访问WebService显示手机号码归属地、Android 基础-2.0 拔打电话号码、android 手机号码归属地查询 代码、Android 简单几步实现手机号码归属地查询,可监听文本框的变化自动查询的相关知识,请在本站进行查询。

本文标签:

上一篇[android] 切换界面的通用处理(android 页面切换)

下一篇[android] 轮播图-滑动图片标题焦点(轮播图滑动效果)