2012-12-12 79 views
0

我有这个代码来自动启动我的服务,我认为alarmon.class运行时,alarmmanager等待60秒,但没有它。错误在哪里?alarmmanager和服务

当我重新启动时,我看到两个烤面包:“服务创建”和“服务启动”。

感谢您的帮助!

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

我认为你必须调用super.onStart() – Guillaume

+0

super.onStart(); public void onStart(Intent intent,int startId){在eclipse中导致错误。另外添加:super.onStart(intent,startId);什么也没发生:-( –

回答

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> 
+0

了解。问题是:在60秒后,类AlarmON不会启动......它仅用于目的测试,接下来将编写一个代码,每天有2个闹钟时间。 –

+0

@PolHallen检查我的编辑上面的答案。 – logray