Google Drive API实施Xamarin Android

时间:2016-07-18 08:59:11

标签: xamarin google-drive-api xamarin.android

我们的应用程序应具有将应用程序文件保存到Google云端硬盘的功能。当然,使用本地配置的帐户。

Android API我试图找出一些线索。但是使用Xamarin实现的android API对我来说似乎很难。

我已经安装了来自Xamarin Components的Google Play Services- Drive,但没有列出我们可以参考流程和功能的示例。

1 个答案:

答案 0 :(得分:3)

基本步骤(有关完整详情,请参阅以下链接):

  • 使用云端硬盘API和范围

  • 创建GoogleApiClient
  • 尝试连接(登录)GoogleApiClient

  • 您第一次尝试连接时会失败,因为用户未选择应该使用的Google帐户

    • 使用StartResolutionForResult来处理此情况
  • 连接GoogleApiClient

    • 请求驱动器内容(DriveContentsResult)将文件内容写入。

    • 获得结果后,将数据写入云端硬盘内容。

    • 设置文件的元数据

    • 使用云端硬盘内容

    • 创建基于云端硬盘的文件

注意:此示例假设您已在设备/模拟器上安装了Google云端硬盘,并且已在Google的Developer API控制台中注册了已启用Google Drive API的应用。

C#示例:

[Activity(Label = "DriveOpen", MainLauncher = true, Icon = "@mipmap/icon")]
public class MainActivity : Activity, GoogleApiClient.IConnectionCallbacks, IResultCallback, IDriveApiDriveContentsResult
{
    const string TAG = "GDriveExample";
    const int REQUEST_CODE_RESOLUTION = 3;

    GoogleApiClient _googleApiClient;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        SetContentView(Resource.Layout.Main);

        Button button = FindViewById<Button>(Resource.Id.myButton);
        button.Click += delegate
        {
            if (_googleApiClient == null)
            {
                _googleApiClient = new GoogleApiClient.Builder(this)
                  .AddApi(DriveClass.API)
                  .AddScope(DriveClass.ScopeFile)
                  .AddConnectionCallbacks(this)
                  .AddOnConnectionFailedListener(onConnectionFailed)
                  .Build();
            }
            if (!_googleApiClient.IsConnected)
                _googleApiClient.Connect();
        };
    }

    protected void onConnectionFailed(ConnectionResult result)
    {
        Log.Info(TAG, "GoogleApiClient connection failed: " + result);
        if (!result.HasResolution)
        {
            GoogleApiAvailability.Instance.GetErrorDialog(this, result.ErrorCode, 0).Show();
            return;
        }
        try
        {
            result.StartResolutionForResult(this, REQUEST_CODE_RESOLUTION);
        }
        catch (IntentSender.SendIntentException e)
        {
            Log.Error(TAG, "Exception while starting resolution activity", e);
        }
    }

    public void OnConnected(Bundle connectionHint)
    {
        Log.Info(TAG, "Client connected.");
        DriveClass.DriveApi.NewDriveContents(_googleApiClient).SetResultCallback(this);
    }

    protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        base.OnActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_RESOLUTION)
        {
            switch (resultCode)
            {
                case Result.Ok:
                    _googleApiClient.Connect();
                    break;
                case Result.Canceled:
                    Log.Error(TAG, "Unable to sign in, is app registered for Drive access in Google Dev Console?");
                    break;
                case Result.FirstUser:
                    Log.Error(TAG, "Unable to sign in: RESULT_FIRST_USER");
                    break;
                default:
                    Log.Error(TAG, "Should never be here: " + resultCode);
                    return;
            }
        }
    }

    void IResultCallback.OnResult(Java.Lang.Object result)
    {
        var contentResults = (result).JavaCast<IDriveApiDriveContentsResult>();
        if (!contentResults.Status.IsSuccess) // handle the error
            return;
        Task.Run(() =>
        {
            var writer = new OutputStreamWriter(contentResults.DriveContents.OutputStream);
            writer.Write("Stack Overflow");
            writer.Close();
            MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                   .SetTitle("New Text File")
                   .SetMimeType("text/plain")
                   .Build();
            DriveClass.DriveApi
                      .GetRootFolder(_googleApiClient)
                      .CreateFile(_googleApiClient, changeSet, contentResults.DriveContents);
        });
    }

    public void OnConnectionSuspended(int cause)
    {
        throw new NotImplementedException();
    }

    public IDriveContents DriveContents
    {
        get
        {
            throw new NotImplementedException();
        }
    }

    public Statuses Status
    {
        get
        {
            throw new NotImplementedException();
        }
    }
}

参考:https://developers.google.com/drive/android/create-file