2016-08-08 4 views
-1

Google 캘린더 API를 사용하려면 많은 문제가 있습니다. 나는 많은 것을 수색하고 실패로 보이는 많은 해결책을 시도했다.Google 캘린더 API 안드로이드 : 403 오류

내가 시도하는 것 : - 사용 연락처 API -의 Google+ API - 구글 캘린더 API - 디버그/릴리즈 모드 에서 앱을 실행 - 많은 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(); 
} 





} 

아래 오류가 발생했습니다. 나는이 질문을하기 전에 모든 것이 갖추어 졌는지 확인했다. 나는 모든 곳에서 해답을 찾을 수 있었고 아무 것도 해보지 않았다. "cancel (true)"는 물론 트리거되지만 if 조건은 입력되지 않습니다. btw. 오류 프로젝트 번호를보고 할 수 있기 때문에, 당신이 제대로 SHA-1과 API 키를 입력 한 의미

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

Google API 콘솔에서 캘린더 API를 사용하도록 설정 했습니까? – earthw0rmjim

+0

"캘린더 API가 프로젝트 608941808256에서 사용되지 않았거나 비활성화되어 있습니다." 프로젝트 ID를 잘못 입력 했습니까? – DaImTo

+0

@ user13 사용 가능 ... htat을 언급했습니다. – PampaZiya

답변

0

(코드 참조). Google 개발 콘솔의 문제입니다. 그 화면에서> 라이브러리> 구글 캘린더 API

에서

로그인 당신은 당신의 API 키 모두를 위해이 API를 사용 할 수 있어야한다 :

다음은해야 할 일입니다. 사용을 클릭하면 자격 증명 페이지로 계속 진행합니다.

것은> 자격 증명을 만들기 당신이 사용하는 API를 입력하고 당신이 그것을 사용하는 경우 일단 나를

을 선택 도와주세요. 귀하의 경우에는 Google 캘린더 API 및 Android가 될 것입니다. 이를 입력하면 개발자 콘솔은 0Auth 2.0 자격 증명을 생성하여 Google 사용자가 로그인하여 앱에서 Google 캘린더 API를 사용할 수 있도록 도와야합니다. 희망이 도움이!

+0

이봐, 이미 확인한 이미지를 확인했다면! 정보를 가져 주셔서 감사하지만 귀하의 단계가 이미 완료된 것 같지만 아직 작동하지 않습니다. 클라이언트 ID가 있는데 "GoogleAccountCredentials.usingaudience (getApplicationContext();"잠재 고객 : 서버 : client_id : "+ CLIENT_ID)"를 사용하려고하지만 "INVALID_AUDIENCE"오류가 발생해도 작동하지 않습니다. – PampaZiya