I'm trying to make an application.
First, press the Button
to obtain the phone numbers of the address book and save them.
Then, every time a call comes in, it checks against the saved phone numbers and warns if it is not in the address book.
Using realm, storing the phone number of the address book was successful. However, if I put an incoming call on the real machine, the application will be forcibly terminated.
I do not know whether the method to verify the phone number is incorrect, I can not retrieve the saved phone number, or it takes too much time. Give me advice to improve
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;
}
}
}
Look for PhoneUtils class and compare the two number as:
compare(String a, String b)
Compare phone numbers a and b, return true if they're identical enough for caller ID purposes.