我有这个代码来自动启动我的服务,我认为AlarmON.class在alarmmanager等待60秒时运行但是没有。哪里出错?
当我重新启动时,我看到两个吐司:“服务已创建”和“服务已启动”。
感谢您的帮助!
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();
}};
答案 0 :(得分:0)
您无需致电
calendar.setTimeInMillis(System.currentTimeMillis());
由于...
Calendar calendar = Calendar.getInstance(); does the same thing.
这就像说给我当前时间然后将当前时间设置为当前时间。
还尝试将代码从onStart移动到onCreate,我已经看到Android不会调用onStart服务的问题。
根据您的评论我编辑了我的帖子。
您的清单中是否注册了AlarmON服务?例如,在应用程序部分:
<service
android:name=".AlarmON"
android:label="@string/service_name" >
</service>