-
Notifications
You must be signed in to change notification settings - Fork 6.1k
/
Copy pathGoogleDriveApiClient.java
108 lines (79 loc) · 2.97 KB
/
GoogleDriveApiClient.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
public class GoogleDriveApiClient extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener,GoogleApiClient.ConnectionCallbacks{
public GoogleApiClient mGoogleApiClient;
public static final int REQUEST_DRIVE_SIGNIN = 123;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//create a api client to connect to drive
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addScope(Drive.SCOPE_APPFOLDER)
.addOnConnectionFailedListener(this)
.build();
//call to connect
mGoogleApiClient.connect();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
//implement the code after connecting
}
@Override
public void onConnectionSuspended(int i) {
if(mGoogleApiClient!=null){
mGoogleApiClient.disconnect();
}
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult result) {
if (!result.hasResolution()) {
GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
return;
}
try {
//call for connection again
result.startResolutionForResult(this, REQUEST_DRIVE_SIGNIN);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_DRIVE_SIGNIN:
if (resultCode == Activity.RESULT_OK) {
mGoogleApiClient.connect();
}
else if (resultCode == RESULT_CANCELED){
Log.d("TAG","result cancelled");
return ;
}
break;
}
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if ((mGoogleApiClient != null)&& (mGoogleApiClient.isConnected())){
mGoogleApiClient.clearDefaultAccountAndReconnect();
mGoogleApiClient.disconnect();
}
}
}