BroadcastReciever仅在进行一次呼叫时检测到两个呼叫

时间:2017-03-31 20:10:18

标签: java android

我已经创建了一个Service类,在该类中我创建了BroadcastReciever,如下所示:

final BroadcastReceiver receiver = new BroadcastReceiver() {
            private ITelephony telephonyService;
            public void onReceive(Context context, Intent intent) {
                TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                try {
                    //Call Rejection
                    Class c = Class.forName(tm.getClass().getName());
                    Method m = c.getDeclaredMethod("getITelephony");
                    m.setAccessible(true);
                    ITelephony telephonyService = (ITelephony) m.invoke(tm);
                    Bundle bundle = intent.getExtras();
                    String phoneNumber = bundle.getString("incoming_number");
                    telephonyService.silenceRinger();
                    telephonyService.endCall();

                    //Checking if number is in contact list
                    String name=findNameByNumber(phoneNumber);
                    if(name.equals("Not Found"))
                    {
                        //Name Not Found
                    }
                    else
                    {
                        //name Found
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

findNameByNumber检查我的联系人列表中是否存在该号码:

private String findNameByNumber(String incomingNumber) {
        String res = "Not Found";
        try {
            ContentResolver resolver = getApplicationContext().getContentResolver();
            Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(incomingNumber));
            Cursor c = resolver.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);

            if (c != null) {
                if (c.moveToFirst()) {
                    res = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                }
                c.close();
            }
        } catch (Exception ex) {
            Toast.makeText(getApplicationContext(),ex.toString(), Toast.LENGTH_SHORT).show();
        }
        return res;
    }

这就是我的IntentFilter对象在Service类中使用接收器的方式:

IntentFilter filter = new IntentFilter();
        filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
        registerReceiver(receiver,filter);

然而,当一个呼叫到来时,它被检测为两个呼叫而不是一个。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

从意图中读取以获得通话状态

这里涉及两个状态变化: 曾经是从空闲到响个不停 其他是从响铃到闲置

post_date