Java Google Drive Android API,上传后获取文件ID



我使用的是Google Drive Android API。这是我的问题:上传一个文件(image.png(后,我需要文件id(为我的数据库建立一个URL(。但经过许多天的研究(谷歌,文档(,我找不到解决方案。许多人谈论REST API或旧版本(贬值(的Google Drive Android API。

这是我上传文件的主页:

package eu.epitech.tuto;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.drive.*;
import com.google.android.gms.drive.widget.DataBufferAdapter;
import com.google.android.gms.tasks.Task;
import java.io.*;
public class ReportAnIssueActivity extends AppCompatActivity {
public static final int GET_FROM_GALLERY = 3;
private static final String TAG = "drive-quickstart";
private static final int REQUEST_CODE_SIGN_IN = 0;
private static final int REQUEST_CODE_CAPTURE_IMAGE = 1;
private static final int REQUEST_CODE_CREATOR = 2;
private DataBufferAdapter<Metadata> mResultsAdapter;
private DriveClient mDriveClient;
private DriveResourceClient mDriveResourceClient;
private Bitmap mBitmapToSave;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report_an_issue);
mResultsAdapter = new ResultsAdapter(this);
signIn();
}
public void importPicture(View view) {
startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE), REQUEST_CODE_CAPTURE_IMAGE);
}
private void buildIssue(String url) {
System.out.println("URL:" + url);
/* Comment because i can't have my url */
/*EditText text = findViewById(R.id.textview_title);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
//    ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
//   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//                                          int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
String pos = longitude + ":" + latitude;
addIssueToBdd(text.getText().toString(), url, "Anonymous", null, pos);*/
}
private void createIssue() {
saveFileToDrive();
}
private void createPictureFile(Bitmap bitmap) throws IOException {
//create a file to write bitmap data
String filename = "mytmp";
File f = new File(getCacheDir(), filename);
if (!f.createNewFile())
return;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
}
private void addIssueToBdd(String title, String pictureUrl, String owner, String date, String location) {
Bdd bdd = new Bdd("tuto");
Issue issue = new Issue(title, pictureUrl, owner, date, location);
bdd.addIssue(issue);
}
/**
* Start sign in activity.
*/
private void signIn() {
Log.i(TAG, "Start sign in");
GoogleSignInClient GoogleSignInClient = buildGoogleSignInClient();
startActivityForResult(GoogleSignInClient.getSignInIntent(), REQUEST_CODE_SIGN_IN);
}
/**
* Build a Google SignIn client.
*/
private GoogleSignInClient buildGoogleSignInClient() {
GoogleSignInOptions signInOptions =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.build();
return GoogleSignIn.getClient(this, signInOptions);
}
/**
* 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;
mDriveResourceClient
.createContents()
.addOnFailureListener(e -> Log.w(TAG, "Failed to create new contents.", e))
.continueWithTask(task -> createFileIntentSender(task.getResult(), image));
}
/**
* Creates an {@link IntentSender} to start a dialog activity with configured {@link
* CreateFileActivityOptions} for user to create a new photo in Drive.
*/
private Task<Void> createFileIntentSender(DriveContents driveContents, Bitmap image) {
Log.i(TAG, "New contents created.");
// Get an output stream for the contents.
OutputStream outputStream = driveContents.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 e) {
Log.w(TAG, "Unable to write file contents.", e);
}
// 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/png")
.setTitle("issue.png")
.build();
// Set up options to configure and display the create file activity.
CreateFileActivityOptions createFileActivityOptions =
new CreateFileActivityOptions.Builder()
.setInitialMetadata(metadataChangeSet)
.setInitialDriveContents(driveContents)
.build();
return mDriveClient
.newCreateFileActivityIntentSender(createFileActivityOptions)
.continueWith(task -> {
startIntentSenderForResult(task.getResult(), REQUEST_CODE_CREATOR, null, 0, 0, 0);
return null;
});
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_SIGN_IN:
Log.i(TAG, "Sign in request code");
if (resultCode == RESULT_OK) {
Log.i(TAG, "Signed in successfully.");
mDriveClient = Drive.getDriveClient(this, GoogleSignIn.getLastSignedInAccount(this));
mDriveResourceClient =
Drive.getDriveResourceClient(this, GoogleSignIn.getLastSignedInAccount(this));
}
break;
case REQUEST_CODE_CAPTURE_IMAGE:
Log.i(TAG, "capture image request code");
if (resultCode == Activity.RESULT_OK) {
Log.i(TAG, "Image captured successfully.");
mBitmapToSave = (Bitmap) data.getExtras().get("data");
ImageButton image = findViewById(R.id.imageButton);
image.setImageBitmap(mBitmapToSave);
createIssue();
}
break;
case REQUEST_CODE_CREATOR:
mBitmapToSave = null;
if (resultCode == RESULT_OK) {
// Here the file can be not yet uploded...
}
break;
}
}
/**
* Clears the result buffer to avoid memory leaks as soon
* as the activity is no longer visible by the user.
*/
@Override
protected void onStop() {
super.onStop();
mResultsAdapter.clear();
}
}

我需要使用Google Drive Android APi,你能帮我获取文件ID吗?

我认为您在成功上传文件后会得到fileID

以下是谷歌文档中的示例代码:

File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = driveService.files().create(fileMetadata, mediaContent)
.setFields("id")
.execute();
System.out.println("File ID: " + file.getId());

最新更新