驱动 API 每次连接,仍然没有互联网
Drive API everytime connected, still without internet
我想将我在我的应用程序中使用驱动器 api 创建的数据库上传到用户驱动器。我现在写了一些代码并在互联网上搜索我如何上传数据库。当我现在测试它时,它总是说 GoogleApi 已连接并正在上传数据库,但当我没有连接到互联网时,我想知道如何。
这是我的代码:
public class Activity_Main extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static GoogleApiClient api;
private static final String DATABASE_NAME = utilsDB.DATABASE_NAME;
private static final String GOOGLE_DRIVE_FILE_NAME = db_backup;
private boolean mResolvingError = false;
private DriveFile mfile;
private static final int DIALOG_ERROR_CODE =100;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
api = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
...
}
@Override
public void onConnectionFailed(ConnectionResult result) {
mToast(Connection failed...);
if(mResolvingError) {
return;
} else if(result.hasResolution()) {
mResolvingError = true;
try {
result.startResolutionForResult(this, DIALOG_ERROR_CODE);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
ErrorDialogFragment fragment = new ErrorDialogFragment();
Bundle args = new Bundle();
args.putInt(error, result.getErrorCode());
fragment.setArguments(args);
fragment.show(getFragmentManager(), errordialog);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
mToast(onActivityResult);
if(requestCode == DIALOG_ERROR_CODE) {
mResolvingError = false;
if(resultCode == RESULT_OK) {
if(!api.isConnecting() && !api.isConnected()) {
api.connect();
}
}
}
}
@Override
public void onConnected(Bundle connectionHint) {
mToast(Connected successfully);
Drive.DriveApi.newDriveContents(api).setResultCallback(contentsCallback);
}
final private ResultCallbackDriveApi.DriveContentsResult contentsCallback = new ResultCallbackDriveApi.DriveContentsResult() {
@Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
debug(Error while trying to create new file contents);
return;
}
String mimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType(db);
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(GOOGLE_DRIVE_FILE_NAME) Google Drive File name
.setMimeType(mimeType)
.setStarred(true).build();
create a file on root folder
Drive.DriveApi.getRootFolder(api)
.createFile(api, changeSet, result.getDriveContents())
.setResultCallback(fileCallback);
}
};
final private ResultCallbackDriveFolder.DriveFileResult fileCallback = new ResultCallbackDriveFolder.DriveFileResult() {
@Override
public void onResult(DriveFolder.DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
mToast(Error while trying to create the file);
return;
}
mfile = result.getDriveFile();
mfile.open(api, DriveFile.MODE_WRITE_ONLY, null).setResultCallback(contentsOpenedCallback);
}
};
final private ResultCallbackDriveApi.DriveContentsResult contentsOpenedCallback = new ResultCallbackDriveApi.DriveContentsResult() {
@Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
mToast(Error opening file);
return;
}
try {
mToast(Uploading db...);
FileInputStream is = new FileInputStream(getDbPath());
BufferedInputStream in = new BufferedInputStream(is);
byte[] buffer = new byte[8 1024];
DriveContents content = result.getDriveContents();
BufferedOutputStream out = new BufferedOutputStream(content.getOutputStream());
int n = 0;
while( ( n = in.read(buffer) ) 0 ) {
out.write(buffer, 0, n);
}
in.close();
mToast(Upload successfull!);
api.disconnect();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
private File getDbPath() {
return getDatabasePath(DATABASE_NAME);
}
@Override
public void onConnectionSuspended(int cause) {
debug(Connection suspended);
}
public void onDialogDismissed() {
mResolvingError = false;
}
public static class ErrorDialogFragment extends DialogFragment {
public ErrorDialogFragment() {}
public Dialog onCreateDialog(Bundle savedInstanceState) {
int errorCode = this.getArguments().getInt(error);
return GooglePlayServicesUtil.getErrorDialog(errorCode, this.getActivity(), DIALOG_ERROR_CODE);
}
public void onDismiss(DialogInterface dialog) {
dialog.dismiss();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sync
mToast(Connecting to Drive API ...);
api.connect();
return true;
}
}
已连接意味着您已连接到 GDAA service in GooPlaySvcs, not to the internet. Please read carefully GDAA 文档(请参阅那里的架构),您会发现重点是,GDAA 试图保护您的应用程序免受在线/离线网络的影响状态(尽可能多)。
只要有网络连接,您的本地状态就会同步。另外,即使你的wifi连上了,也不代表你的GDAA请求会立即得到满足,GDAA会根据它的内部逻辑优化网络流量。
您可以轻松地放弃这些优势并通过切换到 REST Api 获得完全控制权,但您将必须自己处理 on/off-line 状态、请求结果...。并且可能无论如何都会结束使用同步适配器。凌乱。
祝你好运
试试 ConnectionResult resultApi = getGoogleApiClient().blockingConnect();
这将等到 GoogleApi Connected,所以它将在 AsyncTask
.
此外,您可以使用await()
方法代替setResultCallback()
,请看例子:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == DIALOG_ERROR_CODE && resultCode == RESULT_OK) {
final DriveId folderId = (DriveId) data.getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
int intReturnType = 0;
@Override
protected void onPostExecute(Void result) {
//Do Logic...
}
@Override
protected Void doInBackground(Void... params) {
ConnectionResult resultApi = getGoogleApiClient().blockingConnect();
if (!resultApi.isSuccess()) {
return null;
}
DriveFolder folder = Drive.DriveApi.getFolder(getGoogleApiClient(), folderId);
DriveResource.MetadataResult result = folder.getMetadata(getGoogleApiClient()).await();
if (!result.getStatus().isSuccess()) {
Log.d("Folder", "Problem while trying to fetch metadata.");
return null;
}
Log.d("FolderName", metadata.getTitle());
return null;
}
};
task.execute();
}
}
我想将我在我的应用程序中使用驱动器 api 创建的数据库上传到用户驱动器。我现在写了一些代码并在互联网上搜索我如何上传数据库。当我现在测试它时,它总是说 GoogleApi 已连接并正在上传数据库,但当我没有连接到互联网时,我想知道如何。
这是我的代码:
public class Activity_Main extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static GoogleApiClient api;
private static final String DATABASE_NAME = utilsDB.DATABASE_NAME;
private static final String GOOGLE_DRIVE_FILE_NAME = db_backup;
private boolean mResolvingError = false;
private DriveFile mfile;
private static final int DIALOG_ERROR_CODE =100;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
api = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
...
}
@Override
public void onConnectionFailed(ConnectionResult result) {
mToast(Connection failed...);
if(mResolvingError) {
return;
} else if(result.hasResolution()) {
mResolvingError = true;
try {
result.startResolutionForResult(this, DIALOG_ERROR_CODE);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
ErrorDialogFragment fragment = new ErrorDialogFragment();
Bundle args = new Bundle();
args.putInt(error, result.getErrorCode());
fragment.setArguments(args);
fragment.show(getFragmentManager(), errordialog);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
mToast(onActivityResult);
if(requestCode == DIALOG_ERROR_CODE) {
mResolvingError = false;
if(resultCode == RESULT_OK) {
if(!api.isConnecting() && !api.isConnected()) {
api.connect();
}
}
}
}
@Override
public void onConnected(Bundle connectionHint) {
mToast(Connected successfully);
Drive.DriveApi.newDriveContents(api).setResultCallback(contentsCallback);
}
final private ResultCallbackDriveApi.DriveContentsResult contentsCallback = new ResultCallbackDriveApi.DriveContentsResult() {
@Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
debug(Error while trying to create new file contents);
return;
}
String mimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType(db);
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(GOOGLE_DRIVE_FILE_NAME) Google Drive File name
.setMimeType(mimeType)
.setStarred(true).build();
create a file on root folder
Drive.DriveApi.getRootFolder(api)
.createFile(api, changeSet, result.getDriveContents())
.setResultCallback(fileCallback);
}
};
final private ResultCallbackDriveFolder.DriveFileResult fileCallback = new ResultCallbackDriveFolder.DriveFileResult() {
@Override
public void onResult(DriveFolder.DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
mToast(Error while trying to create the file);
return;
}
mfile = result.getDriveFile();
mfile.open(api, DriveFile.MODE_WRITE_ONLY, null).setResultCallback(contentsOpenedCallback);
}
};
final private ResultCallbackDriveApi.DriveContentsResult contentsOpenedCallback = new ResultCallbackDriveApi.DriveContentsResult() {
@Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
mToast(Error opening file);
return;
}
try {
mToast(Uploading db...);
FileInputStream is = new FileInputStream(getDbPath());
BufferedInputStream in = new BufferedInputStream(is);
byte[] buffer = new byte[8 1024];
DriveContents content = result.getDriveContents();
BufferedOutputStream out = new BufferedOutputStream(content.getOutputStream());
int n = 0;
while( ( n = in.read(buffer) ) 0 ) {
out.write(buffer, 0, n);
}
in.close();
mToast(Upload successfull!);
api.disconnect();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
private File getDbPath() {
return getDatabasePath(DATABASE_NAME);
}
@Override
public void onConnectionSuspended(int cause) {
debug(Connection suspended);
}
public void onDialogDismissed() {
mResolvingError = false;
}
public static class ErrorDialogFragment extends DialogFragment {
public ErrorDialogFragment() {}
public Dialog onCreateDialog(Bundle savedInstanceState) {
int errorCode = this.getArguments().getInt(error);
return GooglePlayServicesUtil.getErrorDialog(errorCode, this.getActivity(), DIALOG_ERROR_CODE);
}
public void onDismiss(DialogInterface dialog) {
dialog.dismiss();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sync
mToast(Connecting to Drive API ...);
api.connect();
return true;
}
}
已连接意味着您已连接到 GDAA service in GooPlaySvcs, not to the internet. Please read carefully GDAA 文档(请参阅那里的架构),您会发现重点是,GDAA 试图保护您的应用程序免受在线/离线网络的影响状态(尽可能多)。
只要有网络连接,您的本地状态就会同步。另外,即使你的wifi连上了,也不代表你的GDAA请求会立即得到满足,GDAA会根据它的内部逻辑优化网络流量。
您可以轻松地放弃这些优势并通过切换到 REST Api 获得完全控制权,但您将必须自己处理 on/off-line 状态、请求结果...。并且可能无论如何都会结束使用同步适配器。凌乱。
祝你好运
试试 ConnectionResult resultApi = getGoogleApiClient().blockingConnect();
这将等到 GoogleApi Connected,所以它将在 AsyncTask
.
此外,您可以使用await()
方法代替setResultCallback()
,请看例子:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == DIALOG_ERROR_CODE && resultCode == RESULT_OK) {
final DriveId folderId = (DriveId) data.getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
int intReturnType = 0;
@Override
protected void onPostExecute(Void result) {
//Do Logic...
}
@Override
protected Void doInBackground(Void... params) {
ConnectionResult resultApi = getGoogleApiClient().blockingConnect();
if (!resultApi.isSuccess()) {
return null;
}
DriveFolder folder = Drive.DriveApi.getFolder(getGoogleApiClient(), folderId);
DriveResource.MetadataResult result = folder.getMetadata(getGoogleApiClient()).await();
if (!result.getStatus().isSuccess()) {
Log.d("Folder", "Problem while trying to fetch metadata.");
return null;
}
Log.d("FolderName", metadata.getTitle());
return null;
}
};
task.execute();
}
}