- Как подключить Google Drive на Android Studio для создания папки или файла?
- 1 ответ
- Integrating Google Drive in Android
- Version
- Getting Started
- Registering for Google Drive
- Building Your Android App
- Updating the Gradle File
- Modifying the Android Manifest
- Creating a File Provider
- Adding Strings
- Updating the UI
- Creating a ServiceListener Interface
- Creating a Data Class: GoogleDriveConfig
- Creating the GoogleDriveService
- Handling Activity Results
- Opening a Picked-File Dialog
- Logging In and Out
- Updating MainActivity
- Handling the OnActivityResult Method
- Where to Go From Here?
Как подключить Google Drive на Android Studio для создания папки или файла?
Я хочу подключиться к Google Drive API в Android studio, создать файл и прочитать этот файл, но не могу подключиться, даже если у меня есть apiKey. Если я отлаживаю, то приложение закрывается после GoogleApiClient.connect , Я исследовал различные страницы, но некоторые из них также снимают отпечатки пальцев SHA1, это необходимо? Что я мог сделать не так?
1 ответ
- Установите Android SDK.
- Загрузите и настройте SDK сервисов Google Play, который включает в себя Google Drive Android API.
- Зарегистрируйте вашу заявку. Для этого вам нужно зарегистрировать проект в консоли API Google и получить сертификат подписи для вашего приложения.
- Добавьте необходимые настройки в манифест вашего приложения.
- Добавьте службы Drive в свое приложение. Самый простой способ начать с создания файла.
С помощью API-интерфейса Drive Android можно создавать файлы двумя способами: с помощью класса CreateFileActivityBuilder или с помощью метода createFile() интерфейса DriveFolder. Конечный результат любого подхода одинаков. Однако для случаев, когда пользователь указывает местоположение или заголовок файла, CreateFileActivityBuilder упрощает процесс, предоставляя готовый пользовательский интерфейс. Чтобы создать файлы программно или разрешить пользователям указывать другие метаданные в пользовательском пользовательском интерфейсе, необходимо использовать метод createFile().
Источник
Integrating Google Drive in Android
See how to integrate the Google Drive SDK in order to let your users access and download their Drive files directly to your app.
Version
- Kotlin 1.2, Android 5.0, Android Studio 3
There are times when a user is required to choose a file to upload into an app. There are many places from which to upload files: local storage on the device, Dropbox, Google Drive and other services. In this tutorial, you will create an app that will authenticate a user with Google, launch Google Drive, and then allow a user to choose a file. Once the user selects a file, the app will download and open it.
The Google Drive SDK is used to connect to a user’s Google Drive files. This tutorial will focus on allowing a user to choose an existing file, download it and display it through the app. You will use Google Drive’s built-in file picker, which will allow us to choose any file that is on the user’s Google drive.
Getting Started
Make sure you have Android Studio and the Kotlin plugin installed before you begin. To install Android Studio go to developer.android.com. Your phone or emulator will need up-to-date Google Play services on the device to run the app.
Since your UI will be bare-bones, open up Android Studio 3.1.1 or later and create a new project. From Android Studio, select Start a new Android Studio project from the startup screen or New Project from the File menu.
Enter the name GoogleDriveDemo, your company domain (or example.com if your wish) and a project location. Make sure that Kotlin support is selected and then press Next.
You shouldn’t need to change anything on this screen. Just click Next.
Select Empty Activity and press Next.
Registering for Google Drive
In order to use the Google Drive SDK, you need to enable the API in your app.
Walking through the steps:
- Go to Google Console.
- Sign up for a developer’s account if you don’t have one or sign in.
- Create a project and click Continue.
Add a project name and click Create.
Select Library on the left-hand side to go to the Search screen.
Type “Google Drive” and select Google Drive API.
At this point, you may be asked to set a name on the consent screen before you create a credential. Do so and then create your credential.
You don’t need to complete the form that appears — only the name is required. Enter a name and press Save:
Click Create credentials.
Select OAuth Client ID.
Choose Android, enter a name and the package name that you used to create your app. Although the hint refers to the package name in AndroidManifest.xml, it has to match the applicationId in build.gradle instead — otherwise, the login flow will fail.
- On Mac or Linux,
/.android/debug.keystore
If everything works correctly, you should see something like this:
Copy the SHA1 value from the terminal into the text field and press Create. The Client ID dialog will appear. Press OK.
Now, you are taken to the Credentials page. Authorization on Android uses the SHA1 fingerprint and package name to identify your app, so you don’t have to download any JSON file or copy any API key or secret to your project.
Building Your Android App
Go back to the Android app and you can start adding settings and code.
Updating the Gradle File
First, you’ll update the build.gradle file inside the app folder. Add two variables for the version of Google Play services and Android support libraries after the apply plugin statements near the top:
This will let you re-use the variables and easily change the versions. Replace the version of com.android.support:appcompat-v7 with the variable, and add the support design library, both in the dependencies block:
The appcompat library contains all of the compatibility classes that help you write code that works on many versions of the Android OS. The design support library is used in this tutorial to display a Snackbar message.
Next, add the libraries for the Google Drive SDK and the Okio library from Square for downloading files.
Now, sync the project Gradle files (File ▸ Sync Project with Gradle Files)
Modifying the Android Manifest
Next, you’ll modify AndroidManifest.xml. Open the file and add internet permissions right above the tag:
Add the following code to specify the version of Google Play Services as the first sub-element in the tag:
If you command-click (or Ctrl-click on PC) on the @integer/google_play_services_version you will see that it takes you to the play services values file that let’s the Google Play SDK know which version you are using.
Creating a File Provider
Next, you’ll create a FileProvider. This is required for Android 8.0 Oreo and above to access local files.
First, create a new directory by right-clicking on the app/res directory and selecing New ▸ Android Resource Directory. Name it xml. Right-click on the xml directory and select New ▸ File; name it provider_paths.
This is needed since Android Oreo does not support sharing file:// urls. Open the new file and paste in the following:
Now, in the Android Manifest file, after the meta-data tag you recently added, add:
This sets up your app to use Android’s FileProvider class to handle local files as urls instead of as files. This is a security restriction that Google has implemented.
Adding Strings
Now, you’ll add the strings that you’ll need for the UI. Open the strings.xml file and add:
The first string is for the Google Drive’s activity title, and the rest are for the UI.
Updating the UI
Next, you’ll update the UI. To do so, you’ll simply create three buttons to Login, Logout, and Open Google Drive, and a TextView to display login status. Open activity_main.xml and replace the contents with the following:
Run the app and make sure the UI is displayed correctly:
If everything works correctly, you should have a basic UI with three buttons and a status message at the bottom. If the project does not compile or something goes wrong when running, compare your work with each of the steps above.
Creating a ServiceListener Interface
Since there are only a few classes, you will put all of them in the root source folder. Start with the interface that the listener of your service must implement. Create a new Kotlin interface named ServiceListener:
You may need to choose Option+Return on macOS Alt+Enter on PC to pull in the import for the File class.
These methods notify the listener when:
- loggedIn() : A user is successfully authenticated.
- fileDownloaded(file: File) : A file is selected and downloaded successfully.
- cancelled() : A login or file selection is cancelled.
- handleError(exception: Exception) : There is any error.
This interface will be implemented by MainActivity and used by a service as a way to let the user of the service know when something has happened.
Creating a Data Class: GoogleDriveConfig
Next, create a simple data class for holding the information that the service needs. Create a new data class named GoogleDriveConfig:
This class contains the title that Google Drive will designate as the activity’s title and the mimeTypes that determines which file types to show.
Creating the GoogleDriveService
Next, you’ll create the actual service. Create a new class named GoogleDriveService:
The class is not an Android Service, but instead acts as a service for MainActivity. You will be adding the following code, in order.
First, add a companion object:
Scopes are Google Drive’s set of permissions. Therefore, by giving a file and an app folder scope, you tell Google Drive to let you handle files and folders.
The mime types are for the type of files you want to allow the user to pick. If you want the user to choose images, you would use image/* . Here, you pick .pdf and .doc/.docx files.
You also have two request codes to use for handling the result of signing in and picking a file. The TAG constant is used for Logging.
After the companion object section, add the following variables:
- serviceListener is the listener of your service.
- driveClient handles high-level drive functions like Create File, Open File, and Sync.
- driveResourceClient handles access to Drive resources and/or files.
- signInAccount keeps track of the currently signed-in account.
Now add a GoogleSignInClient property that is lazily-initialized:
googleSignInClient is created when needed and includes the scopes defined earlier. The last statement returns the GoogleSignInClient .
Handling Activity Results
You need to be able to handle the results from the user who is signing in and picking a file in the MainActivity. Create a method named onActivityResult , which will be called inside onActivityResult of MainActivity:
In the method, you call helper methods or the serviceListener depending on the requestCode . You can check the result against the presence of data instead of resultCode . If no data is returned, it means the user cancelled the action.
Now add the helper method for handling sign in with another method to initialize the drive client:
Once the user has signed in, you handle the result in initializeDriveClient() . This will create your drive clients. It also notifies the listener that the user has successfully signed in.
After a user has picked a file, you will get an activity intent and pass it to openItem() , so add that helper method now:
This function gets the driveId from the intent options and passes that ID to another helper method downloadFile() .
The key aspect of the whole service is downloading the picked file. To do that, you need to get an input stream to the file and save it to a local file. You will use Square’s Okio library to easily take that stream and save it to a file.
Add the downloadFile() method now:
There’s a lot going on in this method. Notice the getMetaData() call. That is needed to get the name of the chosen file. You are then saving the file to your app’s internal download folder (which is not visible to the user), then alerting the listener about the downloaded file and where to find it.
Opening a Picked-File Dialog
You have created the methods to handle the result of signing in and picking a file, but you don’t yet have a method to initiate those actions. Create a method named pickFiles() to open the picked-file dialog:
You set the mime type and title, and then set the starting folder if driveId is provided. Then call pickItem with those options.
Next add the pickItem method:
This will start Google Drive’s File Picker activity, which will call your onActivityResult with the user’s response.
Logging In and Out
Next, you add a method that can retrieve any account that has been signed in from previous launches:
If a signed-in account is found and no scope has changed, you call initializeDriveClient() that you created earlier to handle the sign in. Add the following method to launch the Authentication dialog:
Finally, add a method to allow a user to log out.
Updating MainActivity
Now, you will turn your attention back to the MainActivity.
Above the onCreate() function, create a simple enum to keep track of the buttons state:
As mentioned earlier, the activity needs to be set as a serviceListener so that it can respond to the service. Implement the ServiceListener interface in the MainActivity:
And add the interface methods:
Add properties for the service and button state:
You need to change the state of the buttons based on your logged-in or logged-out state. Consequently, you create a function named setButtons :
status , start , logout , and login are the ID of the views you created in activity_main.xml. You should be able to import them using Option+Return on macOS Alt+Enter on PC as long as you have apply plugin:’kotlin-android-extensions’ in the app module build.gradle, which new projects do by default.
Update onCreate() to be:
Here’s what the above does:
- Creates the service with your title and the document mime types.
- Sets MainActivity as the listener.
- Changes the state to logged-in if there is any logged-in account present.
- Sets the button click listeners. There are three buttons: Login, Pick a File and Logout.
- Updates views based on the current state.
Handling the OnActivityResult Method
Add the onActivityResult() method and have it pass the result to the service:
Now, add implementations for the listener methods:
The code inside loggedIn() , cancelled() , and handleError() are pretty straightforward. They update the UI and/or display messages with Snackbar .
In fileDownloaded() , a file is received; subsequently, you want the system to open the file. This is where the FileProvider information you put in the AndroidManifest.xml file comes in.
In Android 8.0 Oreo and above, you can no longer open file:// url’s, so you need to provide your own FileProvider for that. You don’t need any other code than this. MimeTypeMap is a system class that has a few helper methods you can use to get the file extension and mime type from the url. You create an intent and make sure that the system can handle it before starting the activity — the app will crash otherwise.
Time to give it a try! Build and run the app.
First, try logging in:
You will first be presented with an account chooser. After you’ve chosen an account, you’ll need to give the app permissions to access your Google Drive.
Next, hit the “Start Google Drive” button, and you will see your files like this:
Once you select a file and press Select, the download process will start. After the download is complete, you should then see the file you picked automatically open in a system viewer.
Where to Go From Here?
In this tutorial, you have learned how to integrate your app with Google Drive and how to download a file. Congratulations on successfully downloading files from your Google Drive!
You can download the final project by using the download button at the top or bottom of this tutorial.
You can do much more with Google Drive. Try, for example, adding more capabilities to your app, such as creating a file or deleting a file. Check out the documentation about other Google Drive SDK features for Android.
If you have any comments or questions about this tutorial or Google Drive SDK, feel free to join the forum discussion below!
Источник