2012-05-07 57 views
1

我正在开发一个应用程序,用户首先会在几天和时间内被呈现一个简单的用户界面。用户会选择每天的时间。并点击“完成”按钮。现在这将启动报警服务,按照选定的时间每天触发。 (并且会在这些时间点关闭/关闭蓝牙设备)。现在我每天都在使用单独的服务(初学者的本能)。该应用程序工作正常。现在我想要的是,当用户点击“完成”按钮时,应用程序应该继续在后台运行,并且当用户再次单击应用程序图标并单击“默认”按钮时,应该停止所有服务。我怎么能做到这一点?代码触发服务的每一个星期天是如下在同一个Android应用程序中的活动和服务

time interval of 7 x days for the alarm to repeat every 7 days 
    long interval = 1000 * 60 * 60 * 24 * 7; // to make the alarm repeat at every 7 days 

//getting values for hours, mins and AM/PM from the spinner boxes for sunday 
    index = sunHr.getSelectedItemPosition(); 
int sunHrInt = Integer.parseInt(hrList[index]); 


index = spinnerSunMin.getSelectedItemPosition(); 
int sunMinInt = Integer.parseInt(minList[index]); 

index = spinnerSunAmPm.getSelectedItemPosition(); 


    //conversion of time to 24 hrs format 
if (ampmList[index] == "AM") //(convert to 24 hr format) 
{ 
    if (sunHrInt == 12) 
    { 
     sunHrInt = 0; 
    } 
    else 
    { 
     if (sunHrInt != 12) 
     sunHrInt = sunHrInt + 12; 
    } 
} 

    //setting current calender 
    Calendar cur_cal = new GregorianCalendar(); 
     cur_cal.setTimeInMillis(System.currentTimeMillis());//set the current time and date for this calendar 
    //setting calender for sunday 
     Calendar calSun = new GregorianCalendar(); 
     calSun.add(Calendar.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR)); 
     calSun.set(Calendar.HOUR_OF_DAY, sunHrInt); 
     calSun.set(Calendar.MINUTE,sunMinInt); 
     calSun.set(Calendar.SECOND, 0); 
     calSun.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND)); 
     calSun.set(Calendar.DATE, cur_cal.get(Calendar.DATE)); 
     calSun.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH)); 

     //finding out when the sunday is to occur from today 

    days = 8 - calSun.get(Calendar.DAY_OF_WEEK); // how many days until Sunday 

     if (days >= 7) 
     { 
      days = days - 7; 
     } 

     calSun.add(Calendar.DATE, days); 

     //finally triggering the intent 
Intent myIntentSun = new Intent(AndroidAlarmService.this, SunOffAlarmService.class); 
      pendingIntentSun = PendingIntent.getService(AndroidAlarmService.this, 0, myIntentSun, 0); 
      AlarmManager alarmManagerSun = (AlarmManager)getSystemService(ALARM_SERVICE); 
      alarmManagerSun.set(AlarmManager.RTC_WAKEUP, calSun.getTimeInMillis(), pendingIntentSun); 
+0

你已经在做你想做的事了,就像你告诉你每天创建了一个UI和服务一样,你可以通过创建一个UI和一个服务来处理你的服务中的所有相关事件来简化它。使用偏好来存储用户的选择,并在设置的基础上,你可以让你的服务..这是什么问题? – Sandeep

+0

好的。让我解释问题在哪里。我正在模拟器上运行应用程序,检查服务是否在特定的日期和时间运行(通过显示Toasted味精作为模拟器不支持蓝牙,我可以关闭并查看)。现在我的问题是,当用户移动到家中或移动设备上的任何其他屏幕时,我的服务仍然会运行吗?如果是的话,为什么我需要偏好? – learner

+0

是的服务是后台进程,总是在后台运行,而用户使用其他东西的移动...和首选项需要存储用户设置,这是其他事情,这是不涉及服务功能... – Sandeep

回答

-2

使用首存储值和尝试。它可以帮助你

+0

你能让它更精致一点吗? – learner

相关问题