我正在开发应用程序,它将根据生日期和wisher注册的时间自动发送生日祝福。 我创建了一个带有无限for循环的线程,它将从今天的数据库中获取记录,自动为每分钟自动发送消息。
我的代码在正常活动中正常运行。我想放在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;
}
答案 0 :(得分:3)
您应该使用IntentService和AlarmManager定期致电服务:
在另一个线程中调用IntentService的onHandleIntent()
方法,因此您不必担心阻止UI。
AlarmManager
也应该比TimerTask
更有效率。 (见Timer Task VS Alarm Manager usage in Android Service)
public class MyService extends IntentService {
private AlarmManager alarmManager;
private boolean started;
private PendingIntent pendingIntent;
public MyService() {
super(MyService.class.getSimpleName());
}
@Override
public void onCreate() {
super.onCreate();
alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
}
@Override
protected void onHandleIntent(Intent intent) {
if (! started) {
started = true;
// Call the service periodically every 15 minutes
pendingIntent = PendingIntent.getService(
getApplicationContext(),
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(
AlarmManager.ELAPSED_REALTIME,
AlarmManager.INTERVAL_FIFTEEN_MINUTES,
AlarmManager.INTERVAL_FIFTEEN_MINUTES,
pendingIntent);
}
// DO YOUR STUFF HERE
}
}
请查看AlarmManager documention以了解您可以使用的选项。
答案 1 :(得分:2)
首先在java中有一个名为Timer
的类,使用它。不要为在线程中运行的循环编写无穷无尽的东西,这是一种非常粘的处理方式,可能导致所有类型的问题。
我在Timer
中实施了Service
。您可以从尝试此代码开始。我建议你也看看android Alarm
类。
public class SomeService extends Service {
private static final String TAG = SomeService.class.getSimpleName();
private static final long UPDATE_INTERVAL = 1 * 15 * 1000;
private static final long DELAY_INTERVAL = 0;
private Timer timer;
public SomeService() {
}
public void onCreate() {
Log.d(TAG, "STARTING SERVICE");
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
timer.scheduleAtFixedRate(
new TimerTask() {
public void run() {
//DO YOUR CODE
}
},
DELAY_INTERVAL,
UPDATE_INTERVAL
);
super.onStartCommand(intent, flags, startId);
return 0;
}
@Override
public void onDestroy() {
timer.cancel();
super.onDestroy();
}
}
您可以从首发Service
startService(new Intent(this, NotificationService.class));
来启动Activity