Android - how to check which calendar event is currently in progress? - java

I would like to check in internal Android calendar for event which is currently in progress (started before current time, and ends after current time). I'm using Android 2.2
I was playing around with this piece of code - I was trying to set start time to now but this doesn't work, it returns events that started after this moment.
//building query uri
Uri.Builder builder = Uri.parse("content://com.android.calendar/instances/when").buildUpon();
long now = new Date().getTime();
ContentUris.appendId(builder, now - DateUtils.MINUTE_IN_MILLIS * 80);
ContentUris.appendId(builder, now + DateUtils.MINUTE_IN_MILLIS * 80);
Log.d("AlarmReciever", "querying for calendar with id:" + calendarId);
//interating over events
Cursor eventCursor = contentResolver.query(builder.build(), new String[] { "title" }, "Calendars._id=" + calendarId, null, null);
while (eventCursor.moveToNext()) {
final String title = eventCursor.getString(0);
Toast.makeText(context, "title: " + title, Toast.LENGTH_LONG).show();
}
I would appreciate if someone could show me how to do this correctly. Thanks!

Related

how to show error if on device time does not match with internet time in android studio like WhatsApp

im making an android app which shows time of upload relative to the device time, but if the device time and date is not set correct then I do not get the desired result. so how to show warning or error if the device time and date is not correct or matches to the internet time. the app should not work unless the user set the date and time correct.
Get an extra UTC DateTimeOffset parameter as a response from the uploaded API & then convert it into your local timezone.
Cons -
If time is set wrong in the device, you have to create a localization method for it which can convert the timestamp to proper time without interfering with the local timezone.
You can use static timezoneid for conversion or get it by internal API calls, I uses Xamarin soo for me it's like -
var timeZoneId = "Asia/Calcutta"; // use it for worldwide application usage TimeZoneInfo.Local.ToString();
DateTime localizedDateTime = TimeZoneInfo.ConvertTimeFromUtc(incomingDATE.ToUniversalTime(), TimeZoneInfo.FindSystemTimeZoneById(timeZoneId));
Soo convert the received UTC DateTimeOffset to Localized time.
This thing works best for my apps. I use jsoup to search the google time and gets current time and then I compare the phone time with google time. So if these time are different you can stop user using a dialogbox or alertbox to tell them the times have changed. You can implement in MainActivity to check this condition.
Here is a snippet so you get the idea more clearly.
public class HomeActivity extends AppCompatActivity {
//phoneDate and phoneTime to get current phone date and time
String phoneDate = new SimpleDateFormat("dd MMM yyyy ").format(clnd.getTime()).trim();
String phoneTime = new SimpleDateFormat("hh:mm a").format(clnd.getTime()).trim();
String googleDate;
String googleTime ;
#Override
protected void onCreate(Bundle _savedInstanceState) {
super.onCreate(_savedInstanceState);
setContentView(R.layout.home);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
//URL to search time
String url = "https://www.google.co.in/search?q=time";
Document document = Jsoup.connect(url).get();
org.jsoup.select.Elements time = document.getElementsByClass("gsrt vk_bk FzvWSb YwPhnf");
org.jsoup.select.Elements date = document.getElementsByClass("KfQeJ");
Log.d("HTML", "google date" + String.format(date.text()));
Log.d("HTML", "google time" + time.text());
googleDate = date.text().trim();
googleTime = time.text().trim();
//'0'is not present when hour is single digit
char second = googleTime.charAt(1);
if(second == ':'){
googleTime = "0" + googleTime;
}
Log.d("Proper format", "google time" + googleTime);
Log.d("Date", "your current url when webpage loading.." + phoneDate);
Log.d("Time", "your current url when webpage loading.." + phoneTime);
if(googleDate.contains(phoneDate) && googleTime.equals(phoneTime)){
Log.d("Time", "your current url when webpage loading.." + " true");
}else{
Log.d("Time", "your current url when webpage loading.." + " false");
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
}

Accessing field called Date and Time in Event Viewer through Java

I would like to access the field called Date and time from Event Viewer through Java. I managed to get the EventID :
EVENTLOGRECORD record = new EVENTLOGRECORD(pevlr);
if (record.EventID.shortValue() == 4624) {
System.out.println("Successful log in: " + " Event ID: " + record.EventID.shortValue());
}
if (record.EventID.shortValue() == 4634) {
System.out.println("Successful log out: " + " Event ID: " + record.EventID.shortValue());
}
And now the next step would be to get the Date and time
If anyone could help i would really appreciate it !
Meanwhile I figured out how to get the Date and time field. Just used :
long timestamp = record.TimeGenerated.longValue() * 1000;
Date d = new Date(timestamp);

Creating a new intent inside a for loop good or bad?

I am currently stuck with the question, if creating a new intent inside a for loop is good or bad. I have the following situation:
1.
public static void reactivateReminders(Schedule schedule) {
ArrayList<Lecture> allLectures = schedule.getAllLectures();
for(Lecture lecture : allLectures) {
...
// Set up various things for the reminder
...
Intent intent = new Intent(getApplicationContext(), ReminderReceiver.class);
String at = getResources().getString(R.string.at);
String with = getResources().getString(R.string.with);
String beginH = ScheduleHelper.formatNumber(changedBeginH);
String beginM = ScheduleHelper.formatNumber(changedBeginM);
String room = lecture.getRoom();
intent.putExtra("contentText", at + " " + beginH + ":" + beginM + " in " + room + " " + with + " " + lecture.getLecturer());
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), lecture.getAlarmId(), intent, 0);//PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
if(lecture.getBeginH() != beginH || lecture.getBeginM() != beginM)
alarm.cancel(pendingIntent);
alarm.setInexactRepeating(AlarmManager.RTC, calendar.getTimeInMillis() + offset, 1000 * 60 * 60 * 24 * 7, pendingIntent);
}
}
2.
public static void reactivateReminders(Schedule schedule) {
ArrayList<Lecture> allLectures = schedule.getAllLectures();
Intent intent = new Intent(getApplicationContext(), ReminderReceiver.class);
for(Lecture lecture : allLectures) {
...
// Set up various things for the reminder
...
String at = getResources().getString(R.string.at);
String with = getResources().getString(R.string.with);
String beginH = ScheduleHelper.formatNumber(changedBeginH);
String beginM = ScheduleHelper.formatNumber(changedBeginM);
String room = lecture.getRoom();
intent.putExtra("contentText", at + " " + beginH + ":" + beginM + " in " + room + " " + with + " " + lecture.getLecturer());
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), lecture.getAlarmId(), intent, 0);//PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
if(lecture.getBeginH() != beginH || lecture.getBeginM() != beginM)
alarm.cancel(pendingIntent);
alarm.setInexactRepeating(AlarmManager.RTC, calendar.getTimeInMillis() + offset, 1000 * 60 * 60 * 24 * 7, pendingIntent);
}
}
Which option is the better one? I'm not too familiar with Java so I don't know how Java handles either one. Maybe is doesn't make a difference at all but since I'm programming in C++ normally, creating new objects inside a loop worries me.
Thanks for any help in advance.
Edit: Conclusion:
As mentioned by Alex Shutov, it better to not set all reminders at once. The user probably only needs the next one that is coming up.
To achieve this, you should set the earliest reminder somewhere in the app and store the other reminders (or rather the data you use for it) sorted in some place outside the app (XML, SQL, ...) so that your service can, after the earliest reminder set off, read the file to load the next one.
By doing this, you don't burden the system with reminders that the user doesn't even need yet. I will try to implement this idea sometime but for now I will use my approach.
Regarding my code:
A better approach for my posted code is to create the new intent once outside the loop. Since the extra I put in it has the same key, it will overwrite every time and you don't have to create a new intent. Other variables like my "at" and "with", which are constant, can be placed outside of the loop too. The variables "beginH, beginM, room" can be removed and you can just call the functions directly in the putExtra parameter. You can also place the PendingIntent and the AlarmManager line outside the loop.
I would post the code but I think my post will be too big then.
Thanks for the fast help :)
It is a bad idea, because you overload system with unneccessary tasks, you should instead schedule nearest event, in IntentService schedule next event

Android / Blackberry10 call information not appearing

I have made an Android app that I am trying to port over to a blackberry 10 device. Currently, all of the functions of the app work except for one, where I try and get information about recent calls from the phone. This works fine on android, but does not seem to work on the blackberry 10 simulator I am using. Here is my code for the section:
final TextView time = (TextView) findViewById(R.id.AddNewEditTextTime);
final TextView date = (TextView) findViewById(R.id.AddNewEditTextDate);
final TextView number = (TextView) findViewById(R.id.AddNewEditTextNumber);
// fields to select.
String[] strFields = { android.provider.CallLog.Calls.NUMBER,
android.provider.CallLog.Calls.TYPE,
android.provider.CallLog.Calls.CACHED_NAME,
android.provider.CallLog.Calls.CACHED_NUMBER_TYPE,
android.provider.CallLog.Calls.DATE};
// only incoming.
String strSelection = android.provider.CallLog.Calls.TYPE + " = "
+ android.provider.CallLog.Calls.INCOMING_TYPE;
// most recent first
String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
// get a cursor.
Cursor mCallCursor = getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, // content provider
// URI
strFields, // project (fields to get)
strSelection, // selection
null, // selection args
strOrder // sortorder.
);
if (mCallCursor.moveToFirst()) {
String a = mCallCursor.getString(mCallCursor
.getColumnIndex("date"));
String b = mCallCursor.getString(mCallCursor
.getColumnIndex("number"));
mCallCursor.close();
SimpleDateFormat dateF = new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat timeF = new SimpleDateFormat("HH:mm");
String dateString = dateF.format(new Date(Long
.parseLong(a)));
String timeString = timeF.format(new Date(Long
.parseLong(a)));
time.setText(timeString);
date.setText(dateString);
number.setText(b);
}
The if(mCallCursor.moveToFirst()) statement is never entered on the blackberry 10 device, but works fine on Android. Is there something I'm missing / doing wrong, or is there no way to use the android.provider functions like this on a blackberry 10 device?
Apparently accessing call log is not yet supported
This is not supported, the Android API is not hooked up to retreive this data.
Edit: Usually when there's an equivalent native API, the corresponding API in Android will be supported. The Android API almost always uses the native equivalent for its implementation. AFAIK there isn't a native call logs API.
By bbenninger, at support forums.

How to delete specific event in calendar

What I want to do is to delete only the content that is saved by me in the calendar instead of all the content which is already present in the calendar. For that, I use the following code. But it will delete all the content of the calendar. So can anyone tell me how that can be prevented?
Uri CALENDAR_URI = Uri.parse("content://calendar/events");
ContentResolver cr = getContentResolver();
cr.delete(CALENDAR_URI, null, null); // Delete all
ContentValues values = new ContentValues();
values.put("calendar_id", 1);
values.put("title", this.title);
values.put("allDay", this.allDay);
values.put("dtstart", this.dtstart.toMillis(false));
values.put("dtend", this.dtend.toMillis(false));
values.put("description", this.description);
values.put("eventLocation", this.eventLocation);
values.put("visibility", this.visibility);
values.put("hasAlarm", this.hasAlarm);
cr.insert(CALENDAR_URI, values);
So what I want is to delete only that entry that is put by me.
Deleting the event
Uri EVENTS_URI = Uri.parse("content://com.android.calendar/" + "events");
ContentResolver cr = c.getContentResolver();
deleteEvent(cr, EVENTS_URI, 1);
private void deleteEvent(ContentResolver resolver, Uri eventsUri, int calendarId) {
Cursor cursor;
cursor = resolver.query(eventsUri, new String[]{ "_id" }, "calendar_id=" + calendarId, null, null);
while(cursor.moveToNext()) {
long eventId = cursor.getLong(cursor.getColumnIndex("_id"));
resolver.delete(ContentUris.withAppendedId(eventsUri, eventId), null, null);
}
cursor.close();
}
After reading the data from the Calendar just try this out..
Adding a Single-Occurrence Event to a Calendar
To add an entry to a specific calendar, we need to configure a calendar entry to insert using the ContentValues as follows:
ContentValues event = new ContentValues();
Each event needs to be tied to a specific Calendar, so the first thing you're going to want to set is the identifier of the Calendar to insert this event into:
event.put("calendar_id", calId);
We then set some of the basic information about the event, including String fields such as the event title, description and location.
event.put("title", "Event Title");
event.put("description", "Event Desc");
event.put("eventLocation", "Event Location");
There are a number of different options for configuring the time and date of an event.
We can set the event start and end information as follows:
long startTime = START_TIME_MS;
long endTime = END_TIME_MS;
event.put("dtstart", startTime);
event.put("dtend", endTime);
If we are adding a birthday or holiday, we would set the entry to be an all day event:
event.put("allDay", 1); // 0 for false, 1 for true
This information is sufficient for most entries. However, there are a number of other useful calendar entry attributes.
For example, you can set the event status to tentative (0), confirmed (1) or canceled (2):
event.put("eventStatus", 1);
You can control who can see this event by setting its visibility to default (0), confidential (1), private (2), or public (3):
event.put("visibility", 0);
You can control whether an event consumes time (can have schedule conflicts) on the calendar by setting its transparency to opaque (0) or transparent (1).
event.put("transparency", 0);
You can control whether an event triggers a reminder alarm as follows:
event.put("hasAlarm", 1); // 0 for false, 1 for true
Once the calendar event is configured correctly, we're ready to use the ContentResolver to insert the new calendar entry into the appropriate Uri for calendar events:
Uri eventsUri = Uri.parse("content://calendar/events");
Uri url = getContentResolver().insert(eventsUri, event);
The call to the insert() method contacts the Calendar content provider and attempts to insert the entry into the appropriate user Calendar. If you navigate to the Calendar application and launch it, you should see your calendar entry in the appropriate Calendar. Since the Calendar syncs, you will also see the Calendar entry online, if you're using the Google Calendar on the web.
Delete the event
private int DeleteCalendarEntry(int entryID) {
int iNumRowsDeleted = 0;
Uri eventsUri = Uri.parse(getCalendarUriBase()+"events");
Uri eventUri = ContentUris.withAppendedId(eventsUri, entryID);
iNumRowsDeleted = getContentResolver().delete(eventUri, null, null);
Log.i(DEBUG_TAG, "Deleted " + iNumRowsDeleted + " calendar entry.");
return iNumRowsDeleted;
}
Also go through this link for deleting

Categories

Resources