Subir archivo de texto a Google Drive mediante Android
Editado: He establecido mi texto en una cadena como:
String text = ("¡Hola!");
- El valor no se actualiza onProgress para Range-seek-bar
- ¿Qué optimizaciones puedo esperar de Dalvik y la cadena de herramientas de Android?
- Confundido acerca de la sincronización de varias tablas con el adaptador de sincronización y el proveedor de contenido
- cómo puedo agregar elementos a listview dinámicamente en android
- Android cola las solicitudes de HTTP mientras la red no está disponible y procesa cuando se enciende
Quiero convertirlo en un archivo de texto sin formato y luego subirlo a una carpeta de Google Drive. He intentado en el código de abajo, pero no es completa, así que no puedo decir qué errores aparecen.
Estoy utilizando la demostración de inicio rápido de Google Drive y tratando de adaptarla a lo que necesito. Enlace: https://github.com/googledrive/android-quickstart
DriverClass:
public class UploadDrive extends Activity implements ConnectionCallbacks,OnConnectionFailedListener { private static final String TAG = "androiddrivequickstart"; private static final int REQUEST_CODE_CAPTURE_IMAGE = 1; private static final int REQUEST_CODE_CREATOR = 2; private static final int REQUEST_CODE_RESOLUTION = 3; private GoogleApiClient mGoogleApiClient; private Bitmap mBitmapToSave; private void saveFileToDrive() { // Start by creating a new contents, and setting a callback. Log.i(TAG, "Creating new contents."); //How to call? Can i use File from java.io? final Bitmap image = mBitmapToSave; Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(new ResultCallback<DriveContentsResult>() { @Override public void onResult(DriveContentsResult result) { // If the operation was not successful, we cannot do anything // and must // fail. if (!result.getStatus().isSuccess()) { Log.i(TAG, "Failed to create new contents."); return; } // Otherwise, we can write our data to the new contents. Log.i(TAG, "New contents created."); // Get an output stream for the contents. OutputStream outputStream = result.getDriveContents().getOutputStream(); // Write the bitmap data from it. ByteArrayOutputStream textFile = new ByteArrayOutputStream(); //image.compress(Bitmap.CompressFormat.PNG, 100, textFile); try { outputStream.write(textFile.toByteArray()); } catch (IOException e1) { Log.i(TAG, "Unable to write file contents."); } // Create the initial metadata - MIME type and title. // Note that the user will be able to change the title later. MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder() .setMimeType("text/plain").setTitle("Log: test.txt").build(); // Create an intent for the file chooser, and start it. IntentSender intentSender = Drive.DriveApi .newCreateFileActivityBuilder() .setInitialMetadata(metadataChangeSet) .setInitialDriveContents(result.getDriveContents()) .build(mGoogleApiClient); try { startIntentSenderForResult( intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0); } catch (SendIntentException e) { Log.i(TAG, "Failed to launch file chooser."); } } }); } @Override protected void onResume() { super.onResume(); if (mGoogleApiClient == null) { // Create the API client and bind it to an instance variable. // We use this instance as the callback for connection and connection // failures. // Since no account name is passed, the user is prompted to choose. mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Drive.API) .addScope(Drive.SCOPE_FILE) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); } // Connect the client. Once connected, the camera is launched. mGoogleApiClient.connect(); } @Override protected void onPause() { if (mGoogleApiClient != null) { mGoogleApiClient.disconnect(); } super.onPause(); } @Override protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { switch (requestCode) { case REQUEST_CODE_CAPTURE_IMAGE: // Called after a photo has been taken. if (resultCode == Activity.RESULT_OK) { // Store the image data as a bitmap for writing later. mBitmapToSave = (Bitmap) data.getExtras().get("data"); } break; case REQUEST_CODE_CREATOR: // Called after a file is saved to Drive. if (resultCode == RESULT_OK) { Log.i(TAG, "Image successfully saved."); mBitmapToSave = null; // Just start the camera again for another photo. startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE),REQUEST_CODE_CAPTURE_IMAGE); } break; } } @Override public void onConnectionFailed(ConnectionResult result) { // Called whenever the API client fails to connect. Log.i(TAG, "GoogleApiClient connection failed: " + result.toString()); if (!result.hasResolution()) { // show the localized error dialog. GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show(); return; } // The failure has a resolution. Resolve it. // Called typically when the app is not yet authorized, and an // authorization // dialog is displayed to the user. try { result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION); } catch (SendIntentException e) { Log.e(TAG, "Exception while starting resolution activity", e); } } @Override public void onConnected(Bundle connectionHint) { Log.i(TAG, "API client connected."); if (mBitmapToSave == null) { // This activity has no UI of its own. Just start the camera. startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE), REQUEST_CODE_CAPTURE_IMAGE); return; } saveFileToDrive(); } @Override public void onConnectionSuspended(int cause) { Log.i(TAG, "GoogleApiClient connection suspended"); } }
¿Cómo llamo a finalResultText que está en otra clase llamada MainActivity para que pueda convertirlo en un archivo de texto sin formato que se cargue en una carpeta de Google Drive?
- Vista de lista personalizada de Android
- MVP para Android: ¿Qué es un Interactor?
- Siempre vuelve a la pantalla de inicio de sesión
- Widget de la pestaña siempre en los alfabetos de mayúsculas en Android 4.0
- Cómo utilizar dos fragmentos en Android DrawerLayout
- Denominación del ID en las aplicaciones de Android
- Android Studio no me deja usar el interruptor en una cadena?
- ¿Cómo obtengo una vista de imagen para rotar mientras traduce en Android?
Suponiendo que usted pregunta es: "¿Cómo subo un archivo de texto a Google Drive?", Aquí está la descripción rápida:
1 / Obtenga su aplicación autorizada en la consola de desarrolladores , consulte esto . Básicamente, dígale a Google que su aplicación representada por SHA1 / 'nombre-paquete' necesita acceso a Drive API (no olvide su dirección de correo electrónico en la pantalla de consentimiento). Esta autorización es buena tanto para REST como para GDAA api.
2 / Decida si desea utilizar REST o GDAA API para acceder a la unidad. Cada uno tiene ventajas / desventajas (pero es una historia larga).
3 / Eche un vistazo a la demostración de envoltura REST / GDAA aquí , tiene el proceso de autorización de la aplicación en la clase MainActivity (ver método onConnFail ()) y métodos CRUD básicos para REST y GDAA en sus respectivas clases.
Buena suerte
ACTUALIZAR
Sobre la base de sus comentarios a continuación, supongo que desea forzar la demostración QuickStart para trabajar para usted. Tenga en cuenta que GDAA (o REST) no les importa lo que es el contenido Es sólo un montón de bytes. Por lo tanto, como QuickStart convierte el mapa de bits en PNG y alimenta el flujo de salida con sus bytes, tiene que hacerlo con su montón de bytes. Rápidamente me golpearon juntos 2 primitivos a continuación, que alimentaría el flujo de salida de DriveContents con archivo o matriz de bytes (y puede convertir lo que tiene en un archivo o byte []).
DriveContents file2Cont(DriveContents driveContents, java.io.File file) { OutputStream oos = driveContents.getOutputStream(); if (oos != null) try { InputStream is = new FileInputStream(file); byte[] buf = new byte[8192]; int c = 0; while ((c = is.read(buf, 0, buf.length)) > 0) { oos.write(buf, 0, c); oos.flush(); } } catch (Exception e) {/*handle errors*/} finally { try { oos.close(); } catch (Exception ignore) { } } return driveContents; } DriveContents bytes2Cont(DriveContents driveContents, byte[] buf) { OutputStream os = driveContents.getOutputStream(); try { os.write(buf); } catch (IOException e) {/*handle errors*/} finally { try { os.close(); } catch (Exception e) {/*handle errors*/} } return driveContents; }
- Ejemplo simple de DialogFragment – código de ejemplo no funciona para mí
- ¿Cómo desmarcar el botón de radio sin grupo de radio?