android中黑名单的实现

        说明:由于挂断电话android   api不是对外开放的,所以需要使用反射的方法得到拨打电话的服务。
        1.将android源代码中的"aidl"文件拷贝到项目中
                        这样项目中会生成两个包:android.telephony;此包中文件为:NeighboringCellInfo.aidl
                                                        com.android.internal.telephony;此包中文件为:ITelephony.aidl
        2.通过反射挂断电话;代码如下:
        
/**
	 * 挂断电话
	 */
	public void endCall() {
		try {
			Method method = Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
			IBinder binder = (IBinder) method.invoke(null, new Object[]{TELEPHONY_SERVICE});
			ITelephony telephony = ITelephony.Stub.asInterface(binder);
			telephony.endCall();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
         3.删除通话记录中的记录
         
/**
	 * 删除呼叫记录
	 */
	public void deleteCallLog(String incomingNumber) {
		ContentResolver resolver = getContentResolver();
		Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI, null,"number=?", new String[]{incomingNumber}, null);
		if(cursor.moveToNext()){
			String id = cursor.getString(cursor.getColumnIndex("_id"));
			resolver.delete(CallLog.Calls.CONTENT_URI, "_id=?", new String[]{id});
		}
		
	}
          4.直接这样调用是不能删除电话记录的,因为生成电话记录的过程是一个异步的过程,在挂断电话之后不能立即删除电话记录,所以这里要使用ContentObserver(内容观察者)
private class MyObserver extends ContentObserver{
		private String incomingNumber;
		public MyObserver(Handler handler,String incomingNumber) {
			super(handler);
			this.incomingNumber = incomingNumber;
		}
		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			deleteCallLog(incomingNumber);
			
			getContentResolver().unregisterContentObserver(this);
		}
	}

        6.最后把整个service代码贴到下面
        
public class AddressService extends Service{
	
	private static final String TAG = "AddressService";
	
	
	private TelephonyManager manager;
	private MyPhoneListener listener;
	private WindowManager wManager;
	private View view;
	private SharedPreferences sp;
	long startTime = 0;
	long endTime = 0;
	private BlackNumberDao dao;
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	/**
	 * 服务第一次被创建的时候调用的方法
	 * 服务被初始化时调用的方法
	 */
	@Override
	public void onCreate() {
		super.onCreate();
		listener = new MyPhoneListener();
		manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		wManager = (WindowManager) this.getSystemService(WINDOW_SERVICE);
		manager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
		sp = getSharedPreferences("config", MODE_PRIVATE);
		dao = new BlackNumberDao(this);
//		if(3000>(endTime - startTime)){
//			String ns = Context.NOTIFICATION_SERVICE;
//			NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
//			//定义通知栏展现的内容信息
//			int icon = R.drawable.icon5;
//			CharSequence tickerText = "我的通知栏标题";
//			long when = System.currentTimeMillis();
//			Notification notification = new Notification(icon, tickerText, when);
//			//定义下拉通知栏时要展现的内容信息
//			Context context = getApplicationContext();
//			CharSequence contentTitle = "我的通知栏标展开标题";
//			CharSequence contentText = "我的通知栏展开详细内容";
//			Intent notificationIntent = new Intent(AddressService.this,BootStartDemo.class);
//			PendingIntent contentIntent = PendingIntent.getActivity(AddressService.this, 0,notificationIntent, 0);
//			notification.setLatestEventInfo(context, contentTitle, contentText,contentIntent);
//			//用mNotificationManager的notify方法通知用户生成标题栏消息通知
//			mNotificationManager.notify(1, notification);
//		}
	}
	
	/**
	 * 服务停止的时候调用
	 */
	@Override
	public void onDestroy() {
		super.onDestroy();
		manager.listen(listener, PhoneStateListener.LISTEN_NONE);
		listener = null;
	}

	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(null != view){
					wManager.removeView(view);
					view = null;
				}
				endTime = System.currentTimeMillis();
				break;
			case TelephonyManager.CALL_STATE_RINGING: // 零响状态
				//判断number是否在黑名单中
				if(dao.find(incomingNumber)){
					//挂断电话
					endCall();
					//删除呼叫记录
//					deleteCallLog(incomingNumber);
					
					ContentResolver resolver = getContentResolver();
					resolver.registerContentObserver(CallLog.Calls.CONTENT_URI, true, new MyObserver(new Handler(),incomingNumber));
				}
				
				Log.i(TAG,"来电号码为"+ incomingNumber);
				String address = NumberAddressService.getAddress(incomingNumber);
				Log.i(TAG,"归属地为"+ address);
				showLocation(address);
				//获取当前系统的时间
				startTime = System.currentTimeMillis();
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK: //接通电话状态
				
				break;

			}
		}
		
	}

	/**
	 * 在窗体上显示出来位置信息
	 * @param address
	 */
	public void showLocation(String address) {
	    WindowManager.LayoutParams params = new WindowManager.LayoutParams();
	    params.height = WindowManager.LayoutParams.WRAP_CONTENT;
	    params.width = 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");
	    params.gravity = Gravity.LEFT | Gravity.TOP;
	    int x = sp.getInt("lastx", 0);
	    int y = sp.getInt("lasty", 0);
	    params.x = x;
	    params.y = y;
	    view = View.inflate(getApplicationContext(), R.layout.show_location, null);
	    LinearLayout ll_location = (LinearLayout) view.findViewById(R.id.ll_location);
	    TextView tv_location = (TextView) view.findViewById(R.id.tv_location);
	    
	    int background = sp.getInt("background", 0);
	    if(0 == background){
	    	ll_location.setBackgroundResource(R.drawable.call_locate_gray);
	    }else if(1 == background){
	    	ll_location.setBackgroundResource(R.drawable.call_locate_orange);
	    }else {
	    	ll_location.setBackgroundResource(R.drawable.call_locate_green);
	    }
	    
	    tv_location.setText(address);
	    tv_location.setTextSize(24);
	    wManager.addView(view, params);
	    
	}
	
	/**
	 * 删除呼叫记录
	 */
	public void deleteCallLog(String incomingNumber) {
		ContentResolver resolver = getContentResolver();
		Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI, null,"number=?", new String[]{incomingNumber}, null);
		if(cursor.moveToNext()){
			String id = cursor.getString(cursor.getColumnIndex("_id"));
			resolver.delete(CallLog.Calls.CONTENT_URI, "_id=?", new String[]{id});
		}
		
	}

	/**
	 * 挂断电话
	 */
	public void endCall() {
		try {
			Method method = Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
			IBinder binder = (IBinder) method.invoke(null, new Object[]{TELEPHONY_SERVICE});
			ITelephony telephony = ITelephony.Stub.asInterface(binder);
			telephony.endCall();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	private class MyObserver extends ContentObserver{
		private String incomingNumber;
		public MyObserver(Handler handler,String incomingNumber) {
			super(handler);
			this.incomingNumber = incomingNumber;
		}
		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			deleteCallLog(incomingNumber);
			
			getContentResolver().unregisterContentObserver(this);
		}
	}
}

你可能感兴趣的:(android中黑名单的实现)