I am developing application that will sends birthday wishes automatically based on the birthday date with time registered by wisher. i have created a thread with infinite for loop that will get the records from Database for today's date to send message automatically for every minute automatically.
my code is running properly in normal activity. i want to place inside the SERVICE.so help me how to place this code and call the service when application starts.
this is my code
// function to run thread
void startThread()
{
Thread th=new Thread(){
@Override
public void run(){
//
try
{
for (;;)
{
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
//Getting the system date
Calendar today=new GregorianCalendar();
SimpleDateFormat simdate=new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat timeFormat=new SimpleDateFormat("hh:mm a");
String systemDate=simdate.format(today.getTime());
String systemTime=timeFormat.format(today.getTime());
// system process
minText.setText(systemTime);
control.open();
ArrayList<UserPOJO> event=control.MyDatabaseRecords(systemDate);//get the records for system date
for(int i=0;i<event.size();i++)
{
String dbContactID=event.get(i).getContactID();
String dbContactNumber=event.get(i).getContactNumber();
String dbContactMessage=event.get(i).getContactMessageBody();
String dbDate=event.get(i).getContactWishDate();
String dbTime=event.get(i).getContactWishTime();
String[] time=dbTime.split("[ \\:]");
String myhr=time[0];
String mymin=time[1];
String aorp=time[2];
String myDBhr=addZeroBeforeDate(myhr);
// adding zero before time hour
String CurrentDBTime=myDBhr+":"+mymin+" "+aorp;
Toast.makeText(getApplicationContext(),"Searching.....", 300).show();
//Toast.makeText(getApplicationContext(),"DB Time:"+CurrentDBTime+"System Time"+systemTime, 300).show();
if((dbDate.equals(systemDate))&& (CurrentDBTime.equals(systemTime)))
{//
System.out.println("Message Send at:"+systemTime);
Toast.makeText(getApplicationContext(),"Message Sent to :"+dbContactNumber+"on System time:"+systemTime, 300).show();
sendSMS(dbContactNumber, dbContactMessage);
//send.sendSMS(dbContactNumber, dbContactMessage);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
Thread.sleep(60000);
// Thread.sleep(20000);
// set the scan for 60 seconds
}
}
catch (InterruptedException e) {
}
} // run
};
th.start();
}
// Add zero if it is
dateval<10
private static String addZeroBeforeDate(String datevalue)
{
String dval=datevalue;
for(int i=dval.length();i<2;i++)
{
dval="0"+dval;
}
return dval;
}