2016-08-08 53 views
-1

Ich habe eine Menge Probleme beim Versuch, Google Kalender Api mit mir zu arbeiten. Ich habe viel gesucht und viele Lösungen ausprobiert, die zu versagen scheinen.Google Kalender Api Android: 403 Fehler

Was ich versucht: - Aktivieren Kontakte API - Google+ API - Google Calendar API - Ausführen der App im Debug/Release-Modus - Recreating den SHA1-Code viele, viele Male - Ändern der Name der App

Hier ist meine MainActivity, ähnlich wie die im Quickstart, aber ich habe sie ein wenig geändert, um ein einmal erstelltes Event zu erstellen.

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(); 
} 





} 

Unten ist der Fehler Ich erhalte. Ich habe dafür gesorgt, dass alles so ist, wie es sein sollte, bevor ich diese Frage stelle, und ich habe überall nach Antworten gesucht und nichts scheint zu funktionieren. "cancel (true)" wird natürlich ausgelöst, aber keine der if-Bedingungen wird eingegeben. (Siehe Code)

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

+0

Haben Sie die Kalender-API in der Google API-Konsole aktiviert? – earthw0rmjim

+0

"Die Kalender-API wurde im Projekt 608941808256 nicht verwendet oder ist deaktiviert." Könnten Sie die Projekt-ID falsch eingegeben haben? – DaImTo

+0

@ user13 es ist aktiviert ... Ich habe HTAT erwähnt. – PampaZiya

Antwort

0

Da der Fehler das Projekt # melden kann, es bedeutet, dass Sie Ihre SHA-1 und Ihre API-Schlüssel richtig eingegeben haben. Es muss ein Problem in der Google Dev Console sein.

Hier ist, was Sie tun müssen:

Anmelden> Bibliothek> Google Calendar API

Auf diesem Bildschirm sollten Sie in der Lage sein, diese API für alle Ihre API-Schlüssel zu aktivieren. Sobald Sie auf Aktivieren geklickt haben, fahren Sie mit Ihrer Anmeldungsseite fort.

Credentials Erstellen> Helfen Sie mir

wählen Sobald Sie sind es die API geben Sie verwenden und wo Sie es verwenden. In Ihrem Fall wird es Google Kalender API und Android sein. Sobald Sie dies eingegeben haben, sollte Ihnen die Dev-Konsole beim Erstellen von 0Auth 2.0-Anmeldedaten helfen, damit sich Google-Nutzer anmelden und die Google Kalender-API in Ihrer App verwenden können. Hoffe das hilft!

+0

Hey, wenn Sie die Bilder überprüfen, habe ich das schon gemacht! Danke für die Informationen, aber es scheint, dass Ihre Schritte bereits erledigt sind, aber ich kann es nicht zur Arbeit bringen. Ich habe die Client ID und ich versuche "GoogleAccountCredentials.usingaudience (getApplicationContext();" audience: server: client_id: "+ CLIENT_ID)" zu verwenden, aber auch nicht, es heißt "INVALID_AUDIENCE" -Fehler – PampaZiya