Запись/чтения файла в/из облака

Ответить
akhan
Сообщения: 4
Зарегистрирован: 08 янв 2015, 13:43

Запись/чтения файла в/из облака

Сообщение akhan » 19 мар 2016, 16:31

Здравствуйте.
Я новичок в андроиде.
Не могу понять с чего начинать запись простого текстового файла в один из облак(google drive, yandex disk, one drive - везде есть у меня учетка).
Из developer.google.com, https://tech.yandex.ru/disk/rest/?ncrnd=1067 ничего таки и не понял.
Дайте конкретный работающий пример, пожалуйста.
Уже неделю перерыл весь интернет - не нашел.
Хотя много программировал толстых клиентов для базы данных под windows, никогда не связывался с интернет разработкой.

парень
Сообщения: 223
Зарегистрирован: 30 мар 2013, 22:52

Re: Запись/чтения файла в/из облака

Сообщение парень » 19 мар 2016, 18:04

Как найдешь решение, напиши пожалуйста ))) Тоже интересно )))
Мой первенец: MyMoney. Менеджер расходов

Бьем рекорды русских топов :)

Могу ответить на любые вопросы по маркетингу и развитию.

Sergey777
Сообщения: 68
Зарегистрирован: 30 мар 2015, 17:16

Re: Запись/чтения файла в/из облака

Сообщение Sergey777 » 22 мар 2016, 08:00

akhan писал(а):Здравствуйте.
Я новичок в андроиде.
Не могу понять с чего начинать запись простого текстового файла в один из облак(google drive, yandex disk, one drive - везде есть у меня учетка).
Из developer.google.com, https://tech.yandex.ru/disk/rest/?ncrnd=1067 ничего таки и не понял.
Дайте конкретный работающий пример, пожалуйста.
Уже неделю перерыл весь интернет - не нашел.
Хотя много программировал толстых клиентов для базы данных под windows, никогда не связывался с интернет разработкой.
Здравствуйте. Для работы с Google Drive приложение должно использовать библиотеку Google Play Services.

Первоначальные настройки стандартны. Регистрируем приложение в Google Developers Console и получаем подписанный сертификат. Добавляем необходимые настройки в манифест. Добавляем необходимые сервисы Google Drive в приложение, например, для создания файла. Также нам понадобится SHA1 (Window | Preferences | Android | Build). Для экспериментов можно использовать и отладочный сертификат. Идём в Google Console (https://console.developers.google.com/) и создаём новый проект. В левой колонке выбираем APIs & auth. Включаем использование Drive API.

Далее выбираем Credentials. В зависимости от ваших задач можно использовать два варианта.

Вариант первый. Если требуется авторизация.

Щелкаем кнопку Create New Client ID.

Выбираем Installed application and Android.

В поле Package вводим имя пакета вашего приложения.

Вставляем отпечаток SHA1 в форму.

Щелкаем на Create Client ID.

Вариант второй. Приложение будет использовать вызовы API, не требующие авторизации.

Щелкаем Create New Key.

Выберите кнопку Android key.

Вставляем отпечаток SHA1 в форму.

После отпечатка введите точку с запятой, а затем имя пакета вашего приложения.

Щелкаем кнопку Create.

В документации есть несколько примеров, которые следует изучить!!!

В манифесте прописываем:

Код: Выделить всё

<meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />
Следующий пример сохранения снимка на диске Google Drive. При сохранении выводится диалоговое окно, где можно выбрать имя файла и папку.

Код активности:

Код: Выделить всё

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi.ContentsResult;
import com.google.android.gms.drive.MetadataChangeSet;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.graphics.Bitmap;

import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity implements ConnectionCallbacks,
		OnConnectionFailedListener {
	
	private static final String TAG = "android-drive-quickstart";
    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 static final int REQ_CODE_OPEN = 0;
    
    private GoogleApiClient mGoogleApiClient;
    private Bitmap mBitmapToSave;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

    @Override
    protected void onPause() {
        if (mGoogleApiClient != null) {
            mGoogleApiClient.disconnect();
        }
        super.onPause();
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public void onClick(View v) {
    	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
    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");
    }

	@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");
                    saveFileToDrive();
                }
                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;
        }
    }
	
	/**
     * Create a new file and save it to Drive.
     */
    private void saveFileToDrive() {
        // Start by creating a new contents, and setting a callback.
        Log.i(TAG, "Creating new contents.");
        final Bitmap image = mBitmapToSave;
        Drive.DriveApi.newContents(mGoogleApiClient).setResultCallback(new ResultCallback() {

            @Override
            public void onResult(ContentsResult 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.getContents().getOutputStream();
                // Write the bitmap data from it.
                ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
                image.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
                try {
                    outputStream.write(bitmapStream.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("image/jpeg").setTitle("Android Photo.png").build();
                // Create an intent for the file chooser, and start it.
                IntentSender intentSender = Drive.DriveApi
                        .newCreateFileActivityBuilder()
                        .setInitialMetadata(metadataChangeSet)
                        .setInitialContents(result.getContents())
                        .build(mGoogleApiClient);
                try {
                    startIntentSenderForResult(
                            intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
                } catch (SendIntentException e) {
                    Log.i(TAG, "Failed to launch file chooser.");
                }
            }
        });
    }
}

Ответить