Android sign in activity

How to Create User Interface Login & Register with Android Studio

ok, this is my first article in Medium. In this section, I want to share with you about the User Interface on Android and we will create a Login page and a Register page. Some components that I will use:
1. Viewpager
2. Fragment
3. Edittext
4. Button
5. Textview
6. Imageview

What about the results? let’s coding (follow step by step)

  1. Of course we must already have an Android Studio. if not, you can download it first on the official Android Studio website. If you already have one, please open your Android studio.

2. We create a new project by clicking “Start a new Android Studio project”. Fill in the application name column with “LoginApp”, then click next.

3. Select the minimum SDK you need or want, then click next.

4. Select “Empty Activity” and click next. After that, the “Activity Name” and “Layout Name” columns will appear, in this section just leave it like that, then click finish.

After you click finish, Android Studio will make you an Application with the name “LoginApp”.

After the application is successfully built, you can simply make adjustments to the following sections:

Open the colors.xml file in app/res/values/colors.xml, and change it like this:

Create a folder with the name “font” in the res folder, by right clicking on the res directory, select new / directory and name it “font”. After that, copy this font into font directory. (download the font 1 and font 2).

Create some Drawable Resource File in the drawable directory, by right-clicking on the drawable directory, select new / Drawable Resource File.

After that open file styles.xml and change like this :

Add the theme property in the Main Activity in the manifest, in the app / manifests / AndroidManifest.xml folder

So the AndroidManifest.xml file will be as follows:

After all the steps above are done, then make 2 fragments with the name fragment_login and fragment_register in the layout directory, by right-clicking on the layout directory, New/Fragment/Fragment (Blank)

Uncheck:
include fragment factory methods? and include interface methods?

Adjustment of several layouts :

change the activity_main.xml layout, fragment_login.xml and fragment_register.xml so that it will be as below

Open the strings.xml file in the res / values / strings.xml directory and change it to something like the following :

So that the overall structure of the project will be as follows :

Connect fragments with viewpager

Create an inner class in the MainActivity.java class with the name AuthenticationPapterAdapter. This class is a derivative of the FragmentPagerAdapter class and serves to connect Fragments with ViewPager,

Then call the class in the onCreate() method in MainActivity.java and connect with viewpager

So the MainActivity.java class will be like this

The display of the final application will be like this

Источник

New Google Sign-In API

Google Identity Services (GIS) is a new set of APIs that provides users easy and secure sign-in and sign-up, in an easy-to-implement package for developers. This document details a new Google sign in API (part of GIS) that can be used to start the sign-in or sign-up flow when a user taps on a «Sign-In with Google» button. This API can be used instead of the existing Google Sign-In APIs for sign in flows.

You should use this API only when the user explicitly shows intent to sign in with Google. For example, use this API when they click a «Sign in with Google» button in your app.

You should not use this API to prompt the user to sign-in on app launch or in response to another trigger such as adding an item to the shopping cart. For these use cases, use One Tap sign-in and sign-up.

Читайте также:  Виджеты для андроида 4pda

When you start the Google Sign-In flow with the new API, it will display this UI:

Before you begin

Make a sign-in request

To launch a Google Sign-In flow using the Identity API build a GetSignInRequest object. Then, on a SignInClient object call getSignInIntent . This call is async and on success it will provide a PendingIntent to launch the dialog.

Handle sign in results

In onActivityResult retrieve a SignInCredential . The SignInCredential object returned from getSignInCredentialFromIntent contains information about a valid login. If the user fails to log in for some reason, an ApiException is thrown.

The result of a successful sign in always returns the users full name, email, and profile picture url. If you need additional information you can direct users into a complete profile information flow.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Источник

Try Sign-In for Android

Use our Android sample app to see how Sign-In works, or add Sign-In to your existing app.

Get the project

If this is your first time using a Google services sample, check out the google-services repository.

Open Android Studio.

Select File > Open, browse to where you cloned the google-services repository, and open google-services/android/signin .

Configure a Google API project

To use the sample, you need to provide some additional information to finish setting up your project. Click the button below, and specify the package name com .google .samples .quickstart .signin when prompted. You will also need to provide the SHA-1 hash of your signing certificate. See Authenticating Your Client for information.

The sample’s IdTokenActivity and ServerAuthCodeActivity examples require you to specify an OAuth 2.0 web client ID. In a real app, this client ID would represent your app’s backend server. A client ID for this purpose was created when you configured the project above.

Find this value by opening the Google API Console:

Your web server client ID is displayed next to Web client (Auto-created for Google Sign-in). Copy and paste the client ID into your project’s strings.xml file:

Run the sample

Now you’re ready to build the sample and run it from Android Studio.

Build the sample and click the run button and select a connected device or emulator with the latest version of Google Play services.

How it works

The application builds a GoogleSignInClient , specifying the sign-in options it needs. Then, when the sign-in button is clicked, the application starts the sign-in intent, which prompts the user to sign in with a Google account.

Next steps

If you want to see how you can implement Google Sign-In in your own app, take a look at our implementation guide.

Did you have a good experience? Run into trouble? Let us know!

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Источник

Integrating Google Sign-In into Your Android App

To integrate Google Sign-In into your Android app, configure Google Sign-In and add a button to your app’s layout that starts the sign-in flow.

Before you begin

Configure Google Sign-in and the GoogleSignInClient object

In your sign-in activity’s onCreate method, configure Google Sign-In to request the user data required by your app. For example, to configure Google Sign-In to request users’ ID and basic profile information, create a GoogleSignInOptions object with the DEFAULT_SIGN_IN parameter. To request users’ email addresses as well, create the GoogleSignInOptions object with the requestEmail option.

If you need to request additional scopes to access Google APIs, specify them with requestScopes . For the best user experience, on sign-in, only request the scopes that are required for your app to minimally function. Request any additional scopes only when you need them, so that your users see the consent screen in the context of an action they performed. See Requesting Additional Scopes.

Читайте также:  Fly tv для андроид не работает

Then, also in your sign-in activity’s onCreate method, create a GoogleSignInClient object with the options you specified.

Check for an existing signed-in user

In your activity’s onStart method, check if a user has already signed in to your app with Google.

If GoogleSignIn.getLastSignedInAccount returns a GoogleSignInAccount object (rather than null ), the user has already signed in to your app with Google. Update your UI accordingly—that is, hide the sign-in button, launch your main activity, or whatever is appropriate for your app.

If GoogleSignIn.getLastSignedInAccount returns null , the user has not yet signed in to your app with Google. Update your UI to display the Google Sign-in button.

Add the Google Sign-in button to your app

Add the SignInButton in your application’s layout:

Optional: If you are using the default sign-in button graphic instead of providing your own sign-in button assets, you can customize the button’s size with the setSize method.

In the Android activity (for example, in the onCreate method), register your button’s OnClickListener to sign in the user when clicked:

Start the sign-in flow

In the activity’s onClick method, handle sign-in button taps by creating a sign-in intent with the getSignInIntent method, and starting the intent with startActivityForResult .

Starting the intent prompts the user to select a Google account to sign in with. If you requested scopes beyond profile , email , and openid , the user is also prompted to grant access to the requested resources.

After the user signs in, you can get a GoogleSignInAccount object for the user in the activity’s onActivityResult method.

The GoogleSignInAccount object contains information about the signed-in user, such as the user’s name.

You can also get the user’s email address with getEmail , the user’s Google ID (for client-side use) with getId , and an ID token for the user with getIdToken . If you need to pass the currently signed-in user to a backend server, send the ID token to your backend server and validate the token on the server.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Источник

Что такое Activity и его жизненный цикл в Android

Russian (Pусский) translation by Ellen Nelson (you can also view the original English article)

Из моей предыдущей статьи вы узнали, что Intents позволяют отправлять сообщения с одного компонента Android на другой. А очень важным компонентом является Activity.

Activities являются основной частью разработки приложений для Android. И невозможно понять Activity, не понимая их жизненных циклов. В этом материале вы узнаете всё о жизненном цикле Activity.

Жизненный цикл Activity

Activity — это отдельный экран в Android. Это как окно в приложении для рабочего стола, или фрейм в программе на Java. Activity позволяет вам разместить все ваши компоненты пользовательского интерфейса или виджеты на этом экране.

Важно понимать, что у Activity есть жизненный цикл, проще говоря, это означает, что она может быть в одном из различных стадий, в зависимости от того, что происходит с приложением при действиях пользователя.

Методы жизненного цикла

Давайте поближе рассмотрим жизненный цикл Android Activity. Каждый раз, когда Activity меняет стадию, вызывается один из следующих методов жизненного цикла для класса Activity.

onCreate() : вызывается при первой инициализации Activity. Вам нужно выполнить этот метод для выполнения любой инициализации в вашей Activity.

onStart() : это вызывается, когда Activity готова и отображается пользователю в первый раз, так как Activity готовится стать интерактивной и выйти на передний план. После завершения вызова этого метода, будет вызван метод onResume() .

onResume() : когда Activity переходит в это состояние, оно начинает взаимодействовать с пользователем. Activity продолжает работать в этом состоянии, пока что-либо не уведёт фокус от приложения или Activity (например, входящий звонок). Если это произойдет, будет вызван метод onPause() .

onPause() : этот метод используется для приостановки действий, которые не должны происходить, пока Activity в стадии паузы. Вызов этого метода указывает на то, что пользователь покинул приложение. К примеру, входящий звонок может перевести, проигрыватель музыки в состояние паузы. Это должно заглушить или остановить воспроизводящуюся музыку. Когда пользователь возвращается в приложение, вызывается метод onResume() .

Читайте также:  Lets go pikachu андроид

onStop() : этот метод вызывается, если Activity больше не видна в приложении. Такое может случится, если подгружена другая Activity и она занимает весь экран устройства. Когда вызывает этот метод, Activity сообщается перейти в состояние прекращения работы. В этом состоянии, система либо вызывает onRestart() для возврата взаимодействия с Activity, либо вызывает метод onDestroy() , чтобу убрать Activity.

onDestroy() : этот метод вызывается перед тем, как Activity будет завершена. Система вызывает этот метод, когда пользователь завершает Activity, или если система временно убирает процесс, содержащий Activity, для высвобождения места. С этом методом, обязательно освободите любые ресурсы, созданные вашей Activity, иначе ваше приложение будет иметь утечку памяти.

onRestart() : это вызывается, если Activity перезапускается, после того, как было остановлено.

Запуск Activity

Большинство пользовательских взаимодействий приводит к изменению действующей Activity. Поэтому приложение моно раз переключается между Activity за свой жизненный цикл.

Необходимо связывать Activity друг с другом, если требуется чтобы одна Activity запускала другую. Для запуска Activity используйте либо startActivity() , либо startActivityForResult() . В обоих случаях вы должны передать Intent.

Запуск Activity без ожидаемого результата

startActivity() используется, если недавно запущенная Activity не должна возвращать результат.

Следующий фрагмент кода показывает как начать другую Activity, используя этот метод:

Можно также выполнять действия по передачи данных от одной Activity к другой. В этом случае, ваша текущая Activity (вызывающая Activity) хочет передать данные целевой Activity. Вот когда полезны Intents. Чтобы узнать больше об использовании Intents для запуска Activity, смотрите мой предыдущий урок.

Запуск Activity на результат

startActivityForResult() используется для запуска другой Activity и ожидает получение данных в эту свежезапущенную Activity. Другими словами, используйте это если хотите получить результат от целевой Activity в вызывающую Activity, т.е. если целевая Activity собирает некую пользовательскую информацию в модальном диалоговом окне.

Вы получите результат от Activity в методе onActivityResult(int requestCode, int resultCode, Intent data) . Результат будет возвращен в качестве Intent.

Пример запуска Activity

Вот пример, который показывает как работает запуск Activity

Во-первых создайте MainActivity с вашим методом onCreate() , файл макета и кодом запроса.

В методе onCreate() вы создадите новый экземпляр намерения (intent) чтобы запустить вторую Activity.

Когда будете готовы к запуску Activity, скажем в ответ на нажатие кнопки, вы вызовете startActivityForResult() , которая передаст свеже-созданное намерение и код запроса.

В вашей MainActivity , вам всё же нужно обработать результат событий Activity. Это выполняется путём реализации метода onActivityResult() . Вот так вы и получите результат от другой Activity.

Вот как это должно выглядеть:

Теперь создайте вашу SecondActivity . Это должно быть похоже на код ниже.

Прерывание Activity

Перед завершением Activity, будут вызваны соответствующие методы жизненного цикла.

Метод onPause() должен остановить все «слушания» и обновления интерфейса. Метод onStop() должен сохранять данные приложения. И наконец, метод onDestroy() высвободит любые ресурсы, выделенные для Activity.

Когда пользователь переключается обратно на приложение, которое было прервано системным событием, вызывается метод onResume() . На основе сохраненных данных, могут перерегистрироваться «слушатели» и переключиться обновления интерфейса.

Стадия экземпляра Activity

Activity нужен способ сохранить полезное состояние и пользовательские данные, которые она получила. Эти данные могут быть получены от пользователя или созданы, пока Activity не отображалась на экране.

Например, изменение ориентации устройства могут вызвать крушение Activity и её повторное создание. В этом случае, нужно убедиться, что сохранены все состояния Activity, прежде чем она распадётся и снова перезапустится. В противном случае, любые данные, которые были у вашей Activity в это время будут полностью утеряны.

Чтобы сохранить состояние Activity, можно переопределить метод onSaveInstanceState(). Этот метод передаёт объект Bundle , в качестве параметра. Пакет (bundle) может содержать строки, простые типы данных или объекты. В этом методе, просто добавьте любые данные о важном состоянии в пакет (bundle). Позже этот пакет вернется Activity, так что вы сможете восстановить состояние Activity.

Чтобы извлечь сохраненное состояние из пакета и восстановить его (состояние), примените метод onRestoreInstanceState() . Этот callback вызывается между методами жизненного цикла onStart() и onResume() .

Мы получше рассмотрим состояние экземпляра Activity в будущих статьях.

Заключение

После просмотра этого материла, вы хорошо поймете, как работает жизненный цикл Activity. И вы узнали, что есть два способа запуска Activity, а также получение указателей на то, как обрабатывается состояние экземпляра в жизненном цикле Activity.

Спасибо за чтение, и пока вы здесь, ознакомьтесь с некоторыми другими нашими материалами о кодировании приложений для Android.

Источник

Оцените статью