我在嘗試讓Google Calendar Api與我一起工作時遇到了很多麻煩。我搜查了很多,並嘗試了許多似乎失敗的解決方案。Google Calendar Api Android:403錯誤
我的嘗試: - 啓用聯繫人API - Google+的API - 谷歌日曆API - 在調試/釋放模式 運行App - 重塑SHA1碼無數次 - 更改應用程序名稱
這裏是我的MainActivity,它與快速入門中的類似,但我稍微改變了一下,創建了一個事件。
package com.example.roudy.calendarplayground;
public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks{
private GoogleAccountCredential mCredential;
private static final int REQUEST_ACCOUNT_PICKER = 1000;
private static final int REQUEST_AUTHORIZATION = 1001;
private static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002;
private static final int REQUEST_PERMISSION_GET_ACCOUNTS = 1003;
private static final String PREF_ACCOUNT_NAME = "accountName";
private static final String[] SCOPES = { CalendarScopes.CALENDAR };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCredential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
getResultsFromApi();
}
@Override
public void onPermissionsGranted(int requestCode, List<String> perms) {
}
@Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
}
private void getResultsFromApi() {
if (!isGooglePlayServicesAvailable()) {
acquireGooglePlayServices();
} else if (mCredential.getSelectedAccountName() == null) {
chooseAccount();
} else if (!isDeviceOnline()) {
Toast.makeText(this, "No network connection available.", Toast.LENGTH_SHORT).show();
} else if (!EasyPermissions.hasPermissions(this, Manifest.permission.WRITE_CALENDAR)){
EasyPermissions.requestPermissions(
this,
"This app needs to write to your calendar.",
REQUEST_PERMISSION_GET_ACCOUNTS,
Manifest.permission.WRITE_CALENDAR);
} else if(!EasyPermissions.hasPermissions(this, Manifest.permission.READ_CALENDAR)){
EasyPermissions.requestPermissions(
this,
"This app needs to read from your calendar.",
REQUEST_PERMISSION_GET_ACCOUNTS,
Manifest.permission.READ_CALENDAR);
} else {
new createEvent(mCredential).execute();
}
}
private class createEvent extends AsyncTask<Void, Void, Void>{
private com.google.api.services.calendar.Calendar service = null;
private Exception mLastError;
public createEvent (GoogleAccountCredential credential) {
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
service = new com.google.api.services.calendar.Calendar.Builder(
transport, jsonFactory, credential)
.setApplicationName("CalendarPlayground")
.build();
}
@Override
protected Void doInBackground(Void... voids) {
Event event = new Event()
.setSummary("Tutor Meetting!")
.setLocation("beirut, Lebanon")
.setDescription("Some weird description!");
DateTime startDateTime = new DateTime("2016-08-08T17:00:00");
EventDateTime start = new EventDateTime()
.setDateTime(startDateTime)
.setTimeZone("GMT+3");
event.setStart(start);
DateTime endDateTime = new DateTime("2016-08-08T18:00:00");
EventDateTime end = new EventDateTime()
.setDateTime(endDateTime)
.setTimeZone("GMT+3");
event.setEnd(end);
EventReminder[] reminderOverrides = new EventReminder[] {
new EventReminder().setMethod("email").setMinutes(24 * 60),
new EventReminder().setMethod("popup").setMinutes(10),
};
Event.Reminders reminders = new Event.Reminders()
.setUseDefault(false)
.setOverrides(Arrays.asList(reminderOverrides));
event.setReminders(reminders);
String calendarId = "primary";
try {
service.events().insert(calendarId, event).execute();
} catch (Exception e) {
mLastError = e;
e.printStackTrace();
cancel(true);
}
return null;
}
@Override
protected void onCancelled() {
Toast.makeText(MainActivity.this, "Task canceled", Toast.LENGTH_SHORT).show();
if (mLastError != null) {
if (mLastError instanceof GooglePlayServicesAvailabilityIOException) { // not entered
showGooglePlayServicesAvailabilityErrorDialog(
((GooglePlayServicesAvailabilityIOException) mLastError)
.getConnectionStatusCode());
} else if (mLastError instanceof UserRecoverableAuthIOException) { // not entered
startActivityForResult(
((UserRecoverableAuthIOException) mLastError).getIntent(),
MainActivity.REQUEST_AUTHORIZATION);
} else {
}
} else {
}
}
@Override
protected void onPostExecute(Void aVoid) {
Toast.makeText(MainActivity.this, "Event created !", Toast.LENGTH_SHORT).show();
super.onPostExecute(aVoid);
}
}
@AfterPermissionGranted(REQUEST_PERMISSION_GET_ACCOUNTS)
private void chooseAccount() {
if (EasyPermissions.hasPermissions(
this, Manifest.permission.GET_ACCOUNTS)) {
String accountName = getPreferences(Context.MODE_PRIVATE)
.getString(PREF_ACCOUNT_NAME, null);
if (accountName != null) {
mCredential.setSelectedAccountName(accountName);
getResultsFromApi();
} else {
startActivityForResult(
mCredential.newChooseAccountIntent(),
REQUEST_ACCOUNT_PICKER);
}
} else {
EasyPermissions.requestPermissions(
this,
"This app needs to access your Google account (via Contacts).",
REQUEST_PERMISSION_GET_ACCOUNTS,
Manifest.permission.GET_ACCOUNTS);
}
}
@Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case REQUEST_GOOGLE_PLAY_SERVICES:
if (resultCode != RESULT_OK) {
Toast.makeText(this, "This app requires Google Play Services. Please install " +
"Google Play Services on your device and relaunch this app.", Toast.LENGTH_SHORT).show();
} else {
getResultsFromApi();
}
break;
case REQUEST_ACCOUNT_PICKER:
if (resultCode == RESULT_OK && data != null &&
data.getExtras() != null) {
String accountName =
data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
SharedPreferences settings =
getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREF_ACCOUNT_NAME, accountName);
editor.apply();
mCredential.setSelectedAccountName(accountName);
getResultsFromApi();
}
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == RESULT_OK) {
getResultsFromApi();
}
break;
}
}
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(
requestCode, permissions, grantResults, this);
}
private boolean isDeviceOnline() {
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability apiAvailability =
GoogleApiAvailability.getInstance();
final int connectionStatusCode =
apiAvailability.isGooglePlayServicesAvailable(this);
return connectionStatusCode == ConnectionResult.SUCCESS;
}
private void acquireGooglePlayServices() {
GoogleApiAvailability apiAvailability =
GoogleApiAvailability.getInstance();
final int connectionStatusCode =
apiAvailability.isGooglePlayServicesAvailable(this);
if (apiAvailability.isUserResolvableError(connectionStatusCode)) {
showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
}
}
private void showGooglePlayServicesAvailabilityErrorDialog(
final int connectionStatusCode) {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
Dialog dialog = apiAvailability.getErrorDialog(
MainActivity.this,
connectionStatusCode,
REQUEST_GOOGLE_PLAY_SERVICES);
dialog.show();
}
}
以下是我收到的錯誤。在問這個問題之前,我已經確定一切都是應該的,我在任何地方搜索了答案,而且似乎沒有任何工作。 「取消(真)」當然是觸發的,但沒有任何條件輸入,順便說一句。 (見代碼)
W/System.err: {
W/System.err: "code" : 403,
W/System.err: "errors" : [ {
W/System.err: "domain" : "usageLimits",
W/System.err: "message" : "Access Not Configured. Calendar API has not been used in project 608941808256 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/calendar/overview?project=608941808256 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.",
W/System.err: "reason" : "accessNotConfigured",
W/System.err: "extendedHelp" : "https://console.developers.google.com/apis/api/calendar/overview?project=608941808256"
W/System.err: } ],
W/System.err: "message" : "Access Not Configured. Calendar API has not been used in project 608941808256 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/calendar/overview?project=608941808256 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry."
W/System.err: }
I have tried recreating the SHA1 many, many times
Package name copy pasted and everything looks the same
您是否在Google API控制檯中啓用了Calendar API? – earthw0rmjim
「日曆API尚未在項目608941808256中使用過,或者被禁用。」你能不正確地鍵入項目ID嗎? – DaImTo
@ user13它已啓用...我已經提到htat。 – PampaZiya