我正在开发应用程序,它将根据生日日期和许愿者注册的时间自动发送生日祝福。我创建了一个无限循环的线程,它将从数据库中获取今天日期的记录,以自动每分钟自动发送消息。
我的代码在正常活动中正常运行。我想放置在 SERVICE.so 中帮助我如何放置此代码并在应用程序启动时调用服务。
这是我的代码
// 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;
}