手机安全卫士------显示来电归属地的操作

来源:互联网 发布:2015各省医药行业数据 编辑:程序博客网 时间:2024/05/10 11:46

思路:

1.由于我们不确定什么时候会有来电,所以,我们应该使用服务监听来电。

2.服务关闭的时候要取消监听

3.通过服务的开启和关闭控制设置页面上CheckBox状态。

通过服务来监听来电信息

  • 创建一个类,继承自Service
  • 在onCreate方法中,执行对来电的监听操作:
    1) TelePhonyManager manager = getSystemService(TELEPHONY_SERVICE);
    2) manager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
    其中,第一个参数为PhoneStateListener的对象。
    第二个参数设置我们要监听神马~

写一个内部类,继承自PhoneStateListener
重写onCallStateChanged方法,这个方法会在会话发生变化时回调。
在其中判断状态是否为来电,如果为来电状态,获取来电号码,通过号码获取归属地。

最后,在onDestroy中,对监听服务进行关闭。
manager.listen(listener,PhoneStatListener.LISTEN_NONE);

具体实现代码:
public class CallService extends Service
{
private TelephonyManager manager;
private MyPhoneStateListener listener;
public CallService() {
}

public IBinder onBind(Intent intent) {    return null;}private class MyPhoneStateListener extends PhoneStateListener{    //当电话状态发生变化的时候 , 回调    public void onCallStateChanged(int state, String incomingNumber) {        super.onCallStateChanged(state, incomingNumber);        switch (state)        {            case TelephonyManager.CALL_STATE_RINGING:                String location = QueryNumberUtils.getLocationByNumber(incomingNumber);                Toast.makeText(getApplicationContext(),location,Toast.LENGTH_LONG).show();                break;        }    }}public void onCreate(){    super.onCreate();    //监听来电    manager = (TelephonyManager) getApplicationContext().getSystemService(TELEPHONY_SERVICE);    manager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);}public void onDestroy(){    super.onDestroy();    manager.listen(listener,PhoneStateListener.LISTEN_NONE);    manager = null;}

}

判断Service是否开启

创建一个方法:
serviceIsWorking(Context context,String serviceName)
{
//获取一个管理器
ActivityManager am = context.getSystemService(Context.ACTIVITY_SERVICE);
//获得服务信息

List<RunningServiceInfo> infos =  am.getRunningServices(100);

//遍历服务
for(RunningServiceInfo info : infos)
//通过info.service.getClassName() 和 服务类名进行对比
如果相同返回true。

}

判断一个服务是否开启
最终的实现代码:

public static boolean serviceIsWorking(Context context,String serviceName)    {        //创建一个组件管理器,获取到系统服务        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);        //获取到正在运行的服务信息        List<ActivityManager.RunningServiceInfo> infos = manager.getRunningServices(100);        //遍历        if(infos != null) {            for (ActivityManager.RunningServiceInfo info : infos) {                //获取Service名字                String name = info.service.getClassName();                if (serviceName.equals(name)) {                    return true;                }            }        }        return false;    }
0 0
原创粉丝点击