Java 谷歌硬盘Android API如何将音频文件上传到我的硬盘?如何同步驱动器文件?
我已经看过了演示,但我尝试了快速入门示例,其中上载了一个图像。但我不知道如何上传一个音频文件,我会给我的文件路径或意图选择器选择文件 如何将音频文件上载到我的驱动器 我需要将其转换为任何流? 为什么谷歌仅仅为了上传文件就把这件事弄得如此复杂? 如何同步驱动器文件 如何从驱动器流式播放音频文件 下面的代码只是上传文件,里面什么都不包含Java 谷歌硬盘Android API如何将音频文件上传到我的硬盘?如何同步驱动器文件?,java,android,google-drive-api,google-drive-android-api,Java,Android,Google Drive Api,Google Drive Android Api,我已经看过了演示,但我尝试了快速入门示例,其中上载了一个图像。但我不知道如何上传一个音频文件,我会给我的文件路径或意图选择器选择文件 如何将音频文件上载到我的驱动器 我需要将其转换为任何流? 为什么谷歌仅仅为了上传文件就把这件事弄得如此复杂? 如何同步驱动器文件 如何从驱动器流式播放音频文件 下面的代码只是上传文件,里面什么都不包含 }我还没有玩过音频文件,但一般来说,Google Drive Android API GDAA不处理音频文件。您只需创建一个文件,设置元数据并在其中填充二进制内容。
}我还没有玩过音频文件,但一般来说,Google Drive Android API GDAA不处理音频文件。您只需创建一个文件,设置元数据并在其中填充二进制内容。看看这个加上一些。您将找到一个代码行
byte[] buff = ("written on: " + _dfn.getName()).getBytes();
if (null == _gc.creatFile(fldr, name, MIMETEXT, buff)) return;
在那里,它生成byte[]缓冲区并创建一个文本MIME类型的文件。所以,试着使用它,只需替换MIME类型并用音频流填充“buff”。我用JPEG二进制文件成功地做到了这一点
还有一个GooApiClnt包装类处理大多数基本GDAA函数。不过,在工作中不要试图用这种方式编写代码,它可能会让你被炒鱿鱼:-
祝你好运。我还没有玩过音频文件,但一般来说,谷歌驱动Android API GDAA不处理音频文件。您只需创建一个文件,设置元数据并在其中填充二进制内容。看看这个加上一些。您将找到一个代码行
byte[] buff = ("written on: " + _dfn.getName()).getBytes();
if (null == _gc.creatFile(fldr, name, MIMETEXT, buff)) return;
在那里,它生成byte[]缓冲区并创建一个文本MIME类型的文件。所以,试着使用它,只需替换MIME类型并用音频流填充“buff”。我用JPEG二进制文件成功地做到了这一点
还有一个GooApiClnt包装类处理大多数基本GDAA函数。不过,在工作中不要试图用这种方式编写代码,它可能会让你被炒鱿鱼:-
祝你好运。在你的onConnected方法中,你创建了一个新文件,但你从未在其中放入任何新内容。您可以在此行中创建新内容:
result = Drive.DriveApi.newContents(mGoogleApiClient).await();
OutputStream outputStream = result.getContents().getOutputStream();
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
然后在这一行中获得它的输出流:
result = Drive.DriveApi.newContents(mGoogleApiClient).await();
OutputStream outputStream = result.getContents().getOutputStream();
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
然后在此行中创建一个空字节数组输出流:
result = Drive.DriveApi.newContents(mGoogleApiClient).await();
OutputStream outputStream = result.getContents().getOutputStream();
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
但您从未使用任何内容填充此“位图流”,最糟糕的是:您从未将其写入内容的“输出流”
接下来要做的是将音频文件的内容写入“bitmapStream”,如下所示:
InputStream in = file.getInputStream(/*you need to get the file's path and put it here*/ "some_audio_file.mp3");
int singleByte;
while((singleByte = in.read()) != -1){
bitmapStream.write(b);
}
outputStream.write(bitmapStream.toByteArray());
现在,您将文件的内容放在“bitmapStrea”中,您可以将其写入新内容的“outputStream”,如下所示:
InputStream in = file.getInputStream(/*you need to get the file's path and put it here*/ "some_audio_file.mp3");
int singleByte;
while((singleByte = in.read()) != -1){
bitmapStream.write(b);
}
outputStream.write(bitmapStream.toByteArray());
比你做的“MetadataChangeSet”的东西,你应该是好的
一些建议:
1.在您的案例中,在主线程上执行I/O操作(如文件或网络活动或文件和网络活动)不是一个好的做法。最好在后台线程中使用AsyncTask
如果您使用ByteArrayOutputStream实例上载音频文件,请不要将其称为“bitmapStream”。
下面是一个类的示例,该类使用AsyncTask上载图像并猜测我称之为ByteArrayOutputStream的内容。。。右-“位图流”:
public class TakePhotoActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
/**
* Request code for auto Google Play Services error resolution.
*/
protected static final int REQUEST_CODE_RESOLUTION = 1;
private static final String TAG = "TakePhotoActivity";
private static final String KEY_IN_RESOLUTION = "is_in_resolution";
private static final int REQUEST_CODE_CREATOR = 2;
/**
* Google API client.
*/
private GoogleApiClient mGoogleApiClient;
/**
* Receives the new file's contents and executes the editor AsyncTask
*/
private ResultCallback<DriveApi.ContentsResult> mSaveFileCallback = new ResultCallback<DriveApi.ContentsResult>() {
@Override
public void onResult(DriveApi.ContentsResult contentsResult) {
EditFileAsyncTask editFileAsyncTask = new EditFileAsyncTask();
editFileAsyncTask.execute(contentsResult);
}
};
/**
* Determines if the client is in a resolution state, and
* waiting for resolution intent to return.
*/
private boolean mIsInResolution;
private Bitmap mBitmapToSave;
/**
* Called when the activity is starting. Restores the activity state.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_take_menu_photo);
if (savedInstanceState != null) {
mIsInResolution = savedInstanceState.getBoolean(KEY_IN_RESOLUTION, false);
}
try {
InputStream inputStream = getAssets().open("some_image.jpg");
mBitmapToSave = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Called when the Activity is made visible.
* A connection to Play 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 onStart() {
super.onStart();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
// Optionally, add additional APIs and scopes if required.
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
Log.d("test", "connect()");
mGoogleApiClient.connect();
}
/**
* Called when activity gets invisible. Connection to Play Services needs to
* be disconnected as soon as an activity is invisible.
*/
@Override
protected void onStop() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onStop();
}
/**
* Saves the resolution state.
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(KEY_IN_RESOLUTION, mIsInResolution);
}
/**
* Handles Google Play Services resolution callbacks.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_RESOLUTION:
retryConnecting();
break;
}
}
private void retryConnecting() {
mIsInResolution = false;
if (!mGoogleApiClient.isConnecting()) {
Log.d("test", "connect()");
mGoogleApiClient.connect();
}
}
/**
* Called when {@code mGoogleApiClient} is connected.
*/
@Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "GoogleApiClient connected");
// TODO: Start making API requests.
if (mBitmapToSave != null) {
saveFileToDrive();
}
}
/**
* Called when {@code mGoogleApiClient} connection is suspended.
*/
@Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "GoogleApiClient connection suspended");
retryConnecting();
}
/**
* Called when {@code mGoogleApiClient} is trying to connect but failed.
* Handle {@code result.getResolution()} if there is a resolution
* available.
*/
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// Show a localized error dialog.
GooglePlayServicesUtil.getErrorDialog(
result.getErrorCode(), this, 0, new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
retryConnecting();
}
}
).show();
return;
}
// If there is an existing resolution error being displayed or a resolution
// activity has started before, do nothing and wait for resolution
// progress to be completed.
if (mIsInResolution) {
return;
}
mIsInResolution = true;
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
retryConnecting();
}
}
private void saveFileToDrive() {
Log.i(TAG, "Creating new contents.");
Drive.DriveApi.newContents(mGoogleApiClient).setResultCallback(mSaveFileCallback);
}
private void showMessage(String message) {
Log.i(TAG, message);
// Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
private class EditFileAsyncTask extends AsyncTask<DriveApi.ContentsResult, Void, Boolean> {
@Override
protected Boolean doInBackground(DriveApi.ContentsResult... params) {
DriveApi.ContentsResult contentsResult = params[0];
if (!contentsResult.getStatus().isSuccess()) {
showMessage("Failed to create new contents.");
return false;
}
showMessage("New contents created.");
OutputStream outputStream = contentsResult.getContents().getOutputStream();
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
mBitmapToSave.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
try {
outputStream.write(bitmapStream.toByteArray());
} catch (IOException e) {
showMessage("Unable to write file contents.");
e.printStackTrace();
}
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("image/jpeg")
.setTitle("some_image.jpg")
.build();
IntentSender intentSender = Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialContents(contentsResult.getContents())
.build(mGoogleApiClient);
try {
startIntentSenderForResult(intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
} catch (SendIntentException e) {
showMessage("Failed to launch file chooser.");
e.printStackTrace();
}
return true;
}
@Override
protected void onPostExecute(Boolean result) {
if (!result) {
showMessage("Error while editing contents");
return;
}
showMessage("Successfully edited contents");
}
}
}
顺便说一下,这个类中的大部分代码是由Android Studio自动生成的,因为当我创建项目时,我将初始类标记为google服务类。
在onConnected方法中,您创建了新文件,但从未在其中放入任何新内容。您可以在此行中创建新内容:
result = Drive.DriveApi.newContents(mGoogleApiClient).await();
OutputStream outputStream = result.getContents().getOutputStream();
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
然后在这一行中获得它的输出流:
result = Drive.DriveApi.newContents(mGoogleApiClient).await();
OutputStream outputStream = result.getContents().getOutputStream();
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
然后在此行中创建一个空字节数组输出流:
result = Drive.DriveApi.newContents(mGoogleApiClient).await();
OutputStream outputStream = result.getContents().getOutputStream();
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
但您从未使用任何内容填充此“位图流”,最糟糕的是:您从未将其写入内容的“输出流”
接下来要做的是将音频文件的内容写入“bitmapStream”,如下所示:
InputStream in = file.getInputStream(/*you need to get the file's path and put it here*/ "some_audio_file.mp3");
int singleByte;
while((singleByte = in.read()) != -1){
bitmapStream.write(b);
}
outputStream.write(bitmapStream.toByteArray());
现在,您将文件的内容放在“bitmapStrea”中,您可以将其写入新内容的“outputStream”,如下所示:
InputStream in = file.getInputStream(/*you need to get the file's path and put it here*/ "some_audio_file.mp3");
int singleByte;
while((singleByte = in.read()) != -1){
bitmapStream.write(b);
}
outputStream.write(bitmapStream.toByteArray());
比你做的“MetadataChangeSet”的东西,你应该是好的
一些建议:
1.在您的案例中,在主线程上执行I/O操作(如文件或网络活动或文件和网络活动)不是一个好的做法。最好在后台线程中使用AsyncTask
如果您使用ByteArrayOutputStream实例上载音频文件,请不要将其称为“bitmapStream”。
下面是一个类的示例,该类使用AsyncTask上载图像并猜测我称之为ByteArrayOutputStream的内容。。。右-“位图流”:
public class TakePhotoActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
/**
* Request code for auto Google Play Services error resolution.
*/
protected static final int REQUEST_CODE_RESOLUTION = 1;
private static final String TAG = "TakePhotoActivity";
private static final String KEY_IN_RESOLUTION = "is_in_resolution";
private static final int REQUEST_CODE_CREATOR = 2;
/**
* Google API client.
*/
private GoogleApiClient mGoogleApiClient;
/**
* Receives the new file's contents and executes the editor AsyncTask
*/
private ResultCallback<DriveApi.ContentsResult> mSaveFileCallback = new ResultCallback<DriveApi.ContentsResult>() {
@Override
public void onResult(DriveApi.ContentsResult contentsResult) {
EditFileAsyncTask editFileAsyncTask = new EditFileAsyncTask();
editFileAsyncTask.execute(contentsResult);
}
};
/**
* Determines if the client is in a resolution state, and
* waiting for resolution intent to return.
*/
private boolean mIsInResolution;
private Bitmap mBitmapToSave;
/**
* Called when the activity is starting. Restores the activity state.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_take_menu_photo);
if (savedInstanceState != null) {
mIsInResolution = savedInstanceState.getBoolean(KEY_IN_RESOLUTION, false);
}
try {
InputStream inputStream = getAssets().open("some_image.jpg");
mBitmapToSave = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Called when the Activity is made visible.
* A connection to Play 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 onStart() {
super.onStart();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
// Optionally, add additional APIs and scopes if required.
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
Log.d("test", "connect()");
mGoogleApiClient.connect();
}
/**
* Called when activity gets invisible. Connection to Play Services needs to
* be disconnected as soon as an activity is invisible.
*/
@Override
protected void onStop() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onStop();
}
/**
* Saves the resolution state.
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(KEY_IN_RESOLUTION, mIsInResolution);
}
/**
* Handles Google Play Services resolution callbacks.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_RESOLUTION:
retryConnecting();
break;
}
}
private void retryConnecting() {
mIsInResolution = false;
if (!mGoogleApiClient.isConnecting()) {
Log.d("test", "connect()");
mGoogleApiClient.connect();
}
}
/**
* Called when {@code mGoogleApiClient} is connected.
*/
@Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "GoogleApiClient connected");
// TODO: Start making API requests.
if (mBitmapToSave != null) {
saveFileToDrive();
}
}
/**
* Called when {@code mGoogleApiClient} connection is suspended.
*/
@Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "GoogleApiClient connection suspended");
retryConnecting();
}
/**
* Called when {@code mGoogleApiClient} is trying to connect but failed.
* Handle {@code result.getResolution()} if there is a resolution
* available.
*/
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// Show a localized error dialog.
GooglePlayServicesUtil.getErrorDialog(
result.getErrorCode(), this, 0, new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
retryConnecting();
}
}
).show();
return;
}
// If there is an existing resolution error being displayed or a resolution
// activity has started before, do nothing and wait for resolution
// progress to be completed.
if (mIsInResolution) {
return;
}
mIsInResolution = true;
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
retryConnecting();
}
}
private void saveFileToDrive() {
Log.i(TAG, "Creating new contents.");
Drive.DriveApi.newContents(mGoogleApiClient).setResultCallback(mSaveFileCallback);
}
private void showMessage(String message) {
Log.i(TAG, message);
// Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
private class EditFileAsyncTask extends AsyncTask<DriveApi.ContentsResult, Void, Boolean> {
@Override
protected Boolean doInBackground(DriveApi.ContentsResult... params) {
DriveApi.ContentsResult contentsResult = params[0];
if (!contentsResult.getStatus().isSuccess()) {
showMessage("Failed to create new contents.");
return false;
}
showMessage("New contents created.");
OutputStream outputStream = contentsResult.getContents().getOutputStream();
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
mBitmapToSave.compress(Bitmap.CompressFormat.PNG, 100, bitmapStream);
try {
outputStream.write(bitmapStream.toByteArray());
} catch (IOException e) {
showMessage("Unable to write file contents.");
e.printStackTrace();
}
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("image/jpeg")
.setTitle("some_image.jpg")
.build();
IntentSender intentSender = Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialContents(contentsResult.getContents())
.build(mGoogleApiClient);
try {
startIntentSenderForResult(intentSender, REQUEST_CODE_CREATOR, null, 0, 0, 0);
} catch (SendIntentException e) {
showMessage("Failed to launch file chooser.");
e.printStackTrace();
}
return true;
}
@Override
protected void onPostExecute(Boolean result) {
if (!result) {
showMessage("Error while editing contents");
return;
}
showMessage("Successfully edited contents");
}
}
}
顺便说一下,这个类中的大部分代码是由Android Studio自动生成的,因为当我创建项目时,我将初始类标记为google服务类。
试试这个:
**
* An AsyncTask that maintains a connected client.
*/
public abstract class ApiClientAsyncTask<Params, Progress, Result>
extends AsyncTask<Params, Progress, Result> {
private GoogleApiClient mClient;
public ApiClientAsyncTask(Context context) {
GoogleApiClient.Builder builder = new GoogleApiClient.Builder(context)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE);
mClient = builder.build();
}
@Override
protected final Result doInBackground(Params... params) {
Log.d("TAG", "in background");
final CountDownLatch latch = new CountDownLatch(1);
mClient.registerConnectionCallbacks(new ConnectionCallbacks() {
@Override
public void onConnectionSuspended(int cause) {
}
@Override
public void onConnected(Bundle arg0) {
latch.countDown();
}
});
mClient.registerConnectionFailedListener(new OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult arg0) {
latch.countDown();
}
});
mClient.connect();
try {
latch.await();
} catch (InterruptedException e) {
return null;
}
if (!mClient.isConnected()) {
return null;
}
try {
return doInBackgroundConnected(params);
} finally {
mClient.disconnect();
}
}
/**
* Override this method to perform a computation on a background thread, while the client is
* connected.
*/
protected abstract Result doInBackgroundConnected(Params... params);
/**
* Gets the GoogleApliClient owned by this async task.
*/
protected GoogleApiClient getGoogleApiClient() {
return mClient;
}
}
类以保存文件:
试试这个:
**
* An AsyncTask that maintains a connected client.
*/
public abstract class ApiClientAsyncTask<Params, Progress, Result>
extends AsyncTask<Params, Progress, Result> {
private GoogleApiClient mClient;
public ApiClientAsyncTask(Context context) {
GoogleApiClient.Builder builder = new GoogleApiClient.Builder(context)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE);
mClient = builder.build();
}
@Override
protected final Result doInBackground(Params... params) {
Log.d("TAG", "in background");
final CountDownLatch latch = new CountDownLatch(1);
mClient.registerConnectionCallbacks(new ConnectionCallbacks() {
@Override
public void onConnectionSuspended(int cause) {
}
@Override
public void onConnected(Bundle arg0) {
latch.countDown();
}
});
mClient.registerConnectionFailedListener(new OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult arg0) {
latch.countDown();
}
});
mClient.connect();
try {
latch.await();
} catch (InterruptedException e) {
return null;
}
if (!mClient.isConnected()) {
return null;
}
try {
return doInBackgroundConnected(params);
} finally {
mClient.disconnect();
}
}
/**
* Override this method to perform a computation on a background thread, while the client is
* connected.
*/
protected abstract Result doInBackgroundConnected(Params... params);
/**
* Gets the GoogleApliClient owned by this async task.
*/
protected GoogleApiClient getGoogleApiClient() {
return mClient;
}
}
类以保存文件:
这很简单。经过我的努力,我找到了解决办法
private String mFileName = null;
File folder = new File(Environment.getExternalStorageDirectory() +
"/FolderFile");
if (!folder.exists()) {
folder.mkdir();
}
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/FolderFile/a.mp3";
录音后。你必须
这很简单。经过我的努力,我找到了解决办法
private String mFileName = null;
File folder = new File(Environment.getExternalStorageDirectory() +
"/FolderFile");
if (!folder.exists()) {
folder.mkdir();
}
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/FolderFile/a.mp3";
录音后。你必须
你的两个链接都不工作。你能更新吗?你的两个链接都不工作。你能更新吗?