我正在使用Google Drive api将文件上传到Google云端硬盘。我想知道,我如何检查重复文件。因为目前我的服务运行时,它会将文件上传到之前已经上传的google驱动器
这是我的代码:
public class MainActivity extends Activity implements ConnectionCallbacks,
OnConnectionFailedListener {
public ArrayList songsList = new ArrayList();
private static final String TAG = "drive-quickstart";
private GoogleApiClient mGoogleApiClient;
public static ArrayList<File> listAllMusicFiles = new ArrayList<File>();
public static final String EXISTING_FOLDER_ID = "0B2EEtIjPUdX6MERsWlYxN3J6RU0";
private SharedPreferences sharedPreferences;
/**
* DriveId of an existing file to be used in file operation samples..
*/
public static final String EXISTING_FILE_ID = "0ByfSjdPVs9MZTHBmMVdSeWxaNTg";
/**
* Extra for account name.
*/
protected static final String EXTRA_ACCOUNT_NAME = "account_name";
/**
* Request code for auto Google Play Services error resolution.
*/
protected static final int REQUEST_CODE_RESOLUTION = 1;
/**
* Next available request code.
*/
protected static final int NEXT_AVAILABLE_REQUEST_CODE = 2;
private static final String DRIVE_ID = "driveId";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final File mainDir = new File(Environment.getExternalStorageDirectory()
.getPath());
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
loadSdcardfiles(mainDir);
}
/**
* Create a new file and save it to Drive.
*/
private void saveFileToDrive(final File file) {
Log.i(TAG, "Creating new contents.");
Drive.DriveApi.newDriveContents(mGoogleApiClient).setResultCallback(
new ResultCallback<DriveApi.DriveContentsResult>() {
@Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Failed to create new contents.");
return;
}
final DriveContents driveContents = result
.getDriveContents();
// 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.getDriveContents()
.getOutputStream();
// Write the bitmap data from it.
try {
@SuppressWarnings("resource")
FileInputStream fileInputStream = new FileInputStream(
file);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.");
}
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setTitle(file.getName()).build();
// create a file on root folder
Drive.DriveApi
.getRootFolder(mGoogleApiClient)
.createFile(mGoogleApiClient,
metadataChangeSet, driveContents)
.setResultCallback(fileCallback);
try {
} catch (Exception e) {
Log.i(TAG, "Failed to launch file chooser.");
}
}
});
}
private void loadSdcardfiles(File aFile) {
if (aFile.isFile()) {
if (aFile.getAbsolutePath().endsWith(".mp3")) {
listAllMusicFiles.add(aFile);
}
} else if (aFile.isDirectory()) {
File[] listOfFiles = aFile.listFiles();
if (listOfFiles != null) {
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
loadSdcardfiles(listOfFiles[i]);
}
}
} else {
}
}
}
@SuppressWarnings("unchecked")
@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 onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
mGoogleApiClient.connect();
}
}
public void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
@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 (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
@Override
public void onConnected(Bundle connectionHint) {
Toast.makeText(this, "API client connected" + listAllMusicFiles.get(0),
1000).show();
if (listAllMusicFiles.size() == 0) {
return;
} else {
for (int i = 0; i < listAllMusicFiles.size(); i++) {
saveFileToDrive(listAllMusicFiles.get(i));
}
}
}
@Override
public void onConnectionSuspended(int cause) {
Toast.makeText(this, "GoogleApiClient connection suspended", 1000)
.show();
}
// private void storeSumFileId(DriveId driveId) {
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putString(DRIVE_ID, driveId.encodeToString());
// editor.apply();
//
// }
// final private ResultCallback<DriveResource.MetadataResult> metadataRetrievedCallback = new ResultCallback<DriveResource.MetadataResult>() {
// @Override
// public void onResult(DriveResource.MetadataResult result) {
// if (!result.getStatus().isSuccess()) {
// Log.v(TAG, "Problem while trying to fetch metadata.");
// return;
// }
//
// Metadata metadata = result.getMetadata();
// if (metadata.isTrashed()) {
// Log.v(TAG, "Folder is trashed");
// } else {
// Log.v(TAG, "Folder is not trashed");
// }
//
// }
// };
final private ResultCallback<DriveFileResult> fileCallback = new ResultCallback<DriveFileResult>() {
@Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the file");
return;
}
showMessage("Created a file with content: "
+ result.getDriveFile().getDriveId());
// storeSumFileId(result.getDriveFile().getDriveId());
}
};
}
我找到了以下链接,但无法在我的代码中使用它: Google Drive Android API - Check if folder exists
https://developers.google.com/drive/android/trash#trash_or_untrash_a_file_or_folder
有谁能告诉我如何在驱动器上制作现有文件?
感谢。