3

我有一个服务叫服务。如何让此服务在固定时间(例如上午 8:00)发出警报或启动祝酒词。

4

2 回答 2

1

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

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);
}
于 2013-09-28T01:14:17.000 回答
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();
}

}

于 2013-09-28T13:47:51.277 回答