好啦,我们今天就要把号码归属地显示在有电话打进来的时候,其实也很简单的啦,我们只要开一个服务,监听电话的广播,然后在电话相应的状态,进行相应的操作就可以的啦
至于怎样把那个view显示到接听电话那个界面上,这个更简单啦,那个Toast是怎样显示的,我们就怎样显示就可以了。
我们打开Toast的源码,可以发现在一个静态的内部类TN里面,有这样一段代码
其实这一段就是设置好我们的Toast而已的代码啦,我们可以参照着来写一下
好啦,我们就要修改上一次写的AddressService这个类啦,
package com.xiaobin.security.service; import android.app.Service; import android.content.Context; import android.content.Intent; import android.graphics.PixelFormat; import android.os.IBinder; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.view.WindowManager; import android.widget.TextView; import com.xiaobin.security.engine.NumberAddressService; public class AddressService extends Service { private TelephonyManager telephonyManager; private MyPhoneListener listener; private WindowManager windowManager; private TextView tv; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); listener = new MyPhoneListener(); telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE); } @Override public void onDestroy() { super.onDestroy(); //停止监听 telephonyManager.listen(listener, PhoneStateListener.LISTEN_NONE); } //显示归属地的窗体 private void showLocation(String address) { WindowManager.LayoutParams params = new WindowManager.LayoutParams(); params.width = WindowManager.LayoutParams.WRAP_CONTENT; params.height = WindowManager.LayoutParams.WRAP_CONTENT; params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE //无法获取焦点 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE //无法点击 | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;//保持屏幕亮 params.format = PixelFormat.TRANSLUCENT;//设置成半透明的 params.type = WindowManager.LayoutParams.TYPE_TOAST; params.setTitle("Toast"); tv = new TextView(AddressService.this); tv.setText("归属地: " + address); windowManager.addView(tv, params); } //======================================================================== private class MyPhoneListener extends PhoneStateListener { @Override public void onCallStateChanged(int state, String incomingNumber) { super.onCallStateChanged(state, incomingNumber); switch(state) { case TelephonyManager.CALL_STATE_IDLE : //空闲状态 if(tv != null) { windowManager.removeView(tv);//移除显示归属地的那个view tv = null; } break; case TelephonyManager.CALL_STATE_OFFHOOK : //接通电话 if(tv != null) { windowManager.removeView(tv);//移除显示归属地的那个view tv = null; } break; case TelephonyManager.CALL_STATE_RINGING : //铃响状态 String address = NumberAddressService.getAddress(incomingNumber); showLocation(address); break; default : break; } } } }
就这样,我们的app就会在有电话进来的时候,把电话的归属地显示出来的啦
但是记得在测试的时候,记得把我们上一次写的那个开启服务的CheckBox勾上,不然就不会显示出来的啦
好啦,今天的代码比较简单,就到这里,下一次,我们就美化一下这个显示框,加入风格的选择
今天源码下载