Integrating LINE Login with your Android app

This topic explains how to implement LINE Login by integrating the LINE SDK for Android with your existing Android app. To see what LINE Login can do, read Trying the starter app and try the LINE Login starter app for Android.

Prerequisites

To build and use the LINE SDK for Android, you need:

  • A provider and a LINE Login channel. You can create both in the LINE Developers console.
  • To set minSdkVersion to 17 or higher (Android 4.2 or later).

Note: Do not use resource IDs that start with linesdk_ as this may cause conflicts with the resources in the SDK.

Add LINE SDK dependency

To integrate LINE SDK for Android, import the required library to your project and configure the Android manifest file of your project by following the steps below.

Import the library into your project

Add LINE SDK dependency in your module-level build.gradle file.

repositories {
   ...
   jcenter()
}

dependencies {
    ...
    implementation 'com.linecorp:linesdk:5.0.1'
    ...
} 

Add Android compilation options

Enable Java 1.8 support. In the same build.gradle file as above, add:

android {
...
  compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
...
}

Setting the Android manifest file

To specify that your app requires Internet access, add the INTERNET permission to your AndroidManifest.xml file.

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

Note: Make sure the launch mode of the activity that is making the login call is not set to singleInstance as that may prevent the activity from receiving the onActivityResult callback.

Adding the LINE Login button

To let the user log in to your Android app, you can create a LINE-branded login button to take the user through the authentication and authorization process.

There are 2 ways to add a login button:

Use the LINE SDK's built-in login button

The LINE SDK provides a pre-defined login button. You can add a login button to the user interface of your app to provide your users with a quick way to log in as below:

  1. Add the login button in your layout XML file.

    <com.linecorp.linesdk.widget.LoginButton
        android:id="@+id/line_login_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    
  2. Find the view in your activity or fragment, set up necessary parameters, and assign a listener to it.

    import java.util.Arrays;
    
    // A delegate for delegating the login result to the internal login handler. 
    private LoginDelegate loginDelegate = LoginDelegate.Factory.create();
    
    LoginButton loginButton = rootView.findViewById(R.id.line_login_btn);
    
    // if the button is inside a Fragment, this function should be called.
    loginButton.setFragment(this); 
    
    loginButton.setChannelId(channelIdEditText.getText().toString());
    
    // configure whether login process should be done by Line App, or inside WebView.
    loginButton.enableLineAppAuthentication(true);
    
    // set up required scopes. 
    loginButton.setAuthenticationParams(new LineAuthenticationParams.Builder()
            .scopes(Arrays.asList(Scope.PROFILE))
            .build()
    );
    loginButton.setLoginDelegate(loginDelegate);
    loginButton.addLoginListener(new LoginListener() {
        @Override
        public void onLoginSuccess(@NonNull LineLoginResult result) {
            Toast.makeText(getContext(), "Login success", Toast.LENGTH_SHORT).show();
        }
    
        @Override
        public void onLoginFailure(@Nullable LineLoginResult result) {
            Toast.makeText(getContext(), "Login failure", Toast.LENGTH_SHORT).show();
        }
    });
    

Use a customized login button

Instead of using the default login button, you can also customize your user interface and login process with your own code.

Download and add the images to your project

The LINE Login button image set includes images for iOS, Android and desktop applications. The image set for Android includes images for multiple screen densities and button states. In this guide, we’ll use the “base” and “pressed” login button images in the Android folder.

  1. Download and extract the LINE Login button images.
  2. Add the "base" and "pressed" login button images to the drawable folder for each screen density.

Configure the images

Before you can use the images, you’ll need to add the login button text that you want to use. See LINE Login button design guidelines for the recommended login button text for different languages. You’ll also need to define stretchable regions of the image to add the button text without distorting the LINE icon.

  1. Create 9-patch files for each image and define the stretchable regions for the login button text.
  2. Add the button to the login screen of your app as a clickable text view with your desired login button text.
  3. Add selector XML files in your drawable folders to define the image which corresponds to the state of the text view.

Starting the login activity

When a user taps the login button, your app calls getLoginIntent() to get the login intent and start the login activity. The context and the channel ID must be passed into this method. If LINE is installed on the device, LINE is opened to perform login without asking for the user’s LINE credentials. If LINE is not installed, users are redirected to the LINE Login screen in a browser to enter their LINE credentials (email address and password).

  1. Set an on-click listener to listen for when the button is tapped.
  2. In the onClick callback, call the getLoginIntent() method in LineLoginApi to get the login intent to start the login activity.
  3. Start the authentication process by calling startActivityForResult() and passing the login intent and request code as parameters. The request code is an integer that is used to identify the request.

The following is an example of how to start the activity to log in the user when the user taps the login button.

private static final int REQUEST_CODE = 1;
...

final TextView loginButton = (TextView) findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {

    public void onClick(View view) {
        try{
            // App-to-app login
            Intent loginIntent = LineLoginApi.getLoginIntent(
                view.getContext(), 
                Constants.CHANNEL_ID, 
                new LineAuthenticationParams.Builder()
                        .scopes(Arrays.asList(Scope.PROFILE))
                        .build());
            startActivityForResult(loginIntent, REQUEST_CODE);

        }
        catch(Exception e) {
            Log.e("ERROR", e.toString());
        }
    }
});

Note: If you do not want to use app-to-app login and instead have the user log in via the LINE Login screen in a browser, use the getLoginIntentWithoutLineAppAuth() method.

Handling the login result

After the user has logged in, the login result is returned in the activity’s onActivityResult() method. Your application must override this method to handle the login result.

Use the getResponseCode() method of the LineLoginResult object to determine if the login was successful. If getResponseCode() returns SUCCESS, the login was successful. Any other value indicates a failure. See Handling errors to determine the type of error that occurred.

The following shows an example of how the login result can be handled by your app.

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode != REQUEST_CODE) {
        Log.e("ERROR", "Unsupported Request");
        return;
    }

    LineLoginResult result = LineLoginApi.getLoginResultFromIntent(data);

    switch (result.getResponseCode()) {

        case SUCCESS:     
            // Login successful
            String accessToken = result.getLineCredential().getAccessToken().getTokenString();

            Intent transitionIntent = new Intent(this, PostLoginActivity.class);
            transitionIntent.putExtra("line_profile", result.getLineProfile());
            transitionIntent.putExtra("line_credential", result.getLineCredential());
            startActivity(transitionIntent);
            break;

        case CANCEL:    
            // Login canceled by user
            Log.e("ERROR", "LINE Login Canceled by user.");
            break;

        default:
            // Login canceled due to other error
            Log.e("ERROR", "Login FAILED!");
            Log.e("ERROR", result.getErrorData().toString());
    }
}

Get the access token

The login result contains a LineCredential() object which contains the user’s access token. As shown in the example above, you can retrieve the access token using the following code.

String accessToken = result.getLineCredential().getAccessToken().getTokenString();

Get user profile immediately after login

The LINE SDK automatically gets a user’s profile information upon logging in. The user’s profile information consists of the display name, user ID, status message, and profile media URL. Access this information by calling the getLineProfile() method in the LineLoginResult object. The following code snippet from the example above demonstrates how to get a user’s profile information from the login result and pass it into an intent.

transitionIntent.putExtra("display_name", result.getLineProfile().getDisplayName());
transitionIntent.putExtra("status_message", result.getLineProfile().getStatusMessage());
transitionIntent.putExtra("user_id", result.getLineProfile().getUserId());
transitionIntent.putExtra("picture_url", result.getLineProfile().getPictureUrl().toString());

The user ID is only unique to an individual provider. The same LINE user will have a different user ID for different providers. Avoid using the user ID to identify users across different providers.

Using user information on your server

warning User impersonation

Do not trust user IDs, or other information available in the LineProfile object, when sent by a client to your backend server. A malicious client can send an arbitrary user ID or malformed information to your server to impersonate a user.

Instead, the client should send the server an access token, and the server should use the token to retrieve user information.

Typically, a back-end server verifies a user's identity based on a user ID, display name, or some other LINE account property. But instead of sending that information from the client to your server directly, the client should send an access token. The server should then use this to securely verify the user's identity against LINE's server.

Learn more about access tokens from Get the access token.

Learn more about what APIs to call from your backend on these pages:

Using the LineApiClient interface

Use the SDK by calling the methods of the LineApiClient interface. To do this, create a static variable of a lineApiClient object and initialize the variable.

  1. Create a static variable of the object to call various methods.
    private static LineApiClient lineApiClient;
    
  2. Initialize the lineApiClient variable on your activity’s onCreate() method as shown below. The channel ID and the context are required for initialization.
    LineApiClientBuilder apiClientBuilder = new LineApiClientBuilder(getApplicationContext(), "your channel id here");
    lineApiClient = apiClientBuilder.build();
    

Note: All methods in the LINE SDK for Android perform network operations and will cause NetworkOnMainThreadExceptions if called on the main thread. To avoid this issue, call the methods using AsyncTask.

{{ $t("form.question.helpful") }}

{{ $t("form.question.detail") }}

{{ $t("form.question.improve") }}

{{ $t("form.info.start") }}{{ $t("form.info.link") }}{{ $t("form.info.end") }}


{{ $t("form.result.success") }}
{{ $t("form.result.error") }}
{{ $t("form.result.errorLink") }}