本文介绍了在Android集成中如何从GoogleDrive中获取选定的文件路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已将GoogleDrive成功集成到Android应用程序中,现在我可以上传任何文件以从应用程序中驱动。但我想下载文件从驱动器到设备为此我使用下面给出的一些代码 -
import java.net.URI ;
导入android.content.Intent;
导入android.content.IntentSender;
导入android.content.IntentSender.SendIntentException;
导入android.net.Uri;
导入android.os.Bundle;
导入android.util.Log;
导入com.google.android.gms.drive.Drive;
导入com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.OpenFileActivityBuilder;
/ **
*一个活动来说明如何使用opener意图选择一个文件。
* /
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);
}
$ b @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(所选文件的ID:+ driveId);
Uri uri = data.getData();
尝试{
Log.d(TAG,Drive Id ===============
+ uri);
} catch(Exception e){
e.printStackTrace();
}
// BaseDemoActivity.EXISTING_FILE_ID = driveId.toString();
}
finish();
休息;
默认值:
super.onActivityResult(requestCode,resultCode,data);
code
$ b 这里是BaseDemoActivity
import android.app.Activity;
导入android.content.Intent;
导入android.content.IntentSender.SendIntentException;
导入android.os.Bundle;
导入android.util.Log;
导入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;
导入com.google.android.gms.drive.Drive;
/ **
*处理对Drive
*服务的授权和连接的抽象活动。
* /
public abstract class BaseDemoActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
$ b private static final String TAG =BaseDriveActivity ;
/ **
*现有文件夹的DriveId将用作文件夹
*操作示例中的父文件夹。
* /
public static final String EXISTING_FOLDER_ID =0B2EEtIjPUdX6MERsWlYxN3J6RU0;
/ **
*在文件操作示例中使用的现有文件的DriveId ..
* /
public static String EXISTING_FILE_ID =0ByfSjdPVs9MZTHBmMVdSeWxaNTg;
/ **
*帐户名额外。
* /
保护static final String EXTRA_ACCOUNT_NAME =account_name;
/ **
*申请自动Google Play服务错误解决的代码。
* /
protected static final int REQUEST_CODE_RESOLUTION = 1;
/ **
*下一个可用的请求代码。
* /
保护static final int NEXT_AVAILABLE_REQUEST_CODE = 2;
/ **
* Google API客户端。
* /
私有GoogleApiClient mGoogleApiClient;
/ **
*当活动可见时调用。一旦活动可见,就会立即启动与云端硬盘服务的连接
*。在
*活动本身上注册
* {@Code ConnectionCallbacks}和{@Code OnConnectionFailedListener}。
* /
@Override
保护无效onResume(){
super.onResume();
if(mGoogleApiClient == null){
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API).addScope(Drive.SCOPE_FILE)
.addScope( Drive.SCOPE_APPFOLDER)
// App文件夹示例
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
}
mGoogleApiClient.connect();
}
/ **
*处理解析回调。
* /
@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();
}
}
/ **
*当活动不可见时调用。只要活动不可见,与云端硬盘服务的连接需要断开
*。
* /
@Override
protected void onPause(){
if(mGoogleApiClient!= null){
mGoogleApiClient.disconnect();
}
super.onPause();
}
/ **
*在连接{@code mGoogleApiClient}时调用。
* /
@Override
public void onConnected(Bundle connectionHint){
Log.i(TAG,GoogleApiClient connected);
}
/ **
*当{@ code mGoogleApiClient}断开连接时调用。
* /
@Override
public void onConnectionSuspended(int cause){
Log.i(TAG,GoogleApiClient connection suspended);
}
/ **
*当{@code mGoogleApiClient}尝试连接但失败时调用。
*处理result.getResolution()}如果有分辨率是
*可用。
* /
@Override
public void onConnectionFailed(ConnectionResult result){
Log.i(TAG,GoogleApiClient connection failed:+ result.toString());
if(!result.hasResolution()){
//显示本地化错误对话框。
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(),this,
0).show();
return;
}
尝试{
result.startResolutionForResult(this,REQUEST_CODE_RESOLUTION);
} catch(SendIntentException e){
Log.e(TAG,开始解析活动时的异常,e);
}
}
/ **
*显示吐司消息。
* /
public void showMessage(String message){
Toast.makeText(this,message,Toast.LENGTH_LONG).show();
}
/ **
* GoogleApiClient的Getter。
* /
public GoogleApiClient getGoogleApiClient(){
return mGoogleApiClient;
我想在PickFileWithOpenerActivity中获取文件路径,在onActivityResult中使用DriveId获取选定的文件ID请别人帮助我,告诉我如何获取文件路径并将文件从Drive下载到设备。
@ Santosh目前您使用的驱动器ID不会被退回选定的文件名我在下面分享我的代码请使用此类代替PickFileWithOpenerActivity
/ **
*版权所有2014 Google Inc.保留所有权利。
*
*根据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;
import 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;
import com.google.android.gms.drive.DriveResource.MetadataResult;
import com.google.android.gms.drive.MetadataChangeSet;
import com.google.android.gms.drive.OpenFileActivityBuilder;
/ **
*将文件固定到设备的活动。固定允许文件的最新
*版本始终在本地可用。您的用户应该被告知
*关于固定的额外带宽和存储要求。
* /
public class PinFileActivity extends BaseDemoActivity {
private static final int REQUEST_CODE_OPENER = NEXT_AVAILABLE_REQUEST_CODE;
private static final String TAG =PinFileActivity;
私人DriveId mFileId;
/ **
*启动一个文件启动器,用于选择一个文件。
* /
@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,$ b $ 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);
}
}
/ **
*处理文件选取器的响应。
* /
@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;
默认值:
super.onActivityResult(requestCode,resultCode,data);
}
}
/ **
*处理元数据响应。如果文件是可pinnable的,并且已经不是
*固定的,则发出请求来固定文件。
* /
final ResultCallback< MetadataResult> metadataCallback = new ResultCallback< MetadataResult>(){
@Override $ b $ public void onResult(MetadataResult result){
if(!result.getStatus()。isSuccess()){
showMessage(尝试检索文件元数据时出现问题);
return;
if(result.getMetadata()。isPinnable()){
showMessage(File is not pinnable);
Log.i(==========所有信息都在这里,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(==========所有信息都在这里,==========>>> ;);
DriveFile文件= Drive.DriveApi.getFile(getGoogleApiClient(),
mFileId);
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setPinned(true).build();
file.updateMetadata(getGoogleApiClient(),changeSet)
.setResultCallback(pinningCallback);
}
};
/ **
*处理锁定请求的响应。
* /
final ResultCallback< MetadataResult> pinningCallback = new ResultCallback< MetadataResult>(){
@Override $ b $ public void onResult(MetadataResult result){
if(!result.getStatus()。isSuccess()){
showMessage(试图固定文件时出现问题);
return;
}
showMessage(成功锁定到设备上的文件);
}
};
}
我已经放了一些登录结果回调,它显示选定的文件和路径
谢谢
I have successfully integrated GoogleDrive in my Android application and now i can upload any file to drive from app. But i want to download file from drive to device for this i am using some code given below -
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);
}
}
}
Here is BaseDemoActivity
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;
}
}
I want to get file path in PickFileWithOpenerActivity currently i am getting selected file id using DriveId in onActivityResult Please someone help me and tell me how i can fetch file path and download file from Drive to Device.
解决方案
@ Santosh Currently you are using Drive ID which will not be return Selected file name i am sharing my code below please use this class instead of PickFileWithOpenerActivity
/**
* 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");
}
};
}
I have put some Log in result call back which is display selected file and path
Thanks
这篇关于在Android集成中如何从GoogleDrive中获取选定的文件路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!