Android 如何停止在谷歌硬盘上上传重复文件?

Android 如何停止在谷歌硬盘上上传重复文件?,android,google-drive-android-api,Android,Google Drive Android Api,我正在使用Google Drive api将文件上载到Google Drive。我想知道,我怎样才能检查重复的文件。因为目前我的服务运行时,它会将之前已经上传的文件上传到google drive 这是我的密码: public class MainActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener { public ArrayList songsList

我正在使用Google Drive api将文件上载到Google Drive。我想知道,我怎样才能检查重复的文件。因为目前我的服务运行时,它会将之前已经上传的文件上传到google drive

这是我的密码:

 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());
        }
    };
}
public类MainActivity扩展活动实现ConnectionCallbacks,
OnConnectionFailedListener{
public ArrayList songsList=new ArrayList();
专用静态最终字符串TAG=“驱动器快速启动”;
私人GoogleapClient MGoogleapClient;
公共静态ArrayList listAllMusicFiles=new ArrayList();
公共静态最终字符串现有\u文件夹\u ID=“0B2EEtIjPUdX6MERsWlYxN3J6RU0”;
私人共享引用共享引用;
/**
*要在文件操作示例中使用的现有文件的DriveId。。
*/
公共静态最终字符串现有_文件_ID=“0ByfSjdPVs9MZTHBmMVdSeWxaNTg”;
/**
*帐户名另加。
*/
受保护的静态最终字符串EXTRA\u ACCOUNT\u NAME=“ACCOUNT\u NAME”;
/**
*自动谷歌播放服务错误解决的请求代码。
*/
受保护的静态最终整数请求\代码\分辨率=1;
/**
*下一个可用的请求代码。
*/
受保护的静态最终整数下一个可用请求代码=2;
专用静态最终管柱驱动器\u ID=“driveId”;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
final File mainDir=新文件(Environment.getExternalStorageDirectory())
.getPath());
SharedReferences=PreferenceManager.GetDefaultSharedReferences(此);
loadsCardFiles(mainDir);
}
/**
*创建新文件并将其保存到驱动器。
*/
私有void saveFileToDrive(最终文件){
Log.i(标记“创建新内容”);
Drive.DriveApi.newDriveContents(mgoogleapClient).setResultCallback(
新的ResultCallback(){
@凌驾
public void onResult(DriveApi.DriveContentsResult结果){
如果(!result.getStatus().issucess()){
Log.i(标记“未能创建新内容”);
返回;
}
最终驱动器内容驱动器内容=结果
.getDriveContents();
//否则,我们可以将数据写入新内容。
Log.i(标记“创建的新内容”);
//获取内容的输出流。
OutputStream OutputStream=result.getDriveContents()
.getOutputStream();
//从中写入位图数据。
试一试{
@抑制警告(“资源”)
FileInputStream FileInputStream=新FileInputStream(
文件);
字节[]缓冲区=新字节[1024];
int字节读取;
而((bytesRead=fileInputStream.read(缓冲区))!=-1){
写入(缓冲区,0,字节读取);
}
}捕获(IOE1异常){
Log.i(标记“无法写入文件内容”);
}
MetadataChangeSet MetadataChangeSet=新建MetadataChangeSet.Builder()
.setTitle(文件.getName()).build();
//在根文件夹上创建文件
Drive.DriveApi
.getRootFolder(mgoogleAppClient)
.createFile(mGoogleApiClient,
metadataChangeSet,driveContents)
.setResultCallback(文件回调);
试一试{
}捕获(例外e){
Log.i(标记“未能启动文件选择器”);
}
}
});
}
私有void loadsCardFiles(文件A文件){
if(aFile.isFile()){
if(aFile.getAbsolutePath().endsWith(“.mp3”)){
列出所有音乐文件。添加(文件);
}
}else if(aFile.isDirectory()){
File[]listOfFiles=aFile.listFiles();
if(listOfFiles!=null){
for(int i=0;i