我有一个Date
数组,它在我的应用程序中的各个位置存储日期和时间,例如:
private Date m_DateTimeArray[];
m_DateTimeArray = new Date[Utilities.DATE_TIME_MAX_COUNT];
m_DateTimeArray[0] = 1-july-2012 12:30:00
m_DateTimeArray[1] = 1-july-2012 01:00:00
m_DateTimeArray[2] = 1-july-2012 02:30:00
m_DateTimeArray[3] = 1-july-2012 03:15:00
m_DateTimeArray[4] = 1-july-2012 04:20:00
m_DateTimeArray[5] = 1-july-2012 05:00:00
m_DateTimeArray[6] = 1-july-2012 06:30:00
现在我退出我的应用程序,所以现在在后台我想要的是,每当我的设备当前日期与存储在数组中的这个日期匹配时,它就会弹出一个包含一些信息的对话框,同样每当我的当前日期与数组中存储的下一个日期匹配时它再次弹出一个对话框。因此,无论我的应用程序是否处于运行状态,整个过程都应该运行。那么如何做到这一点。我经历了许多示例,例如AlarmManager
,IntetService
服务,但无法获得我想要的结果。因此,如果有人处理此类问题,请帮助我解决此问题。
我的主要活动代码
public class AndroidAlarmService extends Activity
{
private PendingIntent pendingIntent;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonStart = (Button)findViewById(R.id.startalarm);
Button buttonCancel = (Button)findViewById(R.id.cancelalarm);
buttonStart.setOnClickListener(new Button.OnClickListener()
{
@Override
public void onClick(View arg0)
{
Intent myIntent = new Intent(AndroidAlarmService.this, MyAlarmService.class);
pendingIntent = PendingIntent.getService(AndroidAlarmService.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 20);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(AndroidAlarmService.this, "Start Alarm", Toast.LENGTH_LONG).show();
}});
buttonCancel.setOnClickListener(new Button.OnClickListener()
{
@Override
public void onClick(View arg0)
{
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
// Tell the user about what we did.
Toast.makeText(AndroidAlarmService.this, "Cancel!", Toast.LENGTH_LONG).show();
}});
}
}
我的警报服务中的代码
public class MyAlarmService extends IntentService
{
public void onCreate()
{
super.onCreate();
}
public MyAlarmService()
{
super("MyAlarmService");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
super.onStartCommand(intent, startId, startId);
Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
protected void onHandleIntent(Intent intent)
{
Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();
}
}