Android 访问谷歌日历事件

Android 访问谷歌日历事件,android,google-calendar-api,Android,Google Calendar Api,我想在我的应用程序中从公共谷歌日历中获取事件 这是我的活动,可以访问somePublicCalendar@google.com我换了一个假帐号,但我的日历是公开的。当然somePublicCalendar@gmail.com不是我的帐户,我无法管理它。我只是想看看日程安排和预约是否有差距。 这是我的活动,目前,光标似乎是空的 public class calendar extends AppCompatActivity implements View.OnClickListener{

我想在我的应用程序中从公共谷歌日历中获取事件

这是我的活动,可以访问somePublicCalendar@google.com我换了一个假帐号,但我的日历是公开的。当然somePublicCalendar@gmail.com不是我的帐户,我无法管理它。我只是想看看日程安排和预约是否有差距。 这是我的活动,目前,光标似乎是空的

public class calendar extends AppCompatActivity implements View.OnClickListener{

    CalendarView calendarView;
    final int callbackId = 42;
    Button home;

    // Projection array. Creating indices for this array instead of doing
// dynamic lookups improves performance.
    public static final String[] EVENT_PROJECTION = new String[] {
            CalendarContract.Calendars._ID,                           // 0
            CalendarContract.Calendars.ACCOUNT_NAME,                  // 1
            CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,         // 2
            CalendarContract.Calendars.OWNER_ACCOUNT                  // 3
    };

    // The indices for the projection array above.
    private static final int PROJECTION_ID_INDEX = 0;
    private static final int PROJECTION_ACCOUNT_NAME_INDEX = 1;
    private static final int PROJECTION_DISPLAY_NAME_INDEX = 2;
    private static final int PROJECTION_OWNER_ACCOUNT_INDEX = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calendar);
        home = findViewById(R.id.inicio);
        calendarView = findViewById(R.id.calendarView);
        checkPermission(callbackId, Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR);
        calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
                consultarCalendario();
            }
        });
    }
    @Override
    public void onRequestPermissionsResult(int callbackId,
                                           String permissions[], int[] grantResults) {

    }

    public void consultarCalendario() {
        // Run query

        Cursor cur = null;
        ContentResolver cr = getContentResolver();
        Uri uri = CalendarContract.Calendars.CONTENT_URI;
        String selection = "((" + CalendarContract.Calendars.ACCOUNT_NAME + " = ?) AND ("
                + CalendarContract.Calendars.ACCOUNT_TYPE + " = ?) AND ("
                + CalendarContract.Calendars.OWNER_ACCOUNT + " = ?))";
        String[] selectionArgs = new String[]{"somePublicCalendar@gmail.com", "com.google",
                "somePublicCalendar@gmail.com"};
// Submit the query and get a Cursor object back.
        cur = cr.query(uri, EVENT_PROJECTION, selection, selectionArgs, null);
        // Use the cursor to step through the returned records
        while (cur.moveToNext()) {
            long calID = 0;
            String displayName = null;
            String accountName = null;
            String ownerName = null;

            // Get the field values
            calID = cur.getLong(PROJECTION_ID_INDEX);
            displayName = cur.getString(PROJECTION_DISPLAY_NAME_INDEX);
            accountName = cur.getString(PROJECTION_ACCOUNT_NAME_INDEX);
            ownerName = cur.getString(PROJECTION_OWNER_ACCOUNT_INDEX);

            // Do something with the values...
            Log.d("Conexion a calendario",calID + "/" + displayName+ "/" + accountName + "/" + ownerName);
        }
    }
    private void checkPermission(int callbackId, String... permissionsId) {
        boolean permissions = true;
        for (String p : permissionsId) {
            permissions = permissions && ContextCompat.checkSelfPermission(this, p) == PERMISSION_GRANTED;
        }

        if (!permissions)
            ActivityCompat.requestPermissions(this, permissionsId, callbackId);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.inicio:
                startActivity(new Intent(this, Principal.class));
                break;
        }
    }
}

我不熟悉您使用的日历库,但这就是我从Google日历中获取条目的方式:

private void callGetEvents() {

    String sURL1 = "https://www.googleapis.com/calendar/v3/calendars/somePublicCalendar%40gmail.com/events?key=XYZTHECALENDARKEYZYX";

    getEvents(sURL1);

}

private void getEvents(String url) {
    final ProgressDialog dialog;    

    dialog = new ProgressDialog(thisContext);         
    dialog.setMessage((String) getResources().getText(R.string.loading_please_wait));         
    dialog.setIndeterminate(true);         
    dialog.setCancelable(false);         
    dialog.show();     

    listOfEvents = new ArrayList<EventItem>();

    JsonObjectRequest req = new JsonObjectRequest(url, null, new Response.Listener<JSONObject> () {  

        @SuppressLint("SimpleDateFormat")
        @Override
        public void onResponse(JSONObject response) {
            try {

                JSONArray items = response.getJSONArray("items");
                Date today = new Date();

                for (int i = 0; i < items.length(); i++) {
                    JSONObject oneObject = null;
                    try {
                        oneObject = items.getJSONObject(i);
                    } catch (JSONException e) {
                        continue;
                    }

                    String title = "";
                    try {
                        title = oneObject.getString("summary");
                    } catch (JSONException e) {
                        title = "";
                    }

                    String description = "";
                    try {
                        description = oneObject.getString("description");
                    } catch (JSONException e) {
                        description = "";
                    }

                    String location = "";
                    try {
                        location = oneObject.getString("location");
                    } catch (JSONException e) {
                        location = "";
                    }

                    JSONObject startObject = null;
                    String startDate = "";
                    Date start_date = new Date();
                    JSONObject endObject = null;
                    String endDate = "";
                    Date end_date = new Date();

                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

                    try {   
                        startObject = oneObject.getJSONObject("start");
                        startDate = startObject.getString("dateTime");
                        try {
                            start_date = dateFormat.parse(startDate);
                        } catch (java.text.ParseException e) {
                            e.printStackTrace();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    try {
                        endObject = oneObject.getJSONObject("end");
                        endDate = endObject.getString("dateTime");
                        try {
                            end_date = dateFormat.parse(endDate);
                        } catch (java.text.ParseException e) {
                            e.printStackTrace();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    EventItem item = new EventItem(title, description, location, start_date, end_date);

                    Log.i("Compare", today.toString() + ":" + endDate);

                    if (title.length() > 0) {
                        if (today.compareTo(end_date) < 0) {
                            listOfEvents.add(item);             
                        }
                    }

                }


                Collections.sort(listOfEvents, new Comparator<EventItem>() {
                      public int compare(EventItem o1, EventItem o2) {
                          return o1.getStartDate().compareTo(o2.getStartDate());
                      }
                    });


                try {

                    adapter = new EventListAdapter(thisContext, listOfEvents);
                    eventListView.setAdapter(adapter);

                } catch (Exception e) {
                   e.printStackTrace();
                } 


            } catch (JSONException e) {
                e.printStackTrace();
            }

            dialog.dismiss();
        }


    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.e("Error: ", error.getMessage());
            Log.e("Error: ", error.getMessage());
            dialog.dismiss();
        }
    }) {

       @Override
       public Map<String, String> getHeaders() throws AuthFailureError {
           HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Accept", "application/json; charset=UTF-8");
                headers.put("Content-Type", "application/json; charset=UTF-8");
           return headers;
       };
    };

    // add the request object to the queue to be executed
    MyApplication.getInstance().addToRequestQueue(req);
}
private void callGetEvents(){
字符串sURL1=”https://www.googleapis.com/calendar/v3/calendars/somePublicCalendar%40gmail.com/events?key=XYZTHECALENDARKEYZYX";
getEvents(sURL1);
}
私有void getEvents(字符串url){
最终进程对话框;
dialog=新建进度对话框(thisContext);
setMessage((String)getResources().getText(R.String.loading_please_wait));
对话框。setUndeterminate(true);
对话框。可设置可取消(false);
dialog.show();
listOfEvents=newarraylist();
JsonObjectRequest req=newJSONObjectRequest(url,null,new Response.Listener(){
@SuppressLint(“SimpleDataFormat”)
@凌驾
公共void onResponse(JSONObject响应){
试一试{
JSONArray items=response.getJSONArray(“items”);
今天日期=新日期();
对于(int i=0;i0){
如果(今天)与(结束日期)相比<0{
事件列表。添加(项目);
}
}
}
Collections.sort(listOfEvents,newcomparator(){
公共整数比较(事件项o1、事件项o2){
返回o1.getStartDate().compareTo(o2.getStartDate());
}
});
试一试{
适配器=新事件列表适配器(此上下文,事件列表);
setAdapter(适配器);
}捕获(例外e){
e、 printStackTrace();
} 
}捕获(JSONException e){
e、 printStackTrace();
}
dialog.dismise();
}
},new Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
e(“Error:,Error.getMessage());
Log.e(“Error:,Error.getMessage());
dialog.dismise();
}
}) {
@凌驾
公共映射getHeaders()引发AuthFailureError{
HashMap headers=新的HashMap();
headers.put(“Accept”,“application/json;charset=UTF-8”);
headers.put(“内容类型”、“应用程序/json;字符集=UTF-8”);
返回标题;
};
};
//将请求对象添加到要执行的队列中
MyApplication.getInstance().addToRequestQueue(req);
}