事件未保存在日历中

时间:2017-04-26 08:20:49

标签: java android calendar

我想直接在日历中保存活动,而无需打开日历应用。我发现在某些设备中,事件不会保存在日历中,但我没有在logcat中收到任何错误。这是我正在使用的代码,

Events.STATUS, Events.STATUS_CONFIRMED

有谁知道发生了什么事?

谢谢!

更新

在相同的设备中,您需要设置状态Content-Type,这是问题

1 个答案:

答案 0 :(得分:2)

找到解决方案:

按照直接创建活动的步骤:

的Manifest.xml

在Manifest中添加权限

 <uses-permission android:name="android.permission.WRITE_CALENDAR" />
 <uses-permission android:name="android.permission.READ_CALENDAR" />

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="testpreference.com.testcalendar.MainActivity">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Calendars" />
    <Spinner
        android:id="@+id/calendarid_spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/newevent_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Event"
        android:layout_gravity="center_horizontal"

        />
</LinearLayout>

MainActivity.java

        import android.os.Bundle;
        import android.support.v7.app.AppCompatActivity;
        import android.view.View;
        import android.widget.ArrayAdapter;
        import android.widget.Button;
        import android.widget.Spinner;
        import android.widget.Toast;

        import java.util.ArrayList;
        import java.util.Date;
        import java.util.Enumeration;
        import java.util.Hashtable;
        import java.util.List;

        public class MainActivity extends AppCompatActivity {

            private static final String TAG = "MainActivity";
            private Spinner calendarIdSpinner;
            private Hashtable<String,String> calendarIdTable;
            private Button newEventButton;


            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                calendarIdSpinner = (Spinner) findViewById(R.id.calendarid_spinner);
                newEventButton = (Button) findViewById(R.id.newevent_button);

                newEventButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (CalendarHelper.haveCalendarReadWritePermissions(MainActivity.this))
                        {
                            addNewEvent();
                        }
                        else
                        {
                            CalendarHelper.requestCalendarReadWritePermission(MainActivity.this);
                        }
                    }
                });


                calendarIdSpinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());

                if (CalendarHelper.haveCalendarReadWritePermissions(this))
                {
                    //Load calendars
                    calendarIdTable = CalendarHelper.listCalendarId(this);

                    updateCalendarIdSpinner();

                }


            }

            private void updateCalendarIdSpinner()
            {
                if (calendarIdTable==null)
                {
                    return;
                }

                List<String> list = new ArrayList<String>();

                Enumeration e = calendarIdTable.keys();
                while (e.hasMoreElements()) {
                    String key = (String) e.nextElement();
                    list.add(key);
                }

                ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                        android.R.layout.simple_spinner_item, list);
                dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                calendarIdSpinner.setAdapter(dataAdapter);
            }

            @Override
            public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

                if (requestCode==CalendarHelper.CALENDARHELPER_PERMISSION_REQUEST_CODE)
                {
                    if (CalendarHelper.haveCalendarReadWritePermissions(this))
                    {
                        Toast.makeText(this, (String)"Have Calendar Read/Write Permission.",
                                Toast.LENGTH_LONG).show();

                    }

                }

                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }

            private void addNewEvent()
            {
                if (calendarIdTable==null)
                {
                    Toast.makeText(this, (String)"No calendars found. Please ensure at least one google account has been added.",
                            Toast.LENGTH_LONG).show();
                    //Load calendars
                    calendarIdTable = CalendarHelper.listCalendarId(this);

                    updateCalendarIdSpinner();

                    return;
                }


                final long oneHour = 1000 * 60 * 60;
                final long tenMinutes = 1000 * 60 * 10;

                long oneHourFromNow = (new Date()).getTime() + oneHour;
                long tenMinutesFromNow = (new Date()).getTime() + tenMinutes;


                String calendarString = calendarIdSpinner.getSelectedItem().toString();

                int calendar_id = Integer.parseInt(calendarIdTable.get(calendarString));

                CalendarHelper.MakeNewCalendarEntry(this, "Test", "Add event", "Somewhere",tenMinutesFromNow,tenMinutesFromNow+oneHour,false,true,calendar_id,3);

            }

        }
  1. 为日历选择创建课程

     import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemSelectedListener;
    import android.widget.Toast;
    
    public class CustomOnItemSelectedListener implements OnItemSelectedListener {
    
        private static final String TAG = "OnItemSelectedListener";
    
        public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
            Toast.makeText(parent.getContext(),
                    "OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
                    Toast.LENGTH_SHORT).show();
        }
    
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
            Log.v(TAG,"onNohingSelected() called.");
        }
    
    }
    
  2. CalendarHelper.java

    import android.Manifest;
    import android.app.Activity;
    import android.content.ContentResolver;
    import android.content.ContentValues;
    import android.content.Context;
    import android.content.pm.PackageManager;
    import android.database.Cursor;
    import android.net.Uri;
    import android.provider.CalendarContract.Events;
    import android.provider.CalendarContract.Reminders;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.content.ContextCompat;
    import android.util.Log;
    
    import java.util.ArrayList;
    import java.util.Hashtable;
    import java.util.List;
    import java.util.TimeZone;
    
    public class CalendarHelper {
    
        //Remember to initialize this activityObj first, by calling initActivityObj(this) from
    //your activity
        private static final String TAG = "CalendarHelper";
        public static final int CALENDARHELPER_PERMISSION_REQUEST_CODE = 99;
    
    
        public static void MakeNewCalendarEntry(Activity caller,String title,String description,String location,long startTime,long endTime, boolean allDay,boolean hasAlarm, int calendarId,int selectedReminderValue) {
    
            ContentResolver cr = caller.getContentResolver();
            ContentValues values = new ContentValues();
            values.put(Events.DTSTART, startTime);
            values.put(Events.DTEND, endTime);
            values.put(Events.TITLE, title);
            values.put(Events.DESCRIPTION, description);
            values.put(Events.CALENDAR_ID, calendarId);
            values.put(Events.STATUS, Events.STATUS_CONFIRMED);
    
    
            if (allDay)
            {
                values.put(Events.ALL_DAY, true);
            }
    
            if (hasAlarm)
            {
                values.put(Events.HAS_ALARM, true);
            }
    
            //Get current timezone
            values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
            Log.i(TAG, "Timezone retrieved=>"+TimeZone.getDefault().getID());
            Uri uri = cr.insert(Events.CONTENT_URI, values);
            Log.i(TAG, "Uri returned=>"+uri.toString());
            // get the event ID that is the last element in the Uri
            long eventID = Long.parseLong(uri.getLastPathSegment());
    
            if (hasAlarm)
            {
                ContentValues reminders = new ContentValues();
                reminders.put(Reminders.EVENT_ID, eventID);
                reminders.put(Reminders.METHOD, Reminders.METHOD_ALERT);
                reminders.put(Reminders.MINUTES, selectedReminderValue);
    
                Uri uri2 = cr.insert(Reminders.CONTENT_URI, reminders);
            }
    
    
        }
    
        public static void requestCalendarReadWritePermission(Activity caller)
        {
            List<String> permissionList = new ArrayList<String>();
    
            if  (ContextCompat.checkSelfPermission(caller,Manifest.permission.WRITE_CALENDAR)!=PackageManager.PERMISSION_GRANTED)
            {
                permissionList.add(Manifest.permission.WRITE_CALENDAR);
    
            }
    
            if  (ContextCompat.checkSelfPermission(caller,Manifest.permission.READ_CALENDAR)!=PackageManager.PERMISSION_GRANTED)
            {
                permissionList.add(Manifest.permission.READ_CALENDAR);
    
            }
    
            if (permissionList.size()>0)
            {
                String [] permissionArray = new String[permissionList.size()];
    
                for (int i=0;i<permissionList.size();i++)
                {
                    permissionArray[i] = permissionList.get(i);
                }
    
                ActivityCompat.requestPermissions(caller,
                        permissionArray,
                        CALENDARHELPER_PERMISSION_REQUEST_CODE);
            }
    
        }
    
        public static Hashtable listCalendarId(Context c) {
    
            if (haveCalendarReadWritePermissions((Activity)c)) {
    
                String projection[] = {"_id", "calendar_displayName"};
                Uri calendars;
                calendars = Uri.parse("content://com.android.calendar/calendars");
    
                ContentResolver contentResolver = c.getContentResolver();
                Cursor managedCursor = contentResolver.query(calendars, projection, null, null, null);
    
                if (managedCursor.moveToFirst())
                {
                    String calName;
                    String calID;
                    int cont = 0;
                    int nameCol = managedCursor.getColumnIndex(projection[1]);
                    int idCol = managedCursor.getColumnIndex(projection[0]);
                    Hashtable<String,String> calendarIdTable = new Hashtable<>();
    
                    do
                    {
                        calName = managedCursor.getString(nameCol);
                        calID = managedCursor.getString(idCol);
                        Log.v(TAG, "CalendarName:" + calName + " ,id:" + calID);
                        calendarIdTable.put(calName,calID);
                        cont++;
                    } while (managedCursor.moveToNext());
                    managedCursor.close();
    
                    return calendarIdTable;
                }
    
            }
    
            return null;
    
        }
    
        public static boolean haveCalendarReadWritePermissions(Activity caller)
        {
            int permissionCheck = ContextCompat.checkSelfPermission(caller,
                    Manifest.permission.READ_CALENDAR);
    
            if (permissionCheck== PackageManager.PERMISSION_GRANTED)
            {
                permissionCheck = ContextCompat.checkSelfPermission(caller,
                        Manifest.permission.WRITE_CALENDAR);
    
                if (permissionCheck== PackageManager.PERMISSION_GRANTED)
                {
                    return true;
                }
            }
    
            return false;
        }
    
    }