显示祝酒词(使用alarmmanager)

时间:2012-12-13 11:47:06

标签: android alarmmanager

我有一个在android启动后运行的服务。我想每天上午9点举杯祝酒。问题是:我如何实现代码(服务中的警报管理器)?

启动后启动服务:

public class AutoStart extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.example.startatboot.UnUsedService");
context.startService(serviceIntent);

}
}


public class Service extends Service {

@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}

@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);

Toast.makeText(UnUsedService.this, "Start Alarm", Toast.LENGTH_LONG).show();
}};

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);    AlarmManager am = (AlarmManager)     context.getSystemService  (Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context,     MyClass.class),      PendingIntent.FLAG_UPDATE_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),     AlarmManager.INTERVAL_DAY, pi);

1 个答案:

答案 0 :(得分:1)

只需用我的代码替换你的代码,

public class Service extends Service {

@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}

@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);

Toast.makeText(UnUsedService.this, "Start Alarm", Toast.LENGTH_LONG).show();
}};

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);    AlarmManager am = (AlarmManager)     context.getSystemService  (Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context,     AlarmReceiver.class),      PendingIntent.FLAG_UPDATE_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),     AlarmManager.INTERVAL_DAY, pi);

现在在同一个包中创建一个新类AlarmReceiver,并将以下代码添加到其中。

 public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();

    }
 }

现在在PendingIntent的{​​{1}}中定义它。

在清单文件中添加以下代码

Alarm

现在运行您的应用程序。而已。它绝对会在9点上祝酒。

让我知道它是否有效。