Transferring user data to a new device with Smart Lock, Google Sign-In, and Auto Backup

Getting a brand new Android smartphone or pill is thrilling, however it’s additionally a dangerous time for software builders. It’s simple to lose your target audience once they transfer to a brand new tool.

Anywhere imaginable, the Android gadget mechanically downloads the person’s previously-installed programs throughout tool setup, so your app will generally observe the person to their new tool. However what about the entire information the person has accumulated to your software?

Your standard Android software comprises a wealth of knowledge customers will need to carry with them, starting from their username and password, to any adjustments they’ve made to the settings, or even paperwork and pictures created inside your software.

When the person launches your app on their glossy new Android tool, they will have to be capable of select up precisely the place they left off, fairly than finding always and energy they’ve invested to your software has been utterly misplaced!

Let’s have a look at a number of techniques you’ll be able to retailer after which repair that all-important person information, together with a very simple approach of backing up your entire app’s information to the cloud, and an API that assists in keeping customers logged into your app, despite the fact that they transfer to a brand new tool.

Saving your software’s information to Google Force

In Android 6.0 and better, you’ll be able to use Auto Backup to save lots of 25MB of your app’s information to a non-public folder within the person’s Google Force account, with out contributing to their Google Force quota. On every occasion your app is reinstalled, this knowledge will probably be restored from Google Force mechanically.

Auto Backup is one of the best ways to backup software information and lots of apps already use it. To peer which programs are already the use of this selection by yourself Android tool:

  • Release the Google Force app.
  • Drag to open the side-menu, after which make a choice “Backups.”
  • Choose the newest backup from the checklist.
  • Faucet “App information,” which can divulge a listing of each and every app that’s backing up information for your Google Force account.

In case your app objectives Android 6.0 or upper, then Auto Backup is enabled via default, because the android:allowBackup characteristic defaults to true. Alternatively, there’s by no means any ensure Android’s default habits gained’t trade in a long run unencumber, so that you will have to at all times be specific in regards to the options your software helps.

To make it transparent your app helps Auto Backup, upload this for your Manifest:


android:allowBackup="true"
...
...
...

Do you wish to have to incorporate the whole lot to your backups?

Through default, Auto Backup will retailer virtually your entire app’s content material, together with shared choice recordsdata, customized information stored for your app’s interior garage, and protracted recordsdata stored to exterior garage.

Alternatively, sometimes it’s possible you’ll want to manually exclude some content material out of your Auto Backups:

  • Any content material that includes delicate person knowledge. Because of customizations made via tool producers, the backup shipping used to retailer and retrieve Auto Backup information can range between gadgets, which makes it tough to ensure the safety of your Auto Backup information.
  • Any content material with a novel identifier, similar to Google Cloud Messaging (GCM) registration IDs. If Auto Backup restores this sort of content material on a brand new tool, the identifiers will probably be old-fashioned and your app might come upon issues when it tries to make use of this content material.

If you wish to have to specify what information’s saved via Auto Backup, you’ll be able to create a report of are/exclude laws:

  • In case your mission doesn’t already comprise a res/xml listing, then control-click its “res” folder and make a choice New > Android useful resource listing. Title this folder ‘”ML” after which click on “OK.”
  • Keep an eye on-click your mission’s res/xml listing after which make a choice New > XML useful resource report.
  • Title this report backup_rules after which make a choice “OK.”

Open this report and create your laws:




//Your laws should get started with a component//



//Specify the report(s) or folder(s) that you need to incorporate to your backups//



//Specify the report(s) or folder(s) that you need to exclude out of your backups//

area="sharedpref"
trail="com.jessicathornsby.check.LOGIN_DETAILS.xml"/>


You specify the site of every report or folder, the use of the “area” characteristic. Within the above instance, each pieces are positioned in sharedpref, however there are a number of different values you’ll be able to use:

  • area=”root.” The listing the place your entire software’s personal recordsdata are saved.
  • area=”report.” The listing returned via getFilesDir().
  • area=”database.” The listing returned via getDatabasePath(), together with databases created with SQLiteOpenHelper.
  • area=”exterior.” The listing returned via getExternalFilesDir().

When developing your laws, there are a couple of issues to keep in mind:

  • Until you state in a different way, Auto Backup will come with virtually your entire software’s information in its backups. Once you create an come with rule, it’ll most effective backup the recordsdata laid out in you. To make sure predominant information doesn’t get left from your backups, you will have to most effective create come with laws when it’s actually predominant.
  • Auto Backup at all times excludes the directories returned via getCacheDir(), getCodeCacheDir() and getNoBackupFilesDir(). Although you create come with laws for those directories, Auto Backup will forget about your request.

When you’ve created your laws, you simply want to reference this report to your mission’s Manifest:


android:fullBackupContent="@xml/backup_rules"
...
...
...

Checking out your app’s Auto Backup reinforce

Backups happen mechanically each time a majority of these prerequisites are met:

  • Auto Backup is enabled at the tool. You’ll toggle Auto Backup off and on via opening your tool’s “Settings” software after which settling on Cloud and accounts > Backup and repair > Again up my information.
  • A minimum of 24 hours have handed because the final backup.
  • The applying information has modified because the earlier backup.
  • The tool is idle and charging, with an lively Wi-Fi connection.

In most cases, this equates to round one backup in step with day, but if checking out your app you don’t have to attend 24 hours for a backup to happen naturally! You’ll check your app’s Auto Backup reinforce on-demand, the use of adb (Android Debug Bridge) instructions, which run from the Terminal (Mac) or Command Advised (Home windows).

You’ll in finding the .adb program to your Android/sdk/platform-tools folder, so open a Terminal/Command Advised Window and “trade listing” to indicate on the platform-tools folder:

cd /Customers/jessicathornsby/Library/Android/sdk/platform-tools

Subsequent, remember to’ve enabled Auto Backup and registered a Google account at the tool or emulator you’re the use of to check your app.

To make sure Auto Backup has restored its information effectively, you’ll want to generate some person information, like a username or password into your app.

When you’re able to create a backup, run the next command within the Terminal or Command Advised window:

./adb shell bmgr backupnow

After a couple of moments, the command will have to go back this:

Backup completed with end result: Good fortune

To revive this backup, uninstall your software after which reinstall it. When your app launches, the entire information integrated within the backup will have to have already got been restored.

Switch usernames and passwords to a brand new tool

In case your app has any more or less sign-in enjoy, it will have to take note the person’s login main points, even if they transfer to a brand new tool.

Not like internet browsers the place customers might periodically delete their historical past and cache, cell customers have a tendency to log into an software as soon as after which keep logged in.

Whilst you’re excited to make use of a brand new tool, the very last thing you need to do is take note software passwords you haven’t typed in years. There are a number of ways in which your app can get better person credentials after which log the person in mechanically, even if they transfer to a brand new tool.

Enforce Google Signal-In

Google Signal-In we could other people log into your software the use of their Gmail deal with and password.

Imposing Google Signal-In to your software is especially efficient, as many Android gadgets ask customers for his or her Google account main points as a part of the tool setup conversation. By the point the person reaches your software, there’s a prime probability they’ll have already saved their Google account main points on their new tool.

If the person has enabled computerized login, it’s possible you’ll even be capable of log them in mechanically the first actual time they release your app. Although the person hasn’t activated computerized login, Google Signal-In makes logging into your software so simple as tapping a “Check in with Google” button.

To put in force Google Signal-In, create a Google API Console mission ^(https://console.developers.google.com/apis/dashboard?project=api-project-724504664393), then open your mission’s construct.gradle report and upload Google Play Services and products as a mission dependency:


dependencies
implementation 'com.google.android.gms:play-services-auth:11.8.0'

Google supplies a typical “Check in with Google” button, too:


android:identity="@+identity/sign_in"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

Customers generally log right into a cell app as soon as after which stay logged in, so that you will have to at all times take a look at whether or not the person is lately signed into your software:


@Override
public void onStart()
tremendous.onStart();
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
updateUI(account);

If GoogleSignIn.getLastSignedInAccount returns null, then the person isn’t logged into your software, and also you will have to give them the approach to log in the use of their Google account:


@Override
safe void onCreate(Package savedInstanceState)

On every occasion the person faucets the “Signal In With Google” button, you will have to get started the sign-in Intent:


findViewById(R.identity.sign_in).setOnClickListener(this);
...
...
...

personal void signIn()

//Create a sign-in intent//

Intent signInIntent = mGoogleSignInClient.getSignInIntent();

//Get started the sign-in intent with startActivityForResult//

startActivityForResult(signInIntent, RC_SIGN_IN);

Subsequent, take care of the Task end result:


@Override
public void onActivityResult(int requestCode, int resultCode, Intent information)

personal void handleSignInResult(Process completedTask)
check out
GoogleSignInAccount account = completedTask.getResult(ApiException.elegance);

//If the person is signed in effectively, then replace your app’s UI//

updateUI(account);
catch (ApiException e)


personal void updateUI(@Nullable GoogleSignInAccount account)

Retailer your password within the cloud with Good Lock

Good Lock for Passwords syncs the person’s passwords with their Google account. Through including Good Lock reinforce for your software, you’ll be able to retailer customers’ passwords within the cloud, and retrieve them mechanically on all next logins, fairly than showing a “Signal In” display. Assuming a person indicators in with the similar Google account on their new tool, your app’s password will probably be mechanically to be had in this new tool.

So as to add Good Lock for Passwords reinforce for your app, you’ll want to upload Google Play Services and products as a mission dependency:


dependencies {
implementation 'com.google.android.gms:play-services-auth:11.8.0'

Subsequent, you’ll want to retrieve the person’s credentials from the cloud. This calls for us to put in force GoogleApiClient.ConnectionCallbacks and GoogleApiClient.OnConnectionFailedListener so our app can take care of a success and failed connection makes an attempt:


public elegance MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

//Get right of entry to the Credentials API, via developing an example of CredentialsClient//

GoogleApiClient mCredentialsClient;

@Override
safe void onCreate(Package savedInstanceState)
tremendous.onCreate(savedInstanceState);
setContentView(R.structure.activity_main);

//Instantiate GoogleApiClient//

mCredentialsClient = new GoogleApiClient.Builder(this)

//Get a notification each time the buyer has attached effectively//

.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.enableAutoManage(this, this)
.addApi(Auth.CREDENTIALS_API)
.construct();


@Override
public void onConnected(Package package deal)

@Override
public void onConnectionSuspended(int i)
Log.d(TAG, "onConnectionSuspended");


@Override
public void onConnectionFailed(ConnectionResult connectionResult)

Then create a CredentialRequest object:


mCredentialRequest = new CredentialRequest.Builder()
.setPasswordLoginSupported(true)
.setAccountTypes(
IdentityProviders.GOOGLE)

.construct();

Now that you simply’re attached, request any credentials to be had in your software:


//Move the request object to the CredentialsClient.request() means//

mCredentialsClient.request(request).addOnCompleteListener(
new OnCompleteListener()
@Override
public void onComplete(@NonNull Process process)

if (process.isSuccessful())

//If no credential used to be gained...//

//TO DO//


);

If a credential is gained, use this knowledge to signal the person into your software:


personal void onCredentialRetrieved(Credential credential)

If the person indicators in with a brand new set of credentials, your app must retailer this knowledge so it may be retrieved on next logins:


Credential credential = new Credential.Builder(e-mail)
.setPassword(password)
.construct();

mCredentialsClient.save(credential).addOnCompleteListener(
new OnCompleteListener() {
@Override
public void onComplete(@NonNull Process process) {
if (process.isSuccessful()) {
Log.d(TAG, "Credentials stored");
go back;

At this level, your software will ask the person to verify they need to save this password to Good Lock, so your ultimate process is dealing with the person’s reaction:


@Override
public void onActivityResult(int requestCode, int resultCode, Intent information)

Switch accounts over Bluetooth

If the person logs into your software the use of a novel username and password, you’ll be able to reproduction this knowledge from their earlier tool, to their new tool as a part of the tool setup procedure, the use of Android’s Account Switch API.

This API creates a connection between the person’s earlier (supply) tool and their new (goal) tool, and transfers your software’s login credentials over an encrypted Bluetooth connection, or by means of a phone-to-phone USB cable if the brand new tool occurs to be a Pixel.

To make use of the Account Switch API, you wish to have so as to add Google Play Services and products 11.2.0 or upper for your mission:


dependencies {
implementation 'com.google.android.gms:play-services-auth:11.8.0'

Subsequent, you’ll want to replace your mission’s Manifest to concentrate for the quite a lot of publicizes related to the Account Switch API.

When the person opts to switch information, the supply tool will ship an ACTION_START_ACCOUNT_EXPORT broadcast for which your software will want to concentrate:


android:enabled="true"
android:exported="true" >



If information is to be had to be imported, then your app will obtain the ACTION_ACCOUNT_IMPORT_DATA_AVAILABLE broadcast:





You’ll additionally want to sign up to concentrate for the ACTION_ACCOUNT_EXPORT_DATA_AVAILABLE broadcast, which will probably be gained via the supply tool:






To ship account information from a supply tool, you’ll want to get started an authenticator provider and contact sendData() according to the ACTION_START_ACCOUNT_EXPORT broadcast.


//Get a connection with an AccountTransferClient object//

AccountTransferClient consumer = AccountTransfer.getAccountTransferClient(this);
Process exportTask = consumer.sendData(ACCOUNT_TYPE, transferBytes);
check out
Duties.wait for(exportTask, TIMEOUT_API, TIME_UNIT);
catch (ExecutionException | InterruptedException | TimeoutException e)

//As soon as the switch is whole, name notifyCompletion with the right final touch standing//

consumer.notifyCompletion(ACCOUNT_TYPE,AuthenticatorTransferCompletionStatus.COMPLETED_FAILURE);
go back;

The setup wizard at the goal tool will then obtain the account information.

Upon receiving the ACTION_ACCOUNT_IMPORT_DATA_AVAILABLE broadcast, your app will want to get started a provider, calling retrieveData() to retrieve information from the supply tool.


AccountTransferClient consumer = AccountTransfer.getAccountTransferClient(this);
Process exportTask = consumer.retrieveData(ACCOUNT_TYPE);
check out catch (ExecutionException | InterruptedException | TimeoutException e)
consumer.notifyCompletion(ACCOUNT_TYPE, AuthenticatorTransferCompletionStatus.COMPLETED_FAILURE);
go back;

consumer.notifyCompletion(ACCOUNT_TYPE, AuthenticatorTransferCompletionStatus.COMPLETED_SUCCESS);

Wrapping up

We most effective checked out how one can repair and keep software information the use of Auto Backup, Google Signal-In, Good Lock, and the Account Switch API, however there’s a lot of other ways do it.

Do you employ any tactics no longer discussed on this article? Tell us within the feedback under!

from Android Authority http://ift.tt/2FrRJ1c
by means of IFTTT ^(https://ifttt.com/?ref=da&site=appmarsh)