2016-04-14 14 views
3

Ich benutze das Laufwerk API, um eine Datei im versteckten App-Ordner auf Google Drive zu erstellen. Ich möchte die Ressourcen-ID dieser Datei erhalten, aber sie gibt immer null zurück. Hier ist der Code. Sobald die Datei erstellt wurde, sollte sie die Dateiressourcen-ID im Aufruf zurück erhalten, aber sie gibt null zurück. Das normale Laufwerk ist in Ordnung, aber das hilft überhaupt nicht, da die ID des Abruf-Laufwerks die Ressourcen-ID benötigt. irgendeine Idee, wie man die Ressourcenidentifikation bekommt. Ich habe mehrere verschiedene Links zu diesem Thema überprüft und alle von ihnen sind keine Hilfe.Get Resource ID für Google Drive API Android

//<editor-fold desc="Variables"> 

// Define Variable Int MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE// 
public static int MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE = 0; 

// Define Variable int RESOLVE_CONNECTION_REQUEST_CODE// 
public static final int RESOLVE_CONNECTION_REQUEST_CODE = 3; 

// Define Variable GoogleApiClient googleApiClient// 
public GoogleApiClient googleApiClient; 

// Define Variable String title// 
String title = "Notes.db"; 

// Define Variable String mime// 
String mime = "application/x-sqlite3"; 

// Define Variable String currentDBPath// 
String dBPath = "/School Binder/Note Backups/Notes.db"; 

// Define Variable File data// 
File data = Environment.getExternalStorageDirectory(); 

// Define Variable File dbFile// 
File dbFile = new File(data, dBPath); 

// Create Metadata For Database Files// 
MetadataChangeSet meta = new MetadataChangeSet.Builder().setTitle(title).setMimeType(mime).build(); 

String EXISTING_FILE_ID = "CAESABjaBSCMicnCsFQoAA"; 

//</editor-fold> 

// Method That Runs When Activity Starts// 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    // Initiate allowWriteExternalStorage Method// 
    allowWriteExternalStorage(); 

    // Initiate connectToGoogleDrive Method// 
    connectToGoogleDrive(); 
} 

// Method That Runs When App Is Resumed// 
protected void onResume() { 
    super.onResume(); 

    // Checks If Api Client Is Null// 
    if (googleApiClient == null) { 

     // Create Api Client// 
     googleApiClient = new GoogleApiClient.Builder(this) 
       .addApi(Drive.API) 
       .addScope(Drive.SCOPE_FILE) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .build(); 
    } 

    // Attempt To Connect To Google drive// 
    googleApiClient.connect(); 
} 

// Method That Runs When App is paused// 
@Override 
protected void onPause() { 

    // Checks If Api Was Used// 
    if (googleApiClient != null) { 

     // Disconnect From Google Drive// 
     googleApiClient.disconnect(); 
    } 
    super.onPause(); 
} 

// Method That Runs When App Is Successfully Connected To Users Google Drive// 
@Override 
public void onConnected(@Nullable Bundle bundle) { 

    // Add New File To Drive// 
    Drive.DriveApi.newDriveContents(googleApiClient).setResultCallback(contentsCallback); 

} 

// Method That Runs When Connection Is Suspended// 
@Override 
public void onConnectionSuspended(int i) { 

} 

// Method That Runs When App Failed To Connect To Google Drive// 
@Override 
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

    // Checks If Connection Failure Can Be Resolved// 
    if (connectionResult.hasResolution()) { 

     // If Above Statement Is True, Try To Fix Connection// 
     try { 

      // Resolve The Connection// 
      connectionResult.startResolutionForResult(this, RESOLVE_CONNECTION_REQUEST_CODE); 

     } catch (IntentSender.SendIntentException ignored) { 
     } 

    } else { 

     // Show Connection Error// 
     GoogleApiAvailability.getInstance().getErrorDialog(this, connectionResult.getErrorCode(), 0).show(); 
    } 
} 

// Method That Gives App Permission To Access System Storage// 
public void allowWriteExternalStorage() { 

    // Allow Or Un - Allow Write To Storage// 
    if (ContextCompat.checkSelfPermission(this, 
      Manifest.permission.WRITE_EXTERNAL_STORAGE) 
      != PackageManager.PERMISSION_GRANTED) { 

     // Request To Write To External Storage// 
     ActivityCompat.requestPermissions(MainActivity.this, 
       new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 
       MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE); 

    } 
} 

// Method That Connects To Google Drive// 
public void connectToGoogleDrive() { 

    // Create Api Client// 
    googleApiClient = new GoogleApiClient.Builder(this) 
      .addApi(Drive.API) 
      .addScope(Drive.SCOPE_FILE) 
      .addScope(Drive.SCOPE_APPFOLDER) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .build(); 

    // Attempt To Connect To Google drive// 
    googleApiClient.connect(); 
} 

//<editor-fold desc="Contents Callback"> 

// What Happens When App Is Trying To Make A New File Or Folder// 
final private ResultCallback<DriveApi.DriveContentsResult> contentsCallback = new ResultCallback<DriveApi.DriveContentsResult>() { 

    @Override 
    public void onResult(@NonNull DriveApi.DriveContentsResult result) { 

     // Runs When File Failed To Create// 
     if (!result.getStatus().isSuccess()) { 

      // Log That File Failed To Create// 
      Log.d("log", "Error while trying to create new file contents"); 

      return; 
     } 

     // Checks If Creating File Was Successful// 
     DriveContents cont = result.getStatus().isSuccess() ? result.getDriveContents() : null; 

     // Write File// 
     if (cont != null) try { 
      OutputStream oos = cont.getOutputStream(); 
      if (oos != null) try { 
       InputStream is = new FileInputStream(dbFile); 
       byte[] buf = new byte[5000]; 
       int c; 
       while ((c = is.read(buf, 0, buf.length)) > 0) { 
        oos.write(buf, 0, c); 
        oos.flush(); 
       } 
      } finally { 

       oos.close(); 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     // Put File In User Hidden App Folder// 
     Drive.DriveApi.getAppFolder(googleApiClient).createFile(googleApiClient, meta, cont).setResultCallback(fileCallback); 
    } 
}; 

//</editor-fold> 

//<editor-fold desc="File Callback"> 

// What Happens If File IS mAde Correctly Or In-Correctly// 
final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new ResultCallback<DriveFolder.DriveFileResult>() { 

    @Override 
    public void onResult(@NonNull DriveFolder.DriveFileResult result) { 

     // Checks If It Failed// 
     if (!result.getStatus().isSuccess()) { 

      Log.d("log", "Error while trying to create the file"); 
      return; 
     } 

     Drive.DriveApi.requestSync(googleApiClient); 

     Log.d("log", "Created a file in App Folder: " + result.getDriveFile().getDriveId()); 

     String File_ID = String.valueOf(result.getDriveFile().getDriveId().getResourceId()); 

     Drive.DriveApi.fetchDriveId(googleApiClient, File_ID).setResultCallback(idCallback); 
    } 
}; 

//</editor-fold> 

//<editor-fold desc="Id Callback"> 

final private ResultCallback<DriveApi.DriveIdResult> idCallback = new ResultCallback<DriveApi.DriveIdResult>() { 
    @Override 
    public void onResult(DriveApi.DriveIdResult result) { 
     if (!result.getStatus().isSuccess()) { 

      Log.d("Message", "Cannot find DriveId. Are you authorized to view this file?"); 

      return; 
     } 
     DriveId driveId = result.getDriveId(); 
     DriveFile file = driveId.asDriveFile(); 
     file.getMetadata(googleApiClient) 
       .setResultCallback(metadataCallback); 
    } 
}; 

//</editor-fold> 

//<editor-fold desc="metadata Callback"> 

final private ResultCallback<DriveResource.MetadataResult> metadataCallback = new 
     ResultCallback<DriveResource.MetadataResult>() { 
      @Override 
      public void onResult(DriveResource.MetadataResult result) { 
       if (!result.getStatus().isSuccess()) { 

        Log.d("Message", "Problem while trying to fetch metadata"); 
        return; 
       } 
       Metadata metadata = result.getMetadata(); 

       Log.d("Message", "Metadata successfully fetched. Title: " + metadata.getTitle()); 
      } 
     }; 

//</editor-fold> 
} 

Antwort

4

Sie wie das nicht tun, lassen sich DriveEventService diese Aufgabe zu bewältigen:

public class GoogleDriveEventService extends DriveEventService { 
    private static final String TAG = "GoogleDriveEventService"; 

    @Override 
    public void onCompletion(CompletionEvent event) { 
     super.onCompletion(event); 
     DriveId driveId = event.getDriveId(); 
     String resourceId = driveId.getResourceId(); 

    }  
} 

UPDATEAndroidManifest.xml

<service 
    android:name="training.com.services.GoogleDriveEventService" android:exported="true"> 
    <intent-filter> 
     <action android:name="com.google.android.gms.drive.events.HANDLE_EVENT"/> 
    </intent-filter> 
</service> 
+0

, wie ich das oben in meinen Code übernehmen kann? danke für die Antwort aber :) – Jordan

+1

Erstellen Sie einfach neue Klasse. Und es wird funktionieren wie Rundfunkempfänger für Sie. Führen Sie diese Methode immer nach dem Hochladen der Datei in das Laufwerk aus. Vergessen Sie nicht, dies mit Ihrer Manifest-Datei zu definieren. Ich bin nicht online im PC, also kann ich es nicht für Sie posten. Ich werde es später poste –

+0

danke Ich schätze es wirklich – Jordan