As announced at Google I / O 2017, Kotlin has joined the official language of Android, so using mBaaS (mobile Backend as a Service) ncmb (nifty cloud mobile backend) and Firebase, Kotlin immediately I tried Android programming. mBaaS is a service that provides general-purpose functions (user management, data store, push notification, etc.) that are often used for application development from the cloud, but this time we will introduce the user authentication functions of both.
AndroidStudio2.3.3
Kotlin 1.1.3
ncmb
firebase
Please refer to the article here for the procedure to install Kotlin in Android Studio.
ncmb(nifty cloud mobile backend)
First, create a new app from the dashboard.
When you create a new app, you will be issued an application key and a client key.
The flow of ncmb email address authentication is as follows.
MainActivity.kt
class MainActivity : AppCompatActivity(), View.OnClickListener{
//constant
companion object Factory {
// ApplicationKey
val APP_KEY = "YOUR APP KEY" //Application key setting issued when creating a new application
// ClientKey
val CLIENT_KEY = "YOUR CLIENT KEY" //Client key settings issued when creating a new application
}
private var mEmailField: EditText? = null
private var mPasswordField: EditText? = null
private var loginMailAddress: EditText? = null
private var loginPassword: EditText? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//**********API key setting and SDK initialization**********
NCMB.initialize(this.baseContext, APP_KEY, CLIENT_KEY)
//Member registration
mEmailField = findViewById(R.id.MailAddress) as EditText
mPasswordField = findViewById(R.id.Password) as EditText
//Login
loginMailAddress = findViewById(R.id.login_MailAddress) as EditText
loginPassword = findViewById(R.id.login_Password) as EditText
//SIGN UP button
findViewById(R.id.Button)?.setOnClickListener(this)
//LOGIN button
findViewById(R.id.login_Button)?.setOnClickListener(this)
//LOGOUT button
findViewById(R.id.logout_Button)?.setOnClickListener(this)
}
}
/**
*When the button is clicked
*/
override fun onClick(v : View) {
val id = v.id
if(id == (R.id.Button)) {
//Member registration
createAccount(mEmailField?.text.toString())
} else if(id == (R.id.login_Button)) {
//Login
signIn(loginMailAddress?.text.toString(), loginPassword?.text.toString())
} else if(id == (R.id.logout_Button)) {
//Log out
signOut()
}
}
The member registration process is performed by the createAccount method that has a String type email as an argument, which is called when the SIGN UP button is pressed.
MainActivity.kt
private fun createAccount(email: String) {
NCMBUser.requestAuthenticationMailInBackground(email) { e ->
if(e == null) {
println("Successful user email authentication")
} else {
println("User email authentication failed")
}
}
}
If you write it in java, it will look like this. It is more verbose than kotlin. NCMBUser's requestAuthenticationMailInBackground method uses the email address entered by the user as an argument and [DoneCallback](http://www.programcreek.com/java-api-examples/index.php?source_dir=ncmb_android-master/ncmb-core/src It takes an interface (/main/java/com/nifty/cloud/mb/core/DoneCallback.java) as an argument. Here [DoneCallback](http://www.programcreek.com/java-api-examples/index.php?source_dir=ncmb_android-master/ncmb-core/src/main/java/com/nifty/cloud/mb/ An anonymous class that implements the core / DoneCallback.java) interface is generated and passed as an argument.
MainActivity.java
private void createAccount(String email) {
NCMBUser.requestAuthenticationMailInBackground(email,
new DoneCallback() {
@Override
public void done(NCMBException e) {
if (e == null) {
System.out.println("Successful user email authentication");
} else if {
System.out.println("User email authentication failed");
}
}
});
}
For those who wrote in kotlin, the DoneCallback interface and the method called done (NCMBException e) are omitted, but this is SAM conversion by the SAM interface. SAM (Single Abstract Method) is an interface that has only one abstract method. [DoneCallback](http://www.programcreek.com/java-api-examples/index.php?source_dir=ncmb_android-master/ncmb-core/src/main/java/com/nifty/cloud/mb/core/ DoneCallback.java) The interface abstract method done (NCMBException e) has a void type as a return value and an NCMBException type as an argument. Therefore, you can omit the type of the function literal and describe it neatly like kotlin by type inference. For function literals, I referred to the article here.
If you can successfully register as a member, your user information will be registered on the member management screen of ncmb.
The login process is performed by the signIn method that has a String type email and a String type password as arguments, which are called when the LOGIN button is pressed. You can log in by calling NCMBUser's loginWithMailAddressInBackground method in the signIn method.
MainActivity.kt
private fun signIn(email: String, password: String) {
NCMBUser.loginWithMailAddressInBackground(email, password) {user, e ->
if(e == null) {
println("Login successful")
} else {
println("Login failure:" + e.message.toString() )
}
}
}
After registering your password from the member registration email and registering as a member, you will be able to log in with your email address and password.
The logout process calls the signOut method with no arguments, which is called when the logout button is pressed. You can log out by calling NCMBUser's logoutInBackground method in the sighOut method.
MainActivity.kt
private fun signOut() {
NCMBUser.logoutInBackground{ e ->
if (e == null) {
println("Successful logout")
} else {
println("Logout failure")
}
}
}
To allow email address password authentication, check "Allow email address / password authentication" from the application settings → member authentication settings on the dashboard and save.
Firebase
Log in to Firebase with your Google account and create a new project.
Enable email / password status from the Firebase Authentication administration screen.
MainActivity.kt
class MainActivity : AppCompatActivity(), View.OnClickListener {
private var mEmailField: EditText? = null
private var mPasswordField: EditText? = null
private var loginEmail: EditText? = null
private var loginPassword: EditText? = null
private var mAuth: FirebaseAuth? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//New user item
mEmailField = findViewById(R.id.MailAddress) as EditText
mPasswordField = findViewById(R.id.Password) as EditText
//Items at login
loginEmail = findViewById(R.id.login_MailAddress) as EditText
loginPassword = findViewById(R.id.login_Password) as EditText
//When pressing the SIGN UP button
findViewById(R.id.Button)?.setOnClickListener(this)
//When pressing the LOGIN button
findViewById(R.id.login_Button)?.setOnClickListener(this)
//When pressing the LOG OUT button
findViewById(R.id.logout_Button)?.setOnClickListener(this)
//Get FirebaseAuth instance
mAuth = FirebaseAuth.getInstance()
}
/**
*Button click processing
*/
override fun onClick(v: View) {
val i = v.id
if (i == R.id.Button) {
//When the new button is pressed
createAccount(mEmailField?.text.toString(), mPasswordField?.text.toString())
} else if (i == R.id.login_Button) {
//When the login button is pressed
signIn(loginEmail?.text.toString(), loginPassword?.text.toString())
} else if (i == R.id.logout_Button) {
//When the logout button is pressed
signOut()
}
}
Added Firebase Authentication dependencies to app-level build.gradle
build.gradle
dependencies {
(Omitted)
// Firebase Authentication
compile 'com.google.firebase:firebase-auth:10.0.1'add to
}
In the createAccount method called when the SIGN UP button is pressed, pass the email address and password entered by the user to the createUserWithEmailAndPassword method of the Firebase instance to create a new account.
MainActivity.kt
private fun createAccount(email: String, password: String) {
mAuth?.createUserWithEmailAndPassword(email, password)
?.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
println("Successful user creation")
sendEmailVerrification()//Send confirmation email
} else {
println("User creation failure:" + task.exception.toString())
}
}
}
** Caution **: In ncmb, a confirmation email was sent at the time of membership registration, and the password was set by clicking the link in the email and the membership registration was completed, but in Firebase, a confirmation email was sent at the time of membership registration. It will not be. Therefore, when a new user is created successfully, a method to send a confirmation email is created and called.
If you can create a user normally, the user information will be saved in the management screen of Firebase.
If you have successfully created a new user, call this method to send a confirmation email to the user.
MainActivity.kt
private fun sendEmailVerrification() {
val user = FirebaseAuth.getInstance().currentUser
user?.sendEmailVerification()
?.addOnCompleteListener(this) { task ->
if(task.isSuccessful) {
println("Successful email transmission")
} else {
println("Email transmission failure:" + task.exception.toString())
}
}
}
In the dignIn method called when the LOGIN button is pressed, pass the email address and password entered by the user to the signInWithEmailAndPassword method of the Firebase instance as arguments.
MainActivity.kt
private fun signIn(email: String, password: String) {
mAuth?.signInWithEmailAndPassword(email, password)
?.addOnCompleteListener(this) { task ->
if(task.isSuccessful) {
println("Successful login user:" + mAuth?.currentUser.toString())
} else {
println("Login failure")
}
}
}
With the signOut method called when the LOGOUT button is pressed, call the signOut method of the Firebase instance to log out.
MainActivity.kt
private fun signOut() {
mAuth?.signOut()
}
Firebase Analytics Firebase also has a tool called Firebase Analytics, which is positioned as Google Analytics specialized for mobile applications, and although I have not investigated it in detail, it seems to be useful for access analysis. Regarding the installation procedure, the article here was easy to understand.
[NCMB Official Document](http://mb.cloud.nifty.com/doc/current/user/authorize_email_android.html# Implementation in App) Firebase Official Document http://qiita.com/RyotaMurohoshi/items/01b370f34a4bf96f5c39 http://kotlin.hatenablog.jp/entry/2012/12/10/093018
Recommended Posts