Android

Add Auth Service to Your Android Project

Prerequisites

Make sure that your project meets the following requirements:

  • minSdkVersion 23 or higher;compileSdkVersion、targetSdkVersion 33 or higher

  • Uses JavaVersion 11

Create a Particle Project and App

Before you can add Auth Service to your Android app, you need to create a Particle project to connect to your Android app. Visit Particle Dashboard to learn more about Particle projects and apps.

👉 Sign up/log in and create your project now

Add the Auth Service SDK to Your App

Declare them in your module (app-level) Gradle file (usually app/build.gradle).

repositories {
    google()
    mavenCentral()
    maven { setUrl("https://jitpack.io") }
    //...
}
dependencies {
    // Particle Auth Service
    implementation("network.particle:auth-service:${latest_version}") 
    
    //find the latest version of the sdk:
    //https://search.maven.org/search?q=g:network.particle
    //...
}

If you want to receive release updates, subscribe to our GitHub repository.

Add Configuration File

Declare them in you app AndroidManifest.xml (usually app/src/main/AndroidManifest.xml).

<application>
        <!--   Particle Network config start     -->
        <activity
                android:name="com.particle.network.controller.WebActivity"
                android:exported="true"
                android:launchMode="singleTask"
                android:configChanges="orientation|keyboardHidden|screenSize"
                android:theme="@style/ThemeAuthWeb"
                >
            <intent-filter>
                <data android:scheme="pn${pn_app_id}" />
        
                <action android:name="android.intent.action.VIEW" />
        
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
            </intent-filter>
        </activity>
        
        <meta-data
                android:name="particle.network.project_id"
                android:value="${pn_project_id}"
                />
        <meta-data
                android:name="particle.network.project_client_key"
                android:value="${pn_project_client_key}"
                />
        <meta-data
                android:name="particle.network.app_id"
                android:value="${pn_app_id}"
                />
        <!--   Particle Network config end     -->
</application>

Replace pn_project_id, pn_project_client_key, pn_app_id with the new values created in Particle Dashboard.

API Reference

Initialize the SDK

Initialize the SDK by calling the ParticleNetwork.init()method, passing the method a context. Do this as soon as your app starts, like in the onCreate()method of your Application.

class App : Application() {
    override fun onCreate() {
        super.onCreate()
        //init Particle SDK for solana chain 
        ParticleNetwork.init(this, Env.DEV, ChainInfo.Solana)
    }
}

Particle Network support Solana and EVM chains, you can init with below chain info:

👉 chainId and chainName configs

Switch ChainInfo

// Async switch chain name, it will check if user has logged in this chain name.
// For example, if a user logged in with ethereum, then switch to  bsc,
// it will switch to bsc directly, beacuse both bsc and ethereum are evm,
// but if switch to solana, beacuse user didn't log in solana before, it will 
// present a web browser for additional information automatically.
ParticleNetwork.switchChain(
    ChainInfo.Ethereum,
    object : ResultCallback {
        override fun success() {
            val currChain = ParticleNetwork.chainInfo.name
        }

        override fun failure() {
           
        }
    })
    
// Sync switch chain name. it will wont check if user has logged in.
ParticleNetwork.setChainInfo(ChainInfo.Polygon)

Login

To auth login with Particle, call ParticleNetwork.login(...)with activity and callback. You can log in with your email or phone number by changing the loginType parameter. Your wallet is created when you log in successfully for the first time.

//   - Parameters:
//   - loginType: Login type, support jwt,email, phone, google, apple and facebook
//   - account: When login type is email or phone, you could pass email address or phone number,Optional.
                When login type is jwt, you must pass json web token.
//   - supportAuthType: Controls whether third-party login buttons are displayed. default will show none third-party login buttons.
//   - loginFormMode: Controls whether show light UI in web, default is false.
//   - prompt: Social login prompt. default is null
ParticleNetwork.login(
    loginType = LoginType.PHONE,
    account = "",
    supportAuthTypeValues = SupportAuthType.FACEBOOK.value or SupportAuthType.GOOGLE.value or SupportAuthType.APPLE.value,
    prompt = null,
    loginCallback = object : WebServiceCallback<UserInfo> {
        override fun success(output: UserInfo) {
        }
        override fun failure(errMsg: ErrorInfo) {
        }
    })

// - without account parameter you can use this method overwrite
ParticleNetwork.login(
    loginType = LoginType.PHONE,
    supportAuthTypeValues = SupportAuthType.FACEBOOK.value or SupportAuthType.GOOGLE.value or SupportAuthType.APPLE.value,
    loginCallback = object : WebServiceCallback<UserInfo> {
        override fun success(output: UserInfo) {
        }
        override fun failure(errMsg: ErrorInfo) {
        }
    })
        
        
// Login with JWT
val account = "json web token"
ParticleNetwork.login(
    loginType = LoginType.JWT,
    account = account,
    supportAuthTypeValues = SupportAuthType.ALL.value,
    loginCallback = object : WebServiceCallback<UserInfo>{
        override fun success(output: UserInfo) {
         
        }
        override fun failure(errMsg: ErrorInfo) {
        
        }
    })

After log-in success, you can obtain user info by calling ParticleNetwork.getUserInfo()

Logout

The SDK will delete users' account information in cache.

ParticleNetwork.logout(object : WebServiceCallback<WebOutput> {
    override fun success(output: WebOutput) {
        //logout success
    }

    override fun failure(errMsg: ErrorInfo) {
        //handle error
    }
})

Fast Logout

Logout without broswer,The SDK will delete users' account information in cache.

 ParticleNetwork.fastLogout(object : ResultCallback {
        override fun success() {
            //logout success
        }

        override fun failure() {
            //handle error
        }
    })

Check user login status

ParticleNetwork.isLogin()

Signatures

Use Particle SDK to sign a transaction or message. The SDK provides three methods for signing:

  1. signAndSendTransaction: sign and send the transaction with Particle Node, then return the signature.

  2. signTransaction: sign transaction, return signed message, only Solana blockchain support it.

  3. signMessage: sign message, return signed message.

  4. signTypedData : sign typed data,only EVM blockchain support it.

//solana transaction: base58 string. 
//evm transcation:'0x' prefixed hex string.
ParticleNetwork.signAndSendTransaction(transaction, object : WebServiceCallback<SignOutput>{
    override fun success(output: SignOutput) {
        //sign and send transaction success
    }

    override fun failure(errMsg: ErrorInfo) {
        // handle error
    }
})


//solana transaction: base58 string. evm not support this method.
ParticleNetwork.signTransaction(transaction, object : WebServiceCallback<SignOutput>{
    override fun success(output: SignOutput) {
        //sign transaction success
    }

    override fun failure(errMsg: ErrorInfo) {
        // handle error
    }
})

//transaction: request base58 string list in solana, not support evm
val allTrans = listOf(trans1, trans2)
ParticleNetwork.signAllTransactions(
    activity,
    allTrans,
    object : WebServiceCallback<SignOutput> {
        override fun success(output: SignOutput) {
            //sign success
        }
        override fun failure(errMsg: ErrorInfo) {
            // handle error
        }
    })

//solana message: any string.
//evm message: '0x' prefixed hex string, use 'personal_sign' to sign.
ParticleNetwork.signMessage(message, object : WebServiceCallback<SignOutput>{
    override fun success(output: SignOutput) {
        //sign success
    }

    override fun failure(errMsg: ErrorInfo) {
        // handle error
    }
})

//sign typed data, only evm support this method.
//message: '0x' prefixed hex string.
ParticleNetwork.signTypedData(message, version, object : WebServiceCallback<SignOutput>{
    override fun success(output: SignOutput) {
        //sign success
    }

    override fun failure(errMsg: ErrorInfo) {
        // handle error
    }
})

You can create transaction with TxData.There's an easy way to do this with Wallet Service

Set Display Wallet

// set display wallet when call sign and send transaction. default is false
ParticleNetwork.setDisplayWallet(true) 

Open Web Wallet

// if user is login, it will open web wallet.
//https://docs.particle.network/developers/wallet-service/sdks/web
 val customStyleJson = 
 """
      {
        "supportAddToken": false,
        "supportChains": [{
            "id": 1,
            "name": "Ethereum"
          },
          {
            "id": 5,
            "name": "Ethereum"
          }
        ]
      }
"""
ParticleNetwork.openWebWallet(customStyleJson)

Open account and security

ParticleNetwork.openAccountAndSecurity()

Set security account config

// set security account config, 
// promptSettingWhenSign default value is 1.
// promptMasterPasswordSettingWhenLogin default value is 0.
// 0 no prompt
// 1 first time show prompt
// 2 every time show prompt
 ParticleNetwork.setSecurityAccountConfig(
    SecurityAccountConfig(
        promptSettingWhenSign = 1,
        promptMasterPasswordSettingWhenLogin = 2
    )
)

Custom interface style

//this is the default setting
ParticleNetwork.setAppearence(ThemeEnum.AUTO)
//dark 
ParticleNetwork.setAppearence(ThemeEnum.DARK)
//light
ParticleNetwork.setAppearence(ThemeEnum.LIGHT)

Language setting

//Set the language of the SDK
//support LanguageEnum.EN、LanguageEnum.JA、LanguageEnum.KO、LanguageEnum.ZH_CN、LanguageEnum.ZH_TW
ParticleNetwork.setAppliedLanguage(LanguageEnum.EN)

//Get Applied Language
val languageEnum = ParticleNetwork.getAppliedLanguage()

Control setpassword dialog

If the user does not set a password, a dialog box will pop up when the user sends a transaction,

If you don't want to prompt the user, you can call the following code

ParticleNetwork.setSecurityAccountConfig(SecurityAccountConfig(false))

Error

ErrorInfo contains error details. You can check the information by printing the message attribute.

Particle Wallet Connect V1

Integrate your app as a wallet connect wallet.

Add the Particle Wallet Connect SDK to Your App

repositories {
    google()
    mavenCentral()
    maven { setUrl("https://jitpack.io") }
    //...
}
dependencies {
    // Particle Wallet Connect Service
    implementation("network.particle:particle-wallet-connect:${latest_version}")
    //...
}

Initialize

// Note: If you want to add listening events, you need to put them before init
ParticleWalletConnect.onXXListeners = {
    ...
}
// Initialize Particle Wallet Connect SDK, a wallet meta data
val dAppMetadata = DAppMetadata(
  "walletConnectProjectId",
  "Particle Connect",
  "https://connect.particle.network/icons/512.png",
  "https://particle.network",
  description = "Particle Connect is a decentralized wallet connection protocol that makes it easy for users to connect their wallets to your DApp.",
)

ParticleWalletConnect.init(this, dAppData = dAppMetadata)

Connect

// Connect to a wallet connect code
val uri = "wc:DDCBBAA8-B1F1-4B98-8F74-84939E0B1533@1?bridge=https%3A%2F%2Fbridge%2Ewalletconnect%2Eorg%2F&key=3da9dbb33b560beeb1750203a8d0e3487b4fe3fdd7b7953d79fbccadae8aab48"
ParticleWalletConnect.connect(uri)

Set Provider And Listeners

//require: This method needs to be called before ParticleWalletConnect.init
//AuthProvider Implemented the following methods:
//personal_sign、eth_signTypedData_v1、eth_signTypedData_v3、eth_signTypedData_v4、eth_sendTransaction、eth_chainId、eth_accounts、eth_requestAccounts
//Here you can replace  your own Provider
 ParticleWalletDelegate.wcEventModels.onEach { wcEvent ->
    when (wcEvent) {
        is Sign.Model.SessionProposal -> {
           
        }

        is Sign.Model.SessionRequest -> {
           
        }

        else -> {

        }
    }
}.launchIn(lifecycleScope)

//approve or reject
ParticleWalletConnect.onSessionRequest = { id, peerMeta ->
    //approve
    ParticleWalletConnect.approveSession(context,"PublicAddress",chainId)
    //or reject
    ParticleWalletConnect.rejectSession()
}
//disconnect session
ParticleWalletConnect.onDisconnect = { code, topic, reason ->
    //disconnect
    ParticleWalletConnect.delWCSessionStoreItem(topic)
}

//receive change network request
ParticleWalletConnect.onWalletChangeNetwork = { id, topic, chainId ->
    //show dialog to switch network
}

Session Operation

//when ParticleWalletConnect.approveSession() is call,a new Session can be saved
//get All Session Info
ParticleWalletConnect.getAllWCSessionStoreItem()
//get Session by topic
ParticleWalletConnect.getWCSessionStoreItem(topic)
//delete Session by topic
ParticleWalletConnect.delWCSessionStoreItem(topic)
//delete all Sessions
ParticleWalletConnect.clearWCSessionStore()

Last updated