Skip to main content

DropBox Instruction



To create a new project, open link:
https://www.dropbox.com/developers/apps/create

In p. 2 choose App folder. In p. 3 write any test name.




Project window will be opened.

If you lost it, you can open it again from here:
https://www.dropbox.com/developers/apps/

On the project page, find the App key and App secret, save them for later.


Next go to Permissions tab and check files.content.read permission





Press Submit at the bottom of the page.


Next you need to get AuthCode

AuthCode is needed to generate RefreshToken, which will be used to access files by webRequests. You need to be authorized in the account on which you will store your content. So if you are making a dropbox app for your own tests, that should be your own account. And if you are preparing to send your project to release, then production manager should send AuthCode to you.

Paste the following link into the address bar of your browser and replace {AppKey} (including {} ) with the key of your app, mentioned above:


https://www.dropbox.com/oauth2/authorize?client_id={AppKey}&response_type=code&token_access_type=offline



The following window will open. Check on the top right corner that you are logged to the right dropbox account.


Нажимаем Продолжить, Проверяем, что выданы нужные разрешения - минимум на просмотр содержимого файлов. Нажимаем Продолжить еще раз. Отправляем код разработчику / разработчик сохраняет код. Код работает в течение примерно часа, так что разработчик должен быть готов получить из него рефреш-токен сразу после генерации кода.


Click Continue (right blue button on the screen above). Check that the app asks you for the right permissions - at least for content read. Click continue once more. You will see AuthCode, that you will need to generate RefreshToken from. AuthCode is only valid for about 10 minutes so you need to generate a RefreshToken quickly. Otherwise you will need to generate a new AuthCode.



In the root of your dropbox storage a special “Applications” folder will appear. If it didn’t, then you need to make any webrequest to your app (described later) and then it will.

Load your content to Applications/YourAppName.



You can get tutorials for andorid implementation in the following link:

https://github.com/dropbox/dropbox-sdk-java


Step 1: Now, Go to your android project and add the dependency in your build.gradle file.

implementation 'com.dropbox.core:dropbox-core-sdk:5.4.4'

Step 2: Add these following pieces to your AndroidManifest.xml to use Dropbox for Authentication in Android.


Add AuthActivity to the manifest


Use your Dropbox APP Key in place of dropboxKey below. You need to add the AuthActivity entry, and it's associated intent-filter.


<manifest>

    ...

    <application>

        <activity

            android:name="com.dropbox.core.android.AuthActivity"

            android:exported="true"

            android:configChanges="orientation|keyboard"

            android:launchMode="singleTask">

            <intent-filter>

                <data android:scheme="db-${dropboxKey}" />

        

                <action android:name="android.intent.action.VIEW" />

        

                <category android:name="android.intent.category.BROWSABLE" />

                <category android:name="android.intent.category.DEFAULT" />

            </intent-filter>

            

            <!-- Additional intent-filter required as a workaround for Apps using targetSdk=33 until the fix in the Dropbox app is available to all users. -->

            <intent-filter>

                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />

            </intent-filter>

        </activity>

    </application>

    ...

</manifest>


Step 3: Additionally, you need to allow queries from the Dropbox official app for verification during the app-to-app authentication flow.


<manifest>

    ...

    <queries>

        <package android:name="com.dropbox.android" />

    </queries>

    ...

</manifest>


Step 4: Add your dropbox app key to strings.xml

<!-- Change this to your app key -->

<string name="APP_KEY">APP_KEY_HERE</string>


Step 5: Login with Dropbox.

public class LoginActivity extends AppCompatActivity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);


        Button SignInButton = (Button) findViewById(R.id.sign_in_button);

        SignInButton.setOnClickListener(new OnClickListener() {

            @Override

            public void onClick(View view) {

                Auth.startOAuth2Authentication(getApplicationContext(), getString(R.string.APP_KEY));

            }

        });

    }


    @Override

    protected void onResume() {

        super.onResume();

        getAccessToken();

    }


    public void getAccessToken() {

        String accessToken = Auth.getOAuth2Token(); //generate Access Token

        if (accessToken != null) {

            //Store accessToken in SharedPreferences

            SharedPreferences prefs = getSharedPreferences("com.example.valdio.dropboxintegration", Context.MODE_PRIVATE);

            prefs.edit().putString("access-token", accessToken).apply();


            //Proceed to MainActivity

            Intent intent = new Intent(LoginActivity.this, MainActivity.class);

            startActivity(intent);

        }

    }

}


Dropbox Client Is Now Logged In.

Step 6: Additionally, This SDK requires special ProGuard rules, if shrink optimization is enabled in project than add following snippets in proguard-rules.pro file (Optional).

-dontwarn okio.**

-dontwarn okhttp3.**

-dontwarn com.squareup.okhttp.**

-dontwarn com.google.apphosting.**

-dontwarn com.google.appengine.**

-dontwarn com.google.protos.cloud.sql.**

-dontwarn com.google.cloud.sql.**

-dontwarn javax.activation.**

-dontwarn javax.mail.**

-dontwarn javax.servlet.**

-dontwarn org.apache.**


Integration for Reading Files & Writing Files from Dropbox

Add these dependencies to an existing project.

Step 1:

implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:okhttp:4.10.0'

 

Step 2:

<string name="APP_KEY_DROPBOX"> </string>

<string name="APP_SECRET_DROPBOX"> </string>

<string name="REFRESH_TOKEN"> </string>

 

  1. You can get App Key from DropBox App Console
  2. You can get App Secret from DropBox App Console
  3. To get the Refresh token, you need to call the function for getting the refresh Token or by Using postman

For Refresh Token:

fun getRefreshToken() {

    println("Requesting refreshToken...")

    val dbxAppInfo =

        DbxAppInfo(

            getString(R.string.APP_KEY_DROPBOX),

            getString(R.string.APP_SECRET_DROPBOX)

        )

    val authCode = " Add Auth CODE here and After that call the fucntion"

    // val redirectUri = "<REDIRECT_URI>"

    val clientId = dbxAppInfo.key

    val clientSecret = dbxAppInfo.secret

    println("Requesting refreshToken...")



    val formBody = FormBody.Builder()

        .add("code", authCode)

        .add("grant_type", "authorization_code")

        .build()



    val credentials = Credentials.basic(clientId, clientSecret)



    val request = Request.Builder()

        .url("https://api.dropbox.com/oauth2/token")

        .post(formBody)

        .header("Authorization", credentials)

        .build()



    val client = OkHttpClient()



    client.newCall(request).enqueue(object : Callback {

        override fun onFailure(call: Call, e: IOException) {

            println("Failed to get refreshToken: ${e.message}")

        }



        override fun onResponse(call: Call, response: Response) {

            if (!response.isSuccessful) {

                println("Failed to get refreshToken: ${response.code}")

                return

            }



            val jsonResponse = response.body?.string()

            val parsedAnswer = JSONObject(jsonResponse)

            val refreshTokenString = parsedAnswer.getString("refresh_token")



            println("Copy this string to RefreshToken: $refreshTokenString")

        }

    })

}

 

For Access Token:

suspend fun getAccessToken(refreshToken:String)=

      CoroutineScope(Dispatchers.IO).async {

          var accessToken :String?=null

          val client = OkHttpClient()

          val requestBody = FormBody.Builder()

              .add("grant_type", "refresh_token")

              .add("refresh_token", refreshToken)

              .add("client_id", getString(R.string.APP_KEY_DROPBOX))

              .add("client_secret", getString(R.string.APP_SECRET_DROPBOX))

              .build()

          val request = Request.Builder()

              .url("https://api.dropbox.com/oauth2/token")

              .post(requestBody)

              .build()

          val response = client.newCall(request).execute()

          if (response.isSuccessful) {

              val responseData = response.body?.string()

              val json = JSONObject(responseData)

              accessToken = json.getString("access_token")

               accessToken

              println("New access token: $accessToken")

          } else {

              println("Error getting new access token: ${response.code} ${response.message}")

               accessToken

          }

       accessToken

      }.await()

 

For Read:

 private lateinit var clientV2: DbxClientV2
private lateinit var config: DbxRequestConfig
onCreate(){

config=DbxRequestConfig.newBuilder("Test_Hasnain_App").build()

//For Read

        CoroutineScope(Dispatchers.IO).launch {

                try {

                    val accessToken=getAccessToken(getString(R.string.REFRESH_TOKEN))

                    if(accessToken!=null)

                    {

                        clientV2= DbxClientV2(config,accessToken)

                        isAccessTokenValid(accessToken)

                    }



                    val dbxFile= clientV2.files().getTemporaryLink("/box_1_avatar.png")

                    withContext(Dispatchers.Main)

                    {

                        Glide.with(this@MainActivity)

                            .load(dbxFile.link).diskCacheStrategy(DiskCacheStrategy.ALL)

                            .into(binding.imageView)



                        binding.fileName.text=dbxFile.metadata.name

                    }



                    Log.e("APPCAKE",dbxFile.link)

                }

                catch (e:Exception)

                {

                    e.printStackTrace()

                }
        }
        
}

 

For-Write:

CoroutineScope(Dispatchers.IO).launch {

            try {

                val filName="abc.txt"

                val string="Hello-World"

                val folder=File(this@MainActivity.filesDir,"filName")

                folder.mkdir()

                val textFile=File(folder,filName)

                textFile.writeText(string)

                val inputStream=FileInputStream(textFile)

                clientV2.files().uploadBuilder("/abc.txt").uploadAndFinish(inputStream)

                inputStream.close()

            }

            catch (e:Exception)

            {

                e.printStackTrace()

            }
}

 

Generate Refresh Token with POST-MAN

REFRESH_TOEKN_VIA_POST_MAN.png

Results.png

*Copy the refresh token from the results and store this in a string file or local properties.

For better Understanding, a demo project will be shared within a group. Kindly, Explore it.