Set Alarm In Android From Excel Date Tutorial

This tutorial will tell to that how to read data from excel file and how to set alarm in android. To read date and time we are using excel file then we will set alarm at this date and time and we will learn how to show notification for this alarm. For this you need..

1. JExcelApi

For reading and writing we need a library. JExcelApi gives all the power of Microsoft Excel: workbooks, formulas, full spreadsheet control. Easy to mix Java logic and Excel capabilities.

2. Android Alarm Manager

Many a times we want some task to be performed at some later time in future. For Example: In SMS Scheduler we want a SMS to be send at some later time, or Task Reminder in which we want to be reminded about a task at a particular time, to implement all these things we use AlramManager class.

AlarmManager class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been
registered for it is broadcast or service by the system, automatically starting the target application if it is not already running.

3. Notification in Android

android.app.Notification.Builder is a builder class for Notification objects. Provides a convenient way
to set the various fields of a Notification and generate content views using the platform’s
notification layout template. If your app supports versions of Android as old as API level 4, you can
instead use NotificationCompat.Builder, available in the Android Support library.

Concepts

Reading Spreadsheets
JExcelApi can read an Excel spreadsheet from a file stored on the local filesystem or from some input
stream. The first step when reading a spreadsheet from a file or input stream is to create a
Workbook. The code fragment below illustrates creating a workbook from a file on the local
filesystem.
import java.io.File;
import java.util.Date;
import jxl.*;

Workbook workbook = Workbook.getWorkbook(new File(“myfile.xls”));
Once you have accessed the workbook, you can use this to access the individual sheets. These are
zero indexed – the first sheet being 0, the second sheet being 1, and so on.
Sheet sheet = workbook.getSheet(0);
Once you have a sheet, you can then start accessing the cells. You can retrieve the cell’s contents as
a string by using the convenience method getContents(). In the example code below, A1 is a text cell,
B2 is numerical value and C2 is a date. The contents of these cells may be accessed as follows
Cell a1 = sheet.getCell(0,0);
Cell b2 = sheet.getCell(1,1);
Cell c2 = sheet.getCell(2,1);
String stringa1 = a1.getContents();
String stringb2 = b2.getContents();
String stringc2 = c2.getContents();
// Do stuff with the strings etc

The demo programs CSV.java and XML.java use the convenience method getContents() in order to
output the spreadsheet contents.
When you have finished processing all the cells, use the close() method. This frees up any allocated
memory used when reading spreadsheets and is particularly important when reading large
spreadsheets.
// Finished – close the workbook and free up memory
workbook.close();

Setting alarm

To set the alarm we are using method “getSysytemService(ALARM_SERVICE)” of the class
AlarmManager.
To use the method we have create an instance “alarmManager” of the class AlarmManager.
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Set pendingIntent which will perform the assigned task will be invoked by Trigger.
Intent intent = new Intent(this,TaskNotify.class);PendingIntent pendingIntent = PendingIntent.getService(this.getApplicationContext(),
REQUEST_CODE,intent,0);
Setting time and task for alarm
alarmManager.set(AlarmManager.RTC_WAKEUP,TimeInMilliSec,pendingIntent);

Example:

Insert two file in your project
1. Date.xls in assets folder
image 1
2. Athan.mp3 in raw folder under res folder
image 2
And make sure you excel file data cells will be in same like
image 3

Whatever date and time you want you can enter but cell field will be same as above mention.

MainActivity.java

package com.example.excelandalarm;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import android.app.Activity;import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView text;
private List<Task> taskList;
private AlarmManager alarmManager;
public static final String EXTRA_ID = "id";
public static final int REQUEST_BROAD_CODE = 376650;
public static final int REQUEST_CODE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
if (TaskNotifyService.mp != null) {
TaskNotifyService.mp.release();
}
taskList = new ArrayList<Task>();
text = (TextView) findViewById(R.id.textview);
readDateFromExcel();
for (Task task : taskList) {setAlarm(task);
text.setText("Alarm is set");
}
}
private void readDateFromExcel() {
try {
Workbook workbook = Workbook.getWorkbook(getAssets().open(
"date.xls"));
Sheet sheet = workbook.getSheet(0);
for (int i = 1; i < sheet.getRows(); i++) {
Cell cell1 = sheet.getCell(1, i);
Cell cell2 = sheet.getCell(2, i);
String date = (cell1.getContents() + " " + cell2.getContents());
if (!date.trim().contentEquals("")) {
Task task = new Task();
task.setDate(date);
taskList.add(task);
}
}
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}public void setAlarm(Task task) {
Date date1 = new Date();
Date date2 = new Date(task.getDate());
if (date2.after(date1)) {
startAlert(task);
}
}
public void startAlert(Task task) {
Intent intent = new Intent(MainActivity.this, TaskNotifyService.class);
PendingIntent pendingIntent = PendingIntent.getService(
this.getApplicationContext(),
new Random().nextInt(REQUEST_BROAD_CODE), intent, 0);
Date date = new Date(task.getDate());
Calendar virtual = Calendar.getInstance();
virtual.set(Calendar.DATE, date.getDate());
virtual.set(Calendar.MONTH, date.getMonth());
virtual.set(Calendar.YEAR, date.getYear() + 1900);
virtual.set(Calendar.HOUR_OF_DAY, date.getHours());
virtual.set(Calendar.MINUTE, date.getMinutes());
virtual.set(Calendar.SECOND, 0);
virtual.set(Calendar.MILLISECOND, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, virtual.getTimeInMillis(),
pendingIntent);
}}

Task.java


package com.example. excelandalarm;
public class Task {
String title, date, note;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getNote() {
return note;
}
public void setNote(String note) {this.note = note;
}
}

TaskNotifyService.java

package com.example. excelandalarm;
import java.util.Random;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
public class TaskNotifyService extends Service {
public static MediaPlayer mp = new MediaPlayer();;
Runnable runnable;
Context c;
public static final int ID = 36589;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stubreturn null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
c = getBaseContext();
player();
sendNotification();
stopSelf();
return super.onStartCommand(intent, flags, startId);
}
public void sendNotification() {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(c)
.setSmallIcon(R.drawable.ic_launcher).setContentTitle("Alarm")
.setContentText("AYN SOFT");
Intent resultIntent = new Intent(c, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(c);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) c
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(new Random().nextInt(ID), mBuilder.build());
}
private void player() {
try {
if (mp != null) {
mp.release();
}
Vibrator vibrator = (Vibrator) c
.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
mp = MediaPlayer.create(c, R.raw.athan);
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
}

activity_main.xml

<RelativeLayout 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"
 tools:context=".MainActivity" > 
<TextView 
 android:id="@+id/textview"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"/>
</RelativeLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example. excelandalarm"
 android:versionCode="1"
 android:versionName="1.0" >
 <uses-sdk
 android:minSdkVersion="8"
 android:targetSdkVersion="17" />
 <uses-permission android:name="android.permission.VIBRATE" />
 <application
 android:allowBackup="true"
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name"
 android:theme="@style/AppTheme" >
 <activity
 android:name="com.example.tutorialproject.MainActivity"
 android:label="@string/app_name" >
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />
 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>
 <service android:name="com.example.tutorialproject.TaskNotifyService"/>
 </application>
</manifest>

image 4 Set Alarm In Android From Excel Date Tutorial

Related Posts

Leave a comment

Hey, so you decided to leave a comment! That's great. Just fill in the required fields and hit submit. Note that your comment will need to be reviewed before its published.