Android中固定时间的操作

时间:2013-09-27 19:40:47

标签: android action

我有一项名为service的服务。如何在固定时间(例如上午8:00)将此服务发出警报或发出祝酒词。

2 个答案:

答案 0 :(得分:1)

在您的服务中为Calendar实例对象设置适当的时间:

Calendar calendar = Calendar.getInstance();
int mYear = calendar.get(Calendar.YEAR);
int mMonth = calendar.get(Calendar.MONTH);
int mDay = calendar.get(Calendar.DAY_OF_MONTH);
int mHour = calendar.get(Calendar.HOUR_OF_DAY);

if(mHour >= 8)
    mDay++;

//set 8:00 a.m.
calendar.set(mYear, mMonth, mDay, 8, 0, 0);

然后使用AlarmManager来规划您的活动:

Intent intent = new Intent(MyService.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MyService.this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);

和你的AlarmReceiver类:

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
       Toast.makeText(context, "Alarm Receiver message", Toast.LENGTH_SHORT).show();
    }

请记住将BraodcastReceiver添加到您的清单文件中:

<receiver android:name=".receiver.AlarmReceiver"/>

编辑:覆盖onStartCommand方法

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    lanzarclase();
    return super.onStartCommand(intent, flags, startId);
}

答案 1 :(得分:0)

public class Servicio extends Service {
private static Context context; 
protected SmsObserver smsSentObserver=null;
public Handler handler;
public Handler handler1;
static String quien;
public static String sujeto, texto;
private static PendingIntent pendingIntent;
String que;
@Override

public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}


  @Override          
    public void onCreate() 
    {

        registersmsevent();
       lanzarclase();
    }

  private void lanzarclase() {       
      Calendar calendar = Calendar.getInstance();
      int mYear = calendar.get(Calendar.YEAR);
      int mMonth = calendar.get(Calendar.MONTH);
      int mDay = calendar.get(Calendar.DAY_OF_MONTH);
      int mHour = calendar.get(Calendar.HOUR_OF_DAY);

      if(mHour >= 9)
          mDay++;

      //set 8:00 a.m.
      calendar.set(mYear, mMonth, mDay, 9, 24, 0);


      Intent intent = new Intent(Servicio.this, AlarmReceiver.class);
      PendingIntent pendingIntent = PendingIntent.getBroadcast(Servicio.this, 0, intent, 0);
      AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
      alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);


  }

另一类是:

public class AlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
   Toast.makeText(context, "Mensaje de alarma recibida", Toast.LENGTH_SHORT).show();
}

}