2

我有一个在 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);
4

1 回答 1

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();

    }
 }

现在PendingIntentAlarm.

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

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

现在运行您的应用程序。而已。它肯定会在 9 点敬酒。

让我知道它是否有效。

于 2012-12-13T12:09:35.467 回答