Wednesday 5 June 2013

Android - How to get device Phone Number in Android


How to get device Phone Number in Android


Step 1:  put code in .java file
               TelephonyManager mTelephonyMgr;  
            mTelephonyMgr = (TelephonyManager)        getSystemService(Context.TELEPHONY_SERVICE);   

                String yourNumber = mTelephonyMgr.getLine1Number();
                Toast.makeText(getApplicationContext(), "Your Phone Number is = " + yourNumber , Toast.LENGTH_LONG).show();


Step 2:  For Getting Phone Number Permission is given in AndroidManifest.xml

         <uses-permission android:name="android.permission.READ_PHONE_STATE" />

Android - To check whether the contact exists in Contact list or not


To check whether the contact exists in Contact list or not


If you are working with contact related application like Contact Backup & Restore application, and you want to check to check whether the contact exists in contact list or not, then you must go for this.

Step-1 :  In your activity, use contactExists() function for checking particular contact exist or not.
public class Conatclist extends Activity {
  @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.conatct);
    //Check if contact is already exists or not in Contact list
       if(contactExists(this,"4561237890"))
    {
    Toast.makeText(GanzfeldActivity.this,"exists",Toast.LENGTH_SHORT).show();
          
    }
    else
    {
    Toast.makeText(GanzfeldActivity.this," not exists",Toast.LENGTH_SHORT).show();
    }
}
public  boolean contactExists(Activity _activity,String number){
  Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,Uri.encode(number));
String[] mPhoneNumberProjection = { PhoneLookup._ID, PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME };
Cursor cur = _activity.getContentResolver().query(lookupUri,mPhoneNumberProjection, null, null, null);
 try {
    if (cur.moveToFirst()) {
      // if contact are in contact list it will return true
      return true;
   }} finally {
       if (cur != null)
          cur.close();
  }
     //if contact are not match that means contact are not added
    return false;
}
}

Step-2: For accessing contact detail , you need to give permission in android manifest file.

<uses-permission android:name="android.permission.READ_CONTACTS" />