我有这段代码来自动启动我的服务,我认为当 alarmmanager 等待 60 秒时 AlarmON.class 运行,但不是。错误在哪里?
当我重新启动时,我看到了 toast:“服务已创建”和“服务已启动”。
谢谢您的帮助!
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 UnUsedService extends Service {
private PendingIntent pendingIntent;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
}
@Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(UnUsedService.this, AlarmON.class);
pendingIntent = PendingIntent.getService(UnUsedService.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 60);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(UnUsedService.this, "Start Alarm", Toast.LENGTH_LONG).show();
}};