获取Google Drive API Android的资源Id
我正在使用驱动器api在google drive上的隐藏应用程序文件夹中创建一个文件。我想获取该文件的资源id,但它一直返回null。这是代码。创建文件后,它应该在回调中获取文件资源id,但返回null。它可以得到正常的驱动器,但这一点都没有帮助,因为获取驱动器id需要资源id。关于如何获取资源id,我已经检查了多个不同的链接,所有这些都没有帮助获取Google Drive API Android的资源Id,android,google-drive-android-api,Android,Google Drive Android Api,我正在使用驱动器api在google drive上的隐藏应用程序文件夹中创建一个文件。我想获取该文件的资源id,但它一直返回null。这是代码。创建文件后,它应该在回调中获取文件资源id,但返回null。它可以得到正常的驱动器,但这一点都没有帮助,因为获取驱动器id需要资源id。关于如何获取资源id,我已经检查了多个不同的链接,所有这些都没有帮助 //<editor-fold desc="Variables"> // Define Variable Int MY_PERMISSIO
//<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>
}
//
//定义变量Int MY\u PERMISSIONS\u WRITE\u EXTERNAL\u STORAGE//
公共静态int MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE=0;
//定义变量int解析\连接\请求\代码//
公共静态最终整数解析\连接\请求\代码=3;
//定义变量GoogleApiClient GoogleApiClient//
公共GoogleapClient GoogleapClient;
//定义变量字符串标题//
String title=“Notes.db”;
//定义变量字符串mime//
字符串mime=“application/x-sqlite3”;
//定义变量字符串currentDBPath//
字符串dBPath=“/School Binder/Note Backups/Notes.db”;
//定义可变文件数据//
File data=Environment.getExternalStorageDirectory();
//定义变量文件dbFile//
File dbFile=新文件(数据,dBPath);
//为数据库文件创建元数据//
MetadataChangeSet meta=new MetadataChangeSet.Builder().setTitle(title).setMimeType(mime.build();
字符串现有\u文件\u ID=“CAESABjaBSCMicnCsFQoAA”;
//
//方法,该方法在活动启动时运行//
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//启动allowWriteExternalStorage方法//
allowWriteExternalStorage();
//启动connecttologledrive方法//
连接到ogledrive();
}
//方法,该方法在应用程序恢复时运行//
受保护的void onResume(){
super.onResume();
//检查Api客户端是否为空//
if(googleApiClient==null){
//创建Api客户端//
GoogleapClient=新的GoogleapClient.Builder(此)
.addApi(Drive.API)
.addScope(驱动器.SCOPE\u文件)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.build();
}
//尝试连接到Google drive//
googleApiClient.connect();
}
//方法,该方法在应用程序暂停时运行//
@凌驾
受保护的void onPause(){
//检查是否使用了Api//
if(googleApiClient!=null){
//断开与谷歌硬盘的连接//
googleApiClient.disconnect();
}
super.onPause();
}
//当应用程序成功连接到用户Google Drive时运行的方法//
@凌驾
未连接的公共无效(@Nullable Bundle){
//将新文件添加到驱动器//
Drive.DriveApi.newDriveContents(GoogleAppClient.setResultCallback(contentsCallback);
}
//方法,该方法在连接挂起时运行//
@凌驾
公共空间连接暂停(int i){
}
//当应用程序无法连接到Google Drive时运行的方法//
@凌驾
public void onconnection失败(@NonNull ConnectionResult ConnectionResult){
//检查是否可以解决连接故障//
if(connectionResult.hasResolution()){
//如果上述语句为真,请尝试修复连接//
试一试{
//解析连接//
connectionResult.startResolutionForResult(这是解析连接请求代码);
}捕获(忽略IntentSender.SendIntentException){
}
}否则{
//显示连接错误//
GoogleAppAvailability.getInstance().getErrorDialog(此,connectionResult.getErrorCode(),0.show();
}
}
//方法,该方法授予应用程序访问系统存储的权限//
public void allowWriteExternalStorage(){
//允许或取消允许对存储器的写入//
如果(ContextCompat.checkSelfPermission)(此,
清单.权限.写入(外部存储)
!=PackageManager.权限(已授予){
//请求写入外部存储器//
ActivityCompat.requestPermissions(MainActivity.this,
新字符串[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
我的权限(写入、外部存储);
}
}
//连接到Google Drive的方法//
public void connecttogologledrive(){
//创建Api客户端//
GoogleapClient=新的GoogleapClient.Builder(此)
.addApi(Drive.API)
.addScope(驱动器.SCOPE\u文件)
.addScope(Drive.SCOPE\u APPFOLDER)
.addConnectionCallbacks(此)
.addOnConnectionFailedListener(此)
.build();
//尝试连接到Google drive//
googleApiClient.connect();
}
//
//当应用程序尝试创建新文件或文件夹时会发生什么情况//
final private ResultCallback contentsCallback=new ResultCallback(){
@凌驾
public void onResult(@NonNull DriveApi.DriveContentsResult result){
//创建文件失败时运行//
如果(!result.getStatus().issucess()){
//无法创建该文件的日志//
d(“Log”,“尝试创建新文件内容时出错”);
返回;
}
//检查创建文件是否成功//
DriveContents cont=result.getStatus().isSuccess()?result.getDriveContents():null;
//写入文件//
如果(cont!=null),请尝试{
OutputStream oos=cont.getOutputStream();
如果(oos!=null),请尝试{
InputStream is=新文件InputStream(dbFile);
字节[]buf=新字节[5000];
INTC;
而((c=is.read(buf,0,buf.length))>0){
oos.write(buf,0,c);
oos.flush();
}
}最后{
oos.close();
}
}捕获(例外e){
e、 printStackTrace();
}
//将文件放入用户隐藏的应用程序文件夹//
Drive.DriveApi.getAppFolder(GoogleAppClient).createFile(GoogleAppLi
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();
}
}
<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>