使用警报管理器重复调用服务

时间:2014-02-10 10:53:40

标签: java android service android-alarms

我使用Alarm Manager调用服务,此服务需要每天执行一次。这工作正常,现在我需要检查系统是否已启动,然后我需要立即调用此服务。以下是我的警报代码。 (在第一次运行时,我为第二天设置警报,随后在执行后每天设置警报)

public void SetAlarm(Context context){
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 00);
        calendar.set(Calendar.MINUTE,00 ); // Particular minute
        calendar.set(Calendar.SECOND, 00);

        if(bootFlag != 1){

            Toast.makeText(context, "Boot flag in if is"+bootFlag, 1000).show(); 
            calendar.set(Calendar.DAY_OF_MONTH, (calendar.get(calendar.DAY_OF_MONTH)+1));
            AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
            Intent i = new Intent(context, Alarm.class);
            PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
            am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(), 1000*60*60*24, pi); 

        }

        if(bootFlag ==1){
            Toast.makeText(context, "Boot flag in if is"+bootFlag, 1000).show(); 
            AlarmManager amm=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
            Intent ii = new Intent(context, Alarm.class);
            PendingIntent pii = PendingIntent.getBroadcast(context, 0, ii, 0);
            amm.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(), 1000*60*60*24, pii); 
            System.out.println(x);
            Toast.makeText(context, "boot flag = 1 called "+x+" times", 1000).show(); 
            x++;
        } 
}

当我收到启动完成广播时,我将bootFlag设置为1,然后在我的服务中:

public int onStartCommand(Intent i, int flags , int startId){
        wakeLock = null;
        try{
            PowerManager mgr = (PowerManager)getApplicationContext().getSystemService(Context.POWER_SERVICE);
            wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
            wakeLock.acquire();
            alarm.bootFlagSet(0);
            alarm.SetAlarm(getApplicationContext());

            new Async().execute();
            stopService(new Intent(MyService.this, MyService.class));

        }catch(Exception e){
            System.out.println(e);

        }finally{

            if(wakeLock != null){
                wakeLock.release();
            }
        }

        return START_STICKY;
      }

下面是我的启动接收器:

@Override
public void onReceive(Context context, Intent intent) {

    if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
        Toast.makeText(context,"Boot Broadcast", 1000).show(); 

        alarm.bootFlagSet(1);
        alarm.SetAlarm(context);



    }
}

在我的服务中,我为第二天设置闹钟(理想情况下,如果没有靴子),但是如果设备启动则会一次又一次地调用。我哪里错了?

0 个答案:

没有答案