2017-04-05 52 views
0

我在嘗試創建應用程序。匹配被叫號碼的方法

首先,按Button獲取地址簿的電話號碼並保存。

然後,每次來電時,它都會檢查保存的電話號碼,如果不在地址簿中,則會發出警告。

使用領域,存儲通訊簿的電話號碼是成功的。 但是,如果我在真實機器上接聽來電,應用程序將被強行終止。

我不知道驗證電話號碼的方法是否不正確,我無法檢索保存的電話號碼,或者它需要太多時間。 給我建議,以改進

MainActivity.java

public class MainActivity extends AppCompatActivity { 

PhoneReceiver phoneStateListener; 
TelephonyManager manager; 

public Button getPhoneList; 

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

    phoneStateListener = new PhoneReceiver(this); 
    manager = ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)); 

    getPhoneList = (Button)this.findViewById(R.id.phoneList); 
    getPhoneList.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      CreatePhoneNumbers(); 
     } 
    }); 
    } 

public void CreatePhoneNumbers() { 
    final Cursor addressTable = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); 
    RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this).build(); 
    Realm realm = Realm.getInstance(realmConfiguration); 
    User user = new User(); 
    if (addressTable != null) { 
     while (addressTable.moveToNext()) { 
      realm.executeTransaction(new Realm.Transaction(){ 
       @Override 
       public void execute(Realm realm) { 
        User u = realm.createObject(User.class); 
        u.setPhoneNumber(addressTable.getString(addressTable.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))); 
        Log.d("Data", u.toString()); 
       } 
      }); 
     } 
     realm.close(); 
     addressTable.close(); 
    } 
} 
} 

PhoneReceiver.java

class PhoneReceiver extends PhoneStateListener { 

private Context context; 
PhoneReceiver(Context context) { 
    this.context = context; 
} 

@Override 
public void onCallStateChanged(int state, String incomingNumber) { 
    super.onCallStateChanged(state, incomingNumber); 

    switch (state) { 
     case TelephonyManager.CALL_STATE_RINGING: 

      RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(context).build(); 
      Realm realm = Realm.getInstance(realmConfiguration); 
      RealmQuery<User> results = realm.where(User.class).equalTo("phoneNumber", incomingNumber); 
      int count = (int) results.count(); 

      if (count > 0) { 
       Toast.makeText(context, "Calling" + incomingNumber, Toast.LENGTH_LONG).show(); 
      } else { 
       Dialog(); 
      } 
      break; 
     case TelephonyManager.CALL_STATE_OFFHOOK: 
      Toast.makeText(context, "Offhook!!" + incomingNumber, Toast.LENGTH_LONG).show(); 
      break; 
    } 
} 
} 
+0

'應用程序將被強行終止' - 必須有一個錯誤日誌。 – Wizard

回答

1

查找PhoneUtils類和比較這兩個數字爲:

PhoneNumberUtils

比較(一個字符串,字符串二)

比較的電話號碼a和b,返回真 如果他們呼叫者ID的目的不夠一致。

+0

非常感謝。我想的很複雜。我會試一試。 – RNagam