دمج ميزة "تسجيل الدخول باستخدام حساب Google" في تطبيق Android
تنظيم صفحاتك في مجموعات
يمكنك حفظ المحتوى وتصنيفه حسب إعداداتك المفضّلة.
لدمج ميزة "تسجيل الدخول باستخدام حساب Google" في تطبيق Android، عليك ضبط إعدادات هذه الميزة وإضافة زر إلى تصميم تطبيقك لبدء عملية تسجيل الدخول.
قبل البدء
إعداد مشروع على Google API Console وإعداد مشروعك على "استوديو Android"
ضبط ميزة "تسجيل الدخول باستخدام حساب Google" وكائن GoogleSignInClient
في طريقة onCreate لنشاط تسجيل الدخول، اضبط ميزة "تسجيل الدخول باستخدام حساب Google" لطلب بيانات المستخدم المطلوبة من تطبيقك. على سبيل المثال، لضبط ميزة "تسجيل الدخول باستخدام حساب Google" لطلب معرّف المستخدم ومعلومات الملف الشخصي الأساسية، أنشئ عنصر GoogleSignInOptions مع المَعلمة DEFAULT_SIGN_IN. لطلب عناوين البريد الإلكتروني الخاصة بالمستخدمين أيضًا، أنشئ عنصر GoogleSignInOptions باستخدام الخيار requestEmail.
// Configure sign-in to request the user's ID, email address, and basic// profile. ID and basic profile are included in DEFAULT_SIGN_IN.GoogleSignInOptionsgso=newGoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
إذا كنت بحاجة إلى طلب نطاقات إضافية للوصول إلى واجهات Google APIs، حدِّدها باستخدام requestScopes.
لتقديم أفضل تجربة للمستخدم، لا تطلب عند تسجيل الدخول سوى النطاقات المطلوبة لكي يعمل تطبيقك بشكل أساسي. يجب طلب أي نطاقات إضافية فقط عند الحاجة إليها، حتى يرى المستخدمون شاشة الموافقة في سياق إجراء نفّذوه.
اطّلِع على طلب نطاقات إضافية.
بعد ذلك، أنشئ عنصر GoogleSignInClient باستخدام الخيارات التي حدّدتها، وذلك أيضًا في طريقة onCreate الخاصة بنشاط تسجيل الدخول.
// Build a GoogleSignInClient with the options specified by gso.mGoogleSignInClient=GoogleSignIn.getClient(this,gso);
التحقّق من وجود مستخدم حالي مسجّل الدخول
في طريقة onStart الخاصة بنشاطك، تحقَّق ممّا إذا كان المستخدم قد سجّل الدخول إلى تطبيقك باستخدام Google.
// Check for existing Google Sign In account, if the user is already signed in// the GoogleSignInAccount will be non-null.GoogleSignInAccountaccount=GoogleSignIn.getLastSignedInAccount(this);updateUI(account);
إذا عرضت GoogleSignIn.getLastSignedInAccount الكائن GoogleSignInAccount
(بدلاً من null)، يعني ذلك أنّ المستخدم قد سجّل الدخول إلى تطبيقك باستخدام Google.
عدِّل واجهة المستخدم وفقًا لذلك، أي أخفِ زر تسجيل الدخول أو شغِّل نشاطك الرئيسي أو أي شيء آخر مناسب لتطبيقك.
إذا عرضت GoogleSignIn.getLastSignedInAccount القيمة null، يعني ذلك أنّ المستخدم لم يسجّل الدخول إلى تطبيقك باستخدام Google بعد. عدِّل واجهة المستخدم لعرض زر "تسجيل الدخول باستخدام حساب Google".
إضافة زر "تسجيل الدخول باستخدام حساب Google" إلى تطبيقك
اختياري: إذا كنت تستخدم الرسم التلقائي لزر تسجيل الدخول بدلاً من توفير مواد عرض خاصة بك لزر تسجيل الدخول، يمكنك تخصيص حجم الزر باستخدام طريقة setSize.
// Set the dimensions of the sign-in button.SignInButtonsignInButton=findViewById(R.id.sign_in_button);signInButton.setSize(SignInButton.SIZE_STANDARD);
في نشاط Android (على سبيل المثال، في طريقة onCreate)، سجِّل OnClickListener الزر لتسجيل دخول المستخدم عند النقر عليه:
في طريقة onClick الخاصة بالنشاط، عالِج عمليات النقر على زر تسجيل الدخول من خلال إنشاء
نية تسجيل دخول باستخدام الطريقة getSignInIntent،
وبدء النية باستخدام startActivityForResult.
يؤدي بدء الغرض إلى مطالبة المستخدم باختيار حساب Google لتسجيل الدخول إليه. إذا طلبت نطاقات تتجاوز profile وemail وopenid، سيُطلب من المستخدم أيضًا منح إذن الوصول إلى الموارد المطلوبة.
بعد أن يسجّل المستخدم الدخول، يمكنك الحصول على عنصر GoogleSignInAccount
للمستخدم في طريقة onActivityResult الخاصة بالنشاط.
يمكنك أيضًا الحصول على عنوان البريد الإلكتروني للمستخدم باستخدام getEmail،
ومعرّف Google الخاص بالمستخدم (للاستخدام من جهة العميل) باستخدام getId،
ورمز مميّز للمعرّف الخاص بالمستخدم باستخدام getIdToken.
إذا كنت بحاجة إلى تمرير المستخدم الذي سجّل الدخول حاليًا إلى خادم الخلفية،
أرسِل الرمز المميّز لتعريف الهوية إلى خادم الخلفية
وأثبِت صحة الرمز المميّز على الخادم.
يخضع كل من المحتوى وعيّنات التعليمات البرمجية في هذه الصفحة للتراخيص الموضحّة في ترخيص استخدام المحتوى. إنّ Java وOpenJDK هما علامتان تجاريتان مسجَّلتان لشركة Oracle و/أو الشركات التابعة لها.
تاريخ التعديل الأخير: 2025-07-27 (حسب التوقيت العالمي المتفَّق عليه)
[[["يسهُل فهم المحتوى.","easyToUnderstand","thumb-up"],["ساعَدني المحتوى في حلّ مشكلتي.","solvedMyProblem","thumb-up"],["غير ذلك","otherUp","thumb-up"]],[["لا يحتوي على المعلومات التي أحتاج إليها.","missingTheInformationINeed","thumb-down"],["الخطوات معقدة للغاية / كثيرة جدًا.","tooComplicatedTooManySteps","thumb-down"],["المحتوى قديم.","outOfDate","thumb-down"],["ثمة مشكلة في الترجمة.","translationIssue","thumb-down"],["مشكلة في العيّنات / التعليمات البرمجية","samplesCodeIssue","thumb-down"],["غير ذلك","otherDown","thumb-down"]],["تاريخ التعديل الأخير: 2025-07-27 (حسب التوقيت العالمي المتفَّق عليه)"],[],[],null,["# Integrate Google Sign-In into Your Android App\n\n| **Warning:**\n|\n| **The Google Sign-In for Android API is outdated and no longer supported.**\n| To ensure the continued security and usability of your app, [migrate your Sign in with\n| Google implementation to Credential Manager](/identity/sign-in/credential-manager-siwg) today. Credential Manager\n| supports passkey, password, and federated identity authentication (such as\n| Sign-in with Google), stronger security, and a more consistent user\n| experience.\n|\n| **For Wear developers:** Credential Manager will be supported in Wear OS\n| 5.1 and later on selected watches. Developers actively supporting Wear OS 3, 4\n| and 5.0 devices with Sign in with Google should continue using Google Sign-in\n| for Android for your Wear applications. Sign in with Google support will be\n| available on Credential Manager APIs for these versions of WearOS at a later\n| date.\n\nTo integrate Google Sign-In into your Android app, configure Google Sign-In and\nadd a button to your app's layout that starts the sign-in flow.\n\nBefore you begin\n----------------\n\nConfigure a Google API Console project and set up your Android Studio project.\n\nConfigure Google Sign-in and the GoogleSignInClient object\n----------------------------------------------------------\n\n1. In your sign-in activity's `onCreate` method, configure Google Sign-In to\n request the user data required by your app. For example, to configure\n Google Sign-In to request users' ID and basic profile information, create a\n [`GoogleSignInOptions`](https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInOptions.Builder.html#GoogleSignInOptions.Builder())\n object with the `DEFAULT_SIGN_IN` parameter. To request users' email\n addresses as well, create the `GoogleSignInOptions` object with the\n `requestEmail` option.\n\n ```carbon\n // Configure sign-in to request the user's ID, email address, and basic\n // profile. ID and basic profile are included in DEFAULT_SIGN_IN.\n GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)\n .requestEmail()\n .build();\n ```\n\n If you need to request additional scopes to access Google APIs, specify them\n with [`requestScopes`](https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInOptions.Builder.html#requestScopes(com.google.android.gms.common.api.Scope,%20com.google.android.gms.common.api.Scope...)).\n For the best user experience, on sign-in, only request the scopes that are\n required for your app to minimally function. Request any additional scopes\n only when you need them, so that your users see the consent screen in the\n context of an action they performed.\n See [Requesting Additional Scopes](https://developers.google.com/identity/sign-in/android/additional-scopes).\n2. Then, also in your sign-in activity's `onCreate` method, create a\n `GoogleSignInClient` object with the options you specified.\n\n ```scilab\n // Build a GoogleSignInClient with the options specified by gso.\n mGoogleSignInClient = GoogleSignIn.getClient(this, gso);\n ```\n\nCheck for an existing signed-in user\n------------------------------------\n\nIn your activity's `onStart` method, check if a user has already signed in to\nyour app with Google. \n\n```scilab\n// Check for existing Google Sign In account, if the user is already signed in\n// the GoogleSignInAccount will be non-null.\nGoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);\nupdateUI(account);\n```\n\nIf `GoogleSignIn.getLastSignedInAccount` returns a `GoogleSignInAccount` object\n(rather than `null`), the user has already signed in to your app with Google.\nUpdate your UI accordingly---that is, hide the sign-in button, launch your\nmain activity, or whatever is appropriate for your app.\n\nIf `GoogleSignIn.getLastSignedInAccount` returns `null`, the user has not yet\nsigned in to your app with Google. Update your UI to display the Google Sign-in\nbutton.\n| **Note:** If you need to detect changes to a user's auth state that happen outside your app, such as access token or ID token revocation, or to perform cross-device sign-in, you might also call `GoogleSignInClient.silentSignIn` when your app starts.\n\nAdd the Google Sign-in button to your app\n-----------------------------------------\n\n1.\n Add the [`SignInButton`](https://developers.google.com/android/reference/com/google/android/gms/common/SignInButton)\n in your application's layout:\n\n \u003ccom.google.android.gms.common.SignInButton\n android:id=\"@+id/sign_in_button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" /\u003e\n\n2. **Optional** : If you are using the default sign-in button graphic instead of\n providing your own sign-in button assets, you can customize the button's\n size with the [`setSize`](https://developers.google.com/android/reference/com/google/android/gms/common/SignInButton.html#setSize(int))\n method.\n\n ```scilab\n // Set the dimensions of the sign-in button.\n SignInButton signInButton = findViewById(R.id.sign_in_button);\n signInButton.setSize(SignInButton.SIZE_STANDARD);\n ```\n3. In the Android activity (for example, in the `onCreate` method), register\n your button's `OnClickListener` to sign in the user when clicked:\n\n findViewById(R.id.sign_in_button).setOnClickListener(this);\n\nStart the sign-in flow\n----------------------\n\n1.\n In the activity's `onClick` method, handle sign-in button taps by creating a\n sign-in intent with the [`getSignInIntent`](https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInClient#getSignInIntent())\n method, and starting the intent with `startActivityForResult`.\n\n @Override\n public void onClick(View v) {\n switch (v.getId()) {\n case R.id.sign_in_button:\n signIn();\n break;\n // ...\n }\n }\n\n ```scdoc\n private void signIn() {\n Intent signInIntent = mGoogleSignInClient.getSignInIntent();\n startActivityForResult(signInIntent, RC_SIGN_IN);\n }\n ```\n\n Starting the intent prompts the user to select a Google Account to sign in\n with. If you requested scopes beyond `profile`, `email`, and `openid`, the\n user is also prompted to grant access to the requested resources.\n2. After the user signs in, you can get a [`GoogleSignInAccount`](https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInAccount.html)\n object for the user in the activity's `onActivityResult` method.\n\n ```transact-sql\n @Override\n public void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n\n // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);\n if (requestCode == RC_SIGN_IN) {\n // The Task returned from this call is always completed, no need to attach\n // a listener.\n Task\u003cGoogleSignInAccount\u003e task = GoogleSignIn.getSignedInAccountFromIntent(data);\n handleSignInResult(task);\n }\n }\n ```\n\n The `GoogleSignInAccount` object contains information about the signed-in\n user, such as the user's name. \n\n ```css+lasso\n private void handleSignInResult(Task\u003cGoogleSignInAccount\u003e completedTask) {\n try {\n GoogleSignInAccount account = completedTask.getResult(ApiException.class);\n\n // Signed in successfully, show authenticated UI.\n updateUI(account);\n } catch (ApiException e) {\n // The ApiException status code indicates the detailed failure reason.\n // Please refer to the GoogleSignInStatusCodes class reference for more information.\n Log.w(TAG, \"signInResult:failed code=\" + e.getStatusCode());\n updateUI(null);\n }\n }\n ```\n\n You can also get the user's email address with [`getEmail`](https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInAccount.html#getEmail()),\n the user's Google ID (for client-side use) with [`getId`](https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInAccount.html#getId()),\n and an ID token for the user with [`getIdToken`](https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInAccount.html#getIdToken()).\n If you need to pass the currently signed-in user to a backend server,\n [send the ID token to your backend server](https://developers.google.com/identity/sign-in/android/backend-auth)\n and validate the token on the server."]]