如何在Android集成中从GoogleDrive获取选定的文件路径?
我已经成功地将GoogleDrive集成到我的Android应用程序中,现在我可以从应用程序上传任何文件到硬盘。但我想将文件从驱动器下载到设备,为此,我使用下面给出的一些代码-如何在Android集成中从GoogleDrive获取选定的文件路径?,android,google-drive-api,Android,Google Drive Api,我已经成功地将GoogleDrive集成到我的Android应用程序中,现在我可以从应用程序上传任何文件到硬盘。但我想将文件从驱动器下载到设备,为此,我使用下面给出的一些代码- import java.net.URI; import android.content.Intent; import android.content.IntentSender; import android.content.IntentSender.SendIntentException; import android.
import java.net.URI;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.OpenFileActivityBuilder;
/**
* An activity to illustrate how to pick a file with the opener intent.
*/
public class PickFileWithOpenerActivity extends BaseDemoActivity {
private static final String TAG = "PickFileWithOpenerActivity";
private static final int REQUEST_CODE_OPENER = 1;
@Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
.setMimeType(
new String[] { "text/plain", "text/html",
"application/pdf", "audio/mp3", "video/mp4",
"text/plain", "application/msword",
"image/jpeg", "image/png", "text/html" })
.build(getGoogleApiClient());
try {
startIntentSenderForResult(intentSender, REQUEST_CODE_OPENER, null,
0, 0, 0);
} catch (SendIntentException e) {
Log.w(TAG, "Unable to send intent", e);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE_OPENER:
if (resultCode == RESULT_OK) {
DriveId driveId = (DriveId) data
.getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
showMessage("Selected file's ID: " + driveId);
Uri uri = data.getData();
try {
Log.d(TAG, "Drive Id=============== "
+ uri);
} catch (Exception e) {
e.printStackTrace();
}
// BaseDemoActivity.EXISTING_FILE_ID = driveId.toString();
}
finish();
break;
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
}
下面是基本活动
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.drive.Drive;
/**
* An abstract activity that handles authorization and connection to the Drive
* services.
*/
public abstract class BaseDemoActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "BaseDriveActivity";
/**
* DriveId of an existing folder to be used as a parent folder in folder
* operations samples.
*/
public static final String EXISTING_FOLDER_ID = "0B2EEtIjPUdX6MERsWlYxN3J6RU0";
/**
* DriveId of an existing file to be used in file operation samples..
*/
public static 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;
/**
* Google API client.
*/
private GoogleApiClient mGoogleApiClient;
/**
* Called when activity gets visible. A connection to Drive services need to
* be initiated as soon as the activity is visible. Registers
* {@code ConnectionCallbacks} and {@code OnConnectionFailedListener} on the
* activities itself.
*/
@Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API).addScope(Drive.SCOPE_FILE)
.addScope(Drive.SCOPE_APPFOLDER)
// required for App Folder sample
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
}
mGoogleApiClient.connect();
}
/**
* Handles resolution callbacks.
*/
@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();
}
}
/**
* Called when activity gets invisible. Connection to Drive service needs to
* be disconnected as soon as an activity is invisible.
*/
@Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
/**
* Called when {@code mGoogleApiClient} is connected.
*/
@Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "GoogleApiClient connected");
}
/**
* Called when {@code mGoogleApiClient} is disconnected.
*/
@Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "GoogleApiClient connection suspended");
}
/**
* Called when {@code mGoogleApiClient} is trying to connect but failed.
* Handle {@code result.getResolution()} if there is a resolution is
* available.
*/
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
/**
* Shows a toast message.
*/
public void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
/**
* Getter for the {@code GoogleApiClient}.
*/
public GoogleApiClient getGoogleApiClient() {
return mGoogleApiClient;
}
}
我想在PickFileWithOpenActivity中获取文件路径当前我正在使用onActivityResult中的DriveId获取所选文件id请有人帮助我,告诉我如何获取文件路径并将文件从驱动器下载到设备。@Santosh当前您使用的驱动器id不会返回所选文件名我正在共享代码下面请使用该类而不是PickFileWithOpenActivity
/**
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.DriveResource.MetadataResult;
import com.google.android.gms.drive.MetadataChangeSet;
import com.google.android.gms.drive.OpenFileActivityBuilder;
/**
* An activity that pins a file to the device. Pinning allows a file's latest
* version to be available locally all the time. Your users should be informed
* about the extra bandwidth and storage requirements of pinning.
*/
public class PinFileActivity extends BaseDemoActivity {
private static final int REQUEST_CODE_OPENER = NEXT_AVAILABLE_REQUEST_CODE;
private static final String TAG = "PinFileActivity";
private DriveId mFileId;
/**
* Starts a file opener intent to pick a file.
*/
@Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
if (mFileId == null) {
IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
.setMimeType(
new String[] { "text/plain", "text/html",
"application/pdf", "audio/mp3",
"video/mp4", "text/plain",
"application/msword", "image/jpeg",
"image/png", "text/html" })
.build(getGoogleApiClient());
try {
startIntentSenderForResult(intentSender, REQUEST_CODE_OPENER,
null, 0, 0, 0);
} catch (SendIntentException e) {
Log.w(TAG, "Unable to send intent", e);
}
} else {
DriveFile file = Drive.DriveApi.getFile(getGoogleApiClient(),
mFileId);
Log.i("File Name is ", "===========>>>>" + file);
file.getMetadata(getGoogleApiClient()).setResultCallback(
metadataCallback);
}
}
/**
* Handles response from the file picker.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE_OPENER:
if (resultCode == RESULT_OK) {
mFileId = (DriveId) data
.getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
} else {
finish();
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
/**
* Handles the metadata response. If file is pinnable and not already
* pinned, makes a request to pin the file.
*/
final ResultCallback<MetadataResult> metadataCallback = new ResultCallback<MetadataResult>() {
@Override
public void onResult(MetadataResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Problem while trying to retrieve the file metadata");
return;
}
if (result.getMetadata().isPinnable()) {
showMessage("File is not pinnable");
Log.i("==========All Info is here", "mIME tYPE=====>>>"
+ result.getMetadata().getMimeType() + "======>"
+ result.getMetadata().getTitle() + "====="
+ result.getMetadata().getAlternateLink() + "======"
+ result.getMetadata().getWebContentLink() + "======>>"
+ result.getMetadata().getQuotaBytesUsed());
return;
}
if (result.getMetadata().isPinned()) {
showMessage("File is already pinned");
return;
}
Log.i("==========All Info is here", "==========>>>");
DriveFile file = Drive.DriveApi.getFile(getGoogleApiClient(),
mFileId);
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setPinned(true).build();
file.updateMetadata(getGoogleApiClient(), changeSet)
.setResultCallback(pinningCallback);
}
};
/**
* Handles the pinning request's response.
*/
final ResultCallback<MetadataResult> pinningCallback = new ResultCallback<MetadataResult>() {
@Override
public void onResult(MetadataResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Problem while trying to pin the file");
return;
}
showMessage("File successfully pinned to the device");
}
};
}
/**
*版权所有2014谷歌公司。保留所有权利。
*
*根据Apache许可证2.0版(以下简称“许可证”)获得许可;您不能使用此文件,除非
*符合许可证的要求。您可以通过以下方式获得许可证副本:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*除非适用法律要求或书面同意,否则根据
*许可证是按“原样”分发的,没有任何形式的保证或条件
*明示的或暗示的。请参阅许可证以了解管理权限和权限的特定语言
*许可证下的限制。
*/
导入android.content.Intent;
导入android.content.IntentSender;
导入android.content.IntentSender.SendIntentException;
导入android.os.Bundle;
导入android.util.Log;
导入com.google.android.gms.common.api.ResultCallback;
导入com.google.android.gms.drive.drive;
导入com.google.android.gms.drive.DriveFile;
导入com.google.android.gms.drive.DriveId;
导入com.google.android.gms.drive.DriveResource.MetadataResult;
导入com.google.android.gms.drive.MetadataChangeSet;
导入com.google.android.gms.drive.OpenFileActivityBuilder;
/**
*将文件固定到设备的活动。固定允许文件的最新版本
*版本始终在本地可用。应该通知您的用户
*关于固定的额外带宽和存储要求。
*/
公共类PinFileActivity扩展了BaseDemoActivity{
私有静态最终整数请求\代码\开启器=下一个可用\请求\代码;
私有静态最终字符串TAG=“PinFileActivity”;
私有DriveId-mFileId;
/**
*启动文件开启器以拾取文件。
*/
@凌驾
未连接的公共无效(捆绑连接提示){
super.onConnected(connectionHint);
if(mFileId==null){
IntentSender IntentSender=Drive.DriveApi
.newOpenFileActivityBuilder()
.setMimeType(
新字符串[]{“text/plain”,“text/html”,
“应用程序/pdf”、“音频/mp3”,
“视频/mp4”、“文本/普通”,
“应用程序/msword”、“图像/jpeg”,
“image/png”、“text/html”})
.build(getGoogleAppClient());
试一试{
startIntentSenderForResult(意向书签署人、请求代码开启人、,
null,0,0,0);
}捕获(发送){
Log.w(标签“无法发送意图”,e);
}
}否则{
DriveFile file=Drive.DriveApi.getFile(getGoogleAppClient(),
mFileId);
Log.i(“文件名为“,”=============>>>>”+文件);
file.getMetadata(getGoogleAppClient()).setResultCallback(
元数据回调);
}
}
/**
*处理来自文件选择器的响应。
*/
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
开关(请求代码){
案例请求\代码\开场白:
if(resultCode==RESULT\u OK){
mFileId=(DriveId)数据
.getParcelableExtra(OpenFileActivityBuilder.EXTRA\u响应\u驱动器\u ID);
}否则{
完成();
}
打破
违约:
super.onActivityResult(请求代码、结果代码、数据);
}
}
/**
*处理元数据响应
*锁定,请求锁定文件。
*/
final ResultCallback metadataCallback=新ResultCallback(){
@凌驾
公共void onResult(MetadataResult){
如果(!result.getStatus().issucess()){
showMessage(“尝试检索文件元数据时出现问题”);
返回;
}
if(result.getMetadata().ispinable()){
showMessage(“文件不可固定”);
Log.i(“================所有信息都在这里”,“mIME类型=====>>>”
+result.getMetadata().getMimeType()+“==========>”
+result.getMetadata().getTitle()+“=======”
+result.getMetadata().getAlternateLink()+“==========”
+结果.getMetadata().getWebContentLink()+“==========>>”
+result.getMetadata().getQuotaBytesUsed());
返回;
}
if(result.getMetadata().isPinned()){
showMessage(“文件已固定”);
返回;
}
Log.i(“================所有信息都在这里”,“================>>>”);
DriveFile file=Drive.DriveApi.getFile(getGoogleAppClient(),
mFileId);
MetadataChangeSet changeSet=新建MetadataChangeSet.Builder()
.setpinted(true).build();
file.updateMetadata(getGoogleAppClient(),变更集)
.setResultCallback(pinningCallback);
}
};
/**
*处理固定请求的响应。
*/
final ResultCallback pinningCallback=新ResultCallback(){
@凌驾
聚氨基甲酸酯