除了接受的答案:
当对日历数据进行任何更改时,将发送此代码广播的意图:
<receiver
android:name=".NativeEventChangeReceiver">
<intent-filter>
<action android:name="android.intent.action.PROVIDER_CHANGED"/>
<data android:scheme="content"/>
<data android:host="com.android.calendar"/>
</intent-filter>
</receiver>
不幸的是,它也会在设备启动时广播,或者在创建提供程序并且没有额外的内容可以读取时广播。
要使您的应用程序仅处理事件实例的插入/删除:
跟踪事件实例的总数(正如 SagiLow 指出的那样,这仅适用于添加/删除,不考虑更新)。如果更改,请根据用户日历重新验证您的数据:
public class CalendarChangedReceiver extends BroadcastReceiver
{
private static final String TAG = "CalendarChangedReceiver";
@Override
public void onReceive(Context context, Intent intent) {
//Check number of instances
final SharedPreferences prefs = context.getSharedPreferences(Enums.Config.USER_CONSTANTS, Context.MODE_PRIVATE);`enter code here`
long lastTimeValidated = prefs.getLong(AppData.LONG_LAST_TIME_VALIDATED, 0);
int numRowsLastTimeValidated = prefs.getInt(AppData.INT_NUM_ROWS_LAST_TIME_VALIDATED, 0);
int numberOfInstances = getNumberOfInstances(lastTimeValidated, context);
if(numberOfInstances != numRowsLastTimeValidated) {
/* Do somethng here, for instance:
Intent serviceIntent = new Intent(context, ValidateCalendarEventsService.class);
context.startService(serviceIntent);
*/
}
}
private int getNumberOfInstances(long lastTimeValidated, Context context) {
Calendar beginTime = Calendar.getInstance();
beginTime.setTimeInMillis(lastTimeValidated);
Calendar endTime = Calendar.getInstance();
endTime.add(Calendar.YEAR, 1);
endTime.add(Calendar.DAY_OF_MONTH, 1);//now + 366
long startMillis = beginTime.getTimeInMillis();
long endMillis = endTime.getTimeInMillis();
Cursor cur = null;
ContentResolver cr = context.getContentResolver();
// Construct the query with the desired date range.
Uri.Builder builder = CalendarContract.Instances.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, startMillis);
ContentUris.appendId(builder, endMillis);
// Submit the query
cur = cr.query(builder.build(), null, null, null, null);
//handle results
return cur.getCount();
}
}