2016-07-01 21 views
1

AndroidドライブにGoogleドライブAPIを組み込もうとしています。AndroidドライブでGoogleドライブの[アカウントを選択]画面が表示されない

私はbuild.gradleにGoogle Playサービスを追加し、Android APIキーを取得しました。私の問題は、ユーザーがアカウントを選択したOnResume()内にあります。

アカウントを選択するためにユーザーの再送信を続行するだけで、続行しません。

誰でも助けてもらえますか?

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener{ 

    private static final String TAG = "Google Drive Activity"; 
    private static final int REQUEST_CODE_RESOLUTION = 1; 
    private static final int REQUEST_CODE_OPENER = 2; 
    private GoogleApiClient mGoogleApiClient; 
    private boolean fileOperation = false; 
    private DriveId mFileId; 
    public DriveFile file; 

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


    @Override 
    protected void onResume() { 
     super.onResume(); 
     if (mGoogleApiClient == null) { 

      mGoogleApiClient = new GoogleApiClient.Builder(this) 
        .addApi(Drive.API) 
        .addScope(Drive.SCOPE_FILE) 
        .addConnectionCallbacks(this) 
        .addOnConnectionFailedListener(this) 
        .build(); 
     } 

     mGoogleApiClient.connect(); 
    } 

    @Override 
    protected void onStop() { 
     super.onStop(); 
     if (mGoogleApiClient != null) { 

      // disconnect Google API client connection 
      mGoogleApiClient.disconnect(); 
     } 
     super.onPause(); 
    } 

    @Override 
    public void onConnectionFailed(ConnectionResult result) { 
     Log.i(TAG, "GoogleApiClient connection failed: " + result.toString()); 

     if (!result.hasResolution()) { 
      GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show(); 
      return; 
     } 


     try { 
      result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION); 
     } catch (IntentSender.SendIntentException e) { 
      Log.e(TAG, "Exception while starting resolution activity", e); 
     } 
    } 

    @Override 
    public void onConnected(Bundle connectionHint) { 

     Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show(); 
    } 

    @Override 
    public void onConnectionSuspended(int cause) { 

     Log.i(TAG, "GoogleApiClient connection suspended"); 
    } 

    public void onClickCreateFile(View view){ 
     fileOperation = true; 
     Drive.DriveApi.newDriveContents(mGoogleApiClient) 
       .setResultCallback(driveContentsCallback); 
    } 

    public void onClickOpenFile(View view){ 
     fileOperation = false; 
     Drive.DriveApi.newDriveContents(mGoogleApiClient) 
       .setResultCallback(driveContentsCallback); 
    } 

    public void OpenFileFromGoogleDrive(){ 
     IntentSender intentSender = Drive.DriveApi 
       .newOpenFileActivityBuilder() 
       .setMimeType(new String[] { "text/plain", "text/html" }) 
       .build(mGoogleApiClient); 
     try { 
      startIntentSenderForResult(
        intentSender, REQUEST_CODE_OPENER, null, 0, 0, 0); 
     } catch (IntentSender.SendIntentException e) { 
      Log.w(TAG, "Unable to send intent", e); 
     } 
    } 


    final ResultCallback<DriveApi.DriveContentsResult> driveContentsCallback = 
      new ResultCallback<DriveApi.DriveContentsResult>() { 
       @Override 
       public void onResult(DriveApi.DriveContentsResult result) { 
        if (result.getStatus().isSuccess()) { 
         if (fileOperation == true) { 
          CreateFileOnGoogleDrive(result); 
         } else { 
          OpenFileFromGoogleDrive(); 
         } 
        } 
       } 
      }; 


    public void CreateFileOnGoogleDrive(DriveApi.DriveContentsResult result){ 
     final DriveContents driveContents = result.getDriveContents(); 

     new Thread() { 
      @Override 
      public void run() { 
       // write content to DriveContents 
       OutputStream outputStream = driveContents.getOutputStream(); 
       Writer writer = new OutputStreamWriter(outputStream); 
       try { 
        writer.write("Hello abhay!"); 
        writer.close(); 
       } catch (IOException e) { 
        Log.e(TAG, e.getMessage()); 
       } 

       MetadataChangeSet changeSet = new MetadataChangeSet.Builder() 
         .setTitle("abhaytest2") 
         .setMimeType("text/plain") 
         .setStarred(true).build(); 

       Drive.DriveApi.getRootFolder(mGoogleApiClient) 
         .createFile(mGoogleApiClient, changeSet, driveContents) 
         .setResultCallback(fileCallback); 
      } 
     }.start(); 
    } 

    final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new 
      ResultCallback<DriveFolder.DriveFileResult>() { 
       @Override 
       public void onResult(DriveFolder.DriveFileResult result) { 
        if (result.getStatus().isSuccess()) { 
         Toast.makeText(getApplicationContext(), "file created: "+""+ 
           result.getDriveFile().getDriveId(), Toast.LENGTH_LONG).show(); 
        } 
        return; 
       } 
      }; 

    @Override 
    protected void onActivityResult(final int requestCode, 
            final int resultCode, final Intent data) { 
     switch (requestCode) { 
      case REQUEST_CODE_OPENER: 
       if (resultCode == RESULT_OK) { 
        mFileId = (DriveId) data.getParcelableExtra(
          OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID); 
        Log.e("file id", mFileId.getResourceId() + ""); 
        String url = "https://drive.google.com/open?id="+ mFileId.getResourceId(); 
        Intent i = new Intent(Intent.ACTION_VIEW); 
        i.setData(Uri.parse(url)); 
        startActivity(i); 
       } 
       break; 
      default: 
       super.onActivityResult(requestCode, resultCode, data); 
       break; 
     } 
    } 
} 

これは私のマニフェストです。 APIキーをブロックする。

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="edu.moli9479csumb.version1googledrive"> 

    <uses-permission android:name="android.permission.INTERNET" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme"> 
     <meta-data 
      android:name="com.google.android.geo.API_KEY" 
      android:value="AIzaSyD_2eJ5pPdRMysVwxxxxxxxxxxxxxx"/> 
     <meta-data 
      android:name="com.google.android.gms.version" 
      android:value="@integer/google_play_services_version"/> 

     <activity android:name=".MainActivity"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

</manifest> 
+0

ここで愚かな質問をしましたが、Google開発者向けコンソールでドライブAPIを有効にしましたか? – Rajeev

+0

@Rajeev haはい私はしました。 – TheLearner

+0

GoogleドライブAPIを使用している場合、[Infiniteの[アカウントを選択]ループが繰り返される可能性があります](http://stackoverflow.com/questions/35503195/infinite-choose-an-account-loop-when-using-google-drive-api ) –

答えて

0

マニフェストを共有できますか? 次の画面が表示されるクラスに明示的なマニフェストを作成してください。

+0

はい、もちろんです。それは今起きているはずです。 – TheLearner

0

GoogleApiClientが接続できず、ユーザーがAPI用のアプリケーションを承認する必要がある場合は、AccountSelectorを取得します。これは、 "result.startResolutionForResult(this、REQUEST_CODE_RESOLUTION);" onConnectionFailedメソッドから取得します。

ユーザーがアカウントを選択すると、アクティビティはコードREQUEST_CODE_RESOLUTIONでコールバックを取得します。このコードを処理する必要があります。このコードをonActivityResultメソッドで受け取ったときに、再度接続するにはapiClient.connect()を呼び出す必要があります。

詳細はthisを参照してください。私はそれがうまくいってほしい:)

0

[Account Picker](https://developer.android.com/reference/android/accounts/AccountManager.html#newChooseAccountIntent(android.accounts.Account、java.util.ArrayList、java.lang.String []、ブール値、java.lang.Stringを使用して、ユーザーに簡単にアカウントを選択させることができます、java.lang.String、java.lang.String []、android.os.Bundle))、共通アカウントのピッカーは、newChooseAccountIntentで導入された標準のフレームワークアカウントのピッカーと似ています。ユーザーにアカウントの一覧から選択を促すインテントをアクティビティに返します。呼び出し元は通常、startActivityForResult(intent, ...);を呼び出してアクティビティを開始します。

成功すると、アクティビティは、KEY_ACCOUNT_NAMEKEY_ACCOUNT_TYPEというキーを使用して指定されたアカウント名とタイプのバンドルを返します。ユーザーが選択および/またはアカウントを作成したとき

Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[]{"com.google"}, 
false, null, null, null, null); 
startActivityForResult(intent, SOME_REQUEST_CODE); 

アカウントピッカーの活動が返され、そして得られたアカウント名は、次のことができます。

最も一般的なケースは、例えば、1つのアカウントの種類でこれを呼び出すことです次のように取得すること:

protected void onActivityResult(final int requestCode, final int resultCode, 
final Intent data) { 
if (requestCode == SOME_REQUEST_CODE && resultCode == RESULT_OK) { 
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME); 
} 
} 

はここでAPIを使用する方法を具体的に説明して上記のコードを使用して公式のGoogleサンプルコードです:https://developers.google.com/drive/v3/web/quickstart/android#step_5_setup_the_sample

0

あなたのonResume()とonConnectionFailded()メソッドを見てください。

@Override 
protected void onResume() { 
    super.onResume(); 
    if (mGoogleApiClient == null) { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addApi(Drive.API) 
       .addScope(Drive.SCOPE_FILE) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .build(); 
    } 
    mGoogleApiClient.connect(); 
} 


@Override 
public void onConnectionFailed(ConnectionResult result) { 
    Log.i(TAG, "GoogleApiClient connection failed: " + result.toString()); 

    if (!result.hasResolution()) { 
     GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show(); 
     return; 
    } 


    try { 
     result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION); 
    } catch (IntentSender.SendIntentException e) { 
     Log.e(TAG, "Exception while starting resolution activity", e); 
    } 
} 

どうしますか?

onResume()では、GoogleApiClientを作成してconnect()を呼び出します。あなたがアカウントで承認されていないため、接続が失敗します。メソッドonConnectionFailed()が実行され、結果として実際に呼び出される別のアクティビティである解決を開きます。あなたはアカウントを選択しますが、承認が失敗するかキャンセルされたと思います。 元のアクティビティに戻り、onResume()が実行されます。そしてあなたはもう一度完全な円になります。 認証が失敗するのはなぜですか?あなたの信任状に間違いがあるので、私は推測します。デベロッパーコンソールに移動し、パッケージとキーシグネチャのO認証資格情報を作成します。

関連する問題