获取谷歌日历日程数据

首先抄袭一下官网的文档,这个坑爹的文档,浪费了我一天的时间都在找问题是什么,还浪费了爱哥几十分钟来研究为啥不行。哪里有问题在最后...

Android Quickstart

Complete the steps described in the rest of this page, and in about ten minutes you'll have a simple Android application that makes requests to the Google Calendar API.

Note: The purpose of this quickstart is to demonstrate the use of the Calendar API in an Android application. However, production calendar apps will strongly benefit by making use of the  Calendar Provider content provider, which works offline, receives pushes, is a good match for the platform.

Prerequisites

To run this quickstart, you'll need:

  • Android Studio SDK 1.2 or later.
  • Android SDK packages for API 23 or later, including the latest versions of Google Repository, Android Support Library and Google Play Services.
  • Access to the internet on your test device.
  • A Google account with Google Calendar enabled.

This quickstart will assume you are using Android Studio IDE (as opposed to the stand-alone SDK Tools) and are comfortable finding, creating and editing files within a Studio project.

Step 1: Acquire a SHA1 fingerprint

In a terminal, run the folowing Keytool utility command to get the SHA1 fingerprint you will use to enable the API.

  
  
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v

When asked for a keystore password, enter "android".

The Keytool prints the fingerprint to the shell. For example:

$ keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v
Enter keystore password: Type "android" if using debug.keystore
Alias name: androiddebugkey
Creation date: Dec 4, 2014
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Android Debug, O=Android, C=US
Issuer: CN=Android Debug, O=Android, C=US
Serial number: 503bd581
Valid from: Mon Aug 27 13:16:01 PDT 2012 until: Wed Aug 20 13:16:01 PDT 2042
Certificate fingerprints:
   MD5:  1B:2B:2D:37:E1:CE:06:8B:A0:F0:73:05:3C:A3:63:DD
   SHA1: D8:AA:43:97:59:EE:C5:95:26:6A:07:EE:1C:37:8E:F4:F0:C8:05:C8
   SHA256: F3:6F:98:51:9A:DF:C3:15:4E:48:4B:0F:91:E3:3C:6A:A0:97:DC:0A:3F:B2:D2:E1:FE:23:57:F5:EB:AC:13:30
   Signature algorithm name: SHA1withRSA
   Version: 3

Copy the SHA1 fingerprint, which is highlighted in the example above.

Important: When you create a production app, you should not use the debug keystore. For more information, see  Signing your applications.

Step 2: Turn on the Google Calendar API

  1. Use this wizard to create or select a project in the Google Developers Console and automatically turn on the API. Click Continue, then Go to credentials.
  2. At the top of the page, select the OAuth consent screen tab. Select an Email address, enter a Product name if not already set, and click the Save button.
  3. Select the Credentials tab, click the Add credentials button and select OAuth 2.0 client ID.
  4. Select the application type Android.
  5. Copy the SHA1 fingerprint from Step 1 into the Signing-certificate fingerprint field.
  6. In the Package name field, enter com.example.calendarquickstart.
  7. Click the Create button.

Step 3: Create a new Android project

  1. Open Android Studio, and start a New Android Studio Project.
  2. In the New Project screen, name the application "CalendarQuickstart".
  3. Set Company Domain to "example.com" and verify that the package name automatically produced matches the one you entered into the Developer Console in Step 2. Click Next.
  4. In the Target Android Devices screen, check the Phone and Tablet checkbox and choose a Minimum SDK of "API 11: Android 3.0 (Honeycomb)". Leave the other checkboxes unchecked. Click Next.
  5. In the Add an activity to Mobile screen, click Add No Activity.
  6. Click Finish.

At this point Android Studio will create and open the project.

Step 4: Prepare the project

In the Project sidebar you will see an expandable list of the default project files Android Studio has created. One of these is the "build.gradle" file associated with the "app" module (not the project).

Warning: Be sure to open the correct  build.gradle file. The first line should read  apply plugin: 'com.android.application'.
  1. Open the app build.gradle file and replace its contents with the following:
        
        
    apply plugin: 'com.android.application'

    android
    {
        compileSdkVersion
    23
        buildToolsVersion
    "23.0.1"

        defaultConfig
    {
            applicationId
    "com.example.calendarquickstart"
            minSdkVersion
    11
            targetSdkVersion
    23
            versionCode
    1
            versionName
    "1.0"
       
    }
        buildTypes
    {
            release
    {
                minifyEnabled
    false
                proguardFiles getDefaultProguardFile
    ('proguard-android.txt'),
                   
    'proguard-rules.pro'
           
    }
       
    }
    }

    dependencies
    {
        compile fileTree
    (dir: 'libs', include: ['*.jar'])
        compile
    'com.android.support:appcompat-v7:23.0.1'
        compile
    'com.google.android.gms:play-services-identity:7.8.0'
        compile
    ('com.google.api-client:google-api-client-android:1.20.0') {
            exclude
    group: 'org.apache.httpcomponents'
       
    }
        compile
    ('com.google.apis:google-api-services-calendar:v3-rev125-1.20.0') {
            exclude
    group: 'org.apache.httpcomponents'
       
    }
       
    }
  2. In the toolbar, select Tools > Android > Sync Project with Gradle Files. This will acquire and make available the libraries your project needs.
  3. Find and open the default src/main/AndroidManifest.xml file and replace its contents with the following code:
        
        
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       
    package="com.example.calendarquickstart">

       
    <uses-permission android:name="android.permission.INTERNET" />
       
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
       
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
       
    <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
       
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />

       
    <application
           
    android:allowBackup="true"
           
    android:icon="@mipmap/ic_launcher"
           
    android:label="Google Calendar API Android Quickstart"
           
    android:theme="@style/AppTheme" >
           
    <activity
               
    android:name=".MainActivity"
               
    android:label="Google Calendar API Android Quickstart" >
               
    <intent-filter>
                   
    <action android:name="android.intent.action.MAIN" />
                   
    <category android:name="android.intent.category.LAUNCHER" />
               
    </intent-filter>
           
    </activity>

           
    <meta-data
               
    android:name="com.google.android.gms.version"
               
    android:value="@integer/google_play_services_version" />
       
    </application>
    </manifest>

Step 5: Setup the sample

Note: For simplicity this quickstart builds its layout dynamically. Most Android applications, however, benefit from defining layouts, strings and other resources in  XML resource files.

Create a new Java class called "MainActivity" and replace the contents of the new file with the following code:

  
  
package com.example.calendarquickstart;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.GooglePlayServicesAvailabilityIOException;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;

import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.ExponentialBackOff;

import com.google.api.services.calendar.CalendarScopes;
import com.google.api.client.util.DateTime;

import com.google.api.services.calendar.model.*;

import android.accounts.AccountManager;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends Activity {
   
GoogleAccountCredential mCredential;
   
private TextView mOutputText;
   
ProgressDialog mProgress;

   
static final int REQUEST_ACCOUNT_PICKER = 1000;
   
static final int REQUEST_AUTHORIZATION = 1001;
   
static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002;
   
private static final String PREF_ACCOUNT_NAME = "accountName";
   
private static final String[] SCOPES = { CalendarScopes.CALENDAR_READONLY };

   
/**
     * Create the main activity.
     * @param savedInstanceState previously saved instance data.
     */

   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
       
LinearLayout activityLayout = new LinearLayout(this);
       
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
               
LinearLayout.LayoutParams.MATCH_PARENT,
               
LinearLayout.LayoutParams.MATCH_PARENT);
        activityLayout
.setLayoutParams(lp);
        activityLayout
.setOrientation(LinearLayout.VERTICAL);
        activityLayout
.setPadding(16, 16, 16, 16);

       
ViewGroup.LayoutParams tlp = new ViewGroup.LayoutParams(
               
ViewGroup.LayoutParams.WRAP_CONTENT,
               
ViewGroup.LayoutParams.WRAP_CONTENT);

        mOutputText
= new TextView(this);
        mOutputText
.setLayoutParams(tlp);
        mOutputText
.setPadding(16, 16, 16, 16);
        mOutputText
.setVerticalScrollBarEnabled(true);
        mOutputText
.setMovementMethod(new ScrollingMovementMethod());
        activityLayout
.addView(mOutputText);

        mProgress
= new ProgressDialog(this);
        mProgress
.setMessage("Calling Google Calendar API ...");

        setContentView
(activityLayout);

       
// Initialize credentials and service object.
       
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
        mCredential
= GoogleAccountCredential.usingOAuth2(
                getApplicationContext
(), Arrays.asList(SCOPES))
               
.setBackOff(new ExponentialBackOff())
               
.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));
   
}

   
   
/**
     * Called whenever this activity is pushed to the foreground, such as after
     * a call to onCreate().
     */

   
@Override
   
protected void onResume() {
       
super.onResume();
       
if (isGooglePlayServicesAvailable()) {
            refreshResults
();
       
} else {
            mOutputText
.setText("Google Play Services required: " +
                   
"after installing, close and relaunch this app.");
       
}
   
}

   
/**
     * Called when an activity launched here (specifically, AccountPicker
     * and authorization) exits, giving you the requestCode you started it with,
     * the resultCode it returned, and any additional data from it.
     * @param requestCode code indicating which activity result is incoming.
     * @param resultCode code indicating the result of the incoming
     *     activity result.
     * @param data Intent (containing result data) returned by incoming
     *     activity result.
     */

   
@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) {
                    isGooglePlayServicesAvailable
();
               
}
               
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) {
                        mCredential
.setSelectedAccountName(accountName);
                       
SharedPreferences settings =
                                getPreferences
(Context.MODE_PRIVATE);
                       
SharedPreferences.Editor editor = settings.edit();
                        editor
.putString(PREF_ACCOUNT_NAME, accountName);
                        editor
.apply();
                   
}
               
} else if (resultCode == RESULT_CANCELED) {
                    mOutputText
.setText("Account unspecified.");
               
}
               
break;
           
case REQUEST_AUTHORIZATION:
               
if (resultCode != RESULT_OK) {
                    chooseAccount
();
               
}
               
break;
       
}

       
super.onActivityResult(requestCode, resultCode, data);
   
}

   
/**
     * Attempt to get a set of data from the Google Calendar API to display. If the
     * email address isn't known yet, then call chooseAccount() method so the
     * user can pick an account.
     */

   
private void refreshResults() {
       
if (mCredential.getSelectedAccountName() == null) {
            chooseAccount
();
       
} else {
           
if (isDeviceOnline()) {
               
new MakeRequestTask(mCredential).execute();
           
} else {
                mOutputText
.setText("No network connection available.");
           
}
       
}
   
}

   
/**
     * Starts an activity in Google Play Services so the user can pick an
     * account.
     */

   
private void chooseAccount() {
        startActivityForResult
(
                mCredential
.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
   
}

   
/**
     * Checks whether the device currently has a network connection.
     * @return true if the device has a network connection, false otherwise.
     */

   
private boolean isDeviceOnline() {
       
ConnectivityManager connMgr =
               
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
       
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
       
return (networkInfo != null && networkInfo.isConnected());
   
}

   
/**
     * Check that Google Play services APK is installed and up to date. Will
     * launch an error dialog for the user to update Google Play Services if
     * possible.
     * @return true if Google Play Services is available and up to
     *     date on this device; false otherwise.
     */

   
private boolean isGooglePlayServicesAvailable() {
       
final int connectionStatusCode =
               
GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
       
if (GooglePlayServicesUtil.isUserRecoverableError(connectionStatusCode)) {
            showGooglePlayServicesAvailabilityErrorDialog
(connectionStatusCode);
           
return false;
       
} else if (connectionStatusCode != ConnectionResult.SUCCESS ) {
           
return false;
       
}
       
return true;
   
}

   
/**
     * Display an error dialog showing that Google Play Services is missing
     * or out of date.
     * @param connectionStatusCode code describing the presence (or lack of)
     *     Google Play Services on this device.
     */

   
void showGooglePlayServicesAvailabilityErrorDialog(
           
final int connectionStatusCode) {
       
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
                connectionStatusCode
,
               
MainActivity.this,
                REQUEST_GOOGLE_PLAY_SERVICES
);
        dialog
.show();
   
}

   
/**
     * An asynchronous task that handles the Google Calendar API call.
     * Placing the API calls in their own task ensures the UI stays responsive.
     */

   
private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
       
private com.google.api.services.calendar.Calendar mService = null;
       
private Exception mLastError = null;

       
public MakeRequestTask(GoogleAccountCredential credential) {
           
HttpTransport transport = AndroidHttp.newCompatibleTransport();
           
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
            mService
= new com.google.api.services.calendar.Calendar.Builder(
                    transport
, jsonFactory, credential)
                   
.setApplicationName("Google Calendar API Android Quickstart")
                   
.build();
       
}

       
/**
         * Background task to call Google Calendar API.
         * @param params no parameters needed for this task.
         */

       
@Override
       
protected List<String> doInBackground(Void... params) {
           
try {
               
return getDataFromApi();
           
} catch (Exception e) {
                mLastError
= e;
                cancel
(true);
               
return null;
           
}
       
}

       
/**
         * Fetch a list of the next 10 events from the primary calendar.
         * @return List of Strings describing returned events.
         * @throws IOException
         */

       
private List<String> getDataFromApi() throws IOException {
           
// List the next 10 events from the primary calendar.
           
DateTime now = new DateTime(System.currentTimeMillis());
           
List<String> eventStrings = new ArrayList<String>();
           
Events events = mService.events().list("primary")
                   
.setMaxResults(10)
                   
.setTimeMin(now)
                   
.setOrderBy("startTime")
                   
.setSingleEvents(true)
                   
.execute();
           
List<Event> items = events.getItems();

           
for (Event event : items) {
               
DateTime start = event.getStart().getDateTime();
               
if (start == null) {
                   
// All-day events don't have start times, so just use
                   
// the start date.
                    start
= event.getStart().getDate();
               
}
                eventStrings
.add(
                       
String.format("%s (%s)", event.getSummary(), start));
           
}
           
return eventStrings;
       
}


       
@Override
       
protected void onPreExecute() {
            mOutputText
.setText("");
            mProgress
.show();
       
}

       
@Override
       
protected void onPostExecute(List<String> output) {
            mProgress
.hide();
           
if (output == null || output.size() == 0) {
                mOutputText
.setText("No results returned.");
           
} else {
                output
.add(0, "Data retrieved using the Google Calendar API:");
                mOutputText
.setText(TextUtils.join("\n", output));
           
}
       
}

       
@Override
       
protected void onCancelled() {
            mProgress
.hide();
           
if (mLastError != null) {
               
if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
                    showGooglePlayServicesAvailabilityErrorDialog
(
                           
((GooglePlayServicesAvailabilityIOException) mLastError)
                                   
.getConnectionStatusCode());
               
} else if (mLastError instanceof UserRecoverableAuthIOException) {
                    startActivityForResult
(
                           
((UserRecoverableAuthIOException) mLastError).getIntent(),
                           
MainActivity.REQUEST_AUTHORIZATION);
               
} else {
                    mOutputText
.setText("The following error occurred:\n"
                           
+ mLastError.getMessage());
               
}
           
} else {
                mOutputText
.setText("Request cancelled.");
           
}
       
}
   
}
}

Step 6: Run the app

  1. You can test the app by clicking the Run > Run app menu item.
  2. You will be prompted to select a connected device (recommended) or emulation to run the app on. If you choose to run on an emulation, make sure it is configured to use one of the Google APIs (Google Inc.) system images. If you attempt to run the quickstart on a device that does not currently have Google Play services installed, the quickstart will produce a dialog from which you can install it.
  3. If running on an emulator, allow it to fully start and establish its network connection.
  4. If starting the emulator for the first time, you may need to unlock its screen. Regardless, the quickstart app should start automatically.
  5. The first time you run the app it will prompt you to specify an account. Select one of the ones suggested or selectAdd account and follow the instruction prompts to choose an account to connect to.
  6. After selecting an account, the app will prompt you to authorize access. Click OK to authorize.









在Step 4 c 里面让我们用了gms version 配置的meta.
<meta-data
            android:name="com.google.android.calendar.v3.API_KEY"
            android:value="******" />
阿西吧,爱哥好牛逼!谨以此文纪念爱哥牛逼哄哄的样子~@伯乐还要币,,就算了啊。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值