get Primary Email Account of android phone

前端 未结 5 1168
粉色の甜心
粉色の甜心 2021-02-19 07:38

I am working on a project, and I have to fill the EditText automatically with the user\'s primary email, I am considering primary email as the email that associated with google

5条回答
  •  青春惊慌失措
    2021-02-19 08:25

    Whenever user assign email_id then android create a calendar with Email.So if above solution not turning out for you then you can try this as hack. Find Email associated with Calendar. Hope this will help.

        public String getCalendarIdAndEmail(Context c) {
    
        String projection[] = {"_id", "calendar_displayName"};
        //   Uri calendars = Uri.parse("content://com.android.calendar/calendars");
        String calID = null;
        try {
            ContentResolver contentResolver = c.getContentResolver();
    
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
                return calID;
            }
            Cursor managedCursor = contentResolver.query(CalendarContract.Calendars.CONTENT_URI, projection, CalendarContract.Calendars.VISIBLE + " = 1 AND " + CalendarContract.Calendars.IS_PRIMARY + "=1", null, CalendarContract.Calendars._ID + " ASC");
            if (managedCursor.getCount() <= 0) {
                managedCursor = contentResolver.query(CalendarContract.Calendars.CONTENT_URI, projection, CalendarContract.Calendars.VISIBLE + " = 1", null, CalendarContract.Calendars._ID + " ASC");
            } else {
                Log.d("getCount", "" + managedCursor.getCount());
            }
    
            if (managedCursor.moveToFirst()) {
    
                int nameCol = managedCursor.getColumnIndex(projection[1]);
                int idCol = managedCursor.getColumnIndex(projection[0]);
                do {
                   String calName = managedCursor.getString(nameCol);
                    calID = managedCursor.getString(idCol);
                    //CalName is Email id you are looking for
                    Log.e("tag", "calName " + calName + "____calId " + calID);
    
                } while (managedCursor.hasNext());//managedCursor.moveToNext());
                managedCursor.close();
            }
        } catch (Exception e) {
            Log.e("error", e.getMessage(););
        }
        return calID;
    }
    

提交回复
热议问题