服务和AlarmManager

时间:2013-10-11 10:33:57

标签: android service alarmmanager

这是我想要完成的事情并且严重失败。

我需要:

- 启动服务

- 做一些任务

- 设置AlarmManager以在一段时间后再次启动服务

- 停止服务

我遇到的问题是服务正在重新启动,几乎立即被停止。我想要的是服务应该在闹钟响起后启动..

以下是代码: -

 Intent intent = new Intent(ThisService.this,
                            ThisService.class);
    PendingIntent pendingIntent = PendingIntent.getService(ThisService.this, 0,
                                    intent, PendingIntent.FLAG_CANCEL_CURRENT);
    alarmManager.cancel(pendingIntent);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                            getUpdateTime(), getUpdateTime(), pendingIntent);
     stopSelf();

1 个答案:

答案 0 :(得分:1)

您缺少的是广播接收器

流程应为

  1. 开始服务。
  2. 创建BroadCast接收器
  3. 执行服务中的任务
  4. 设置闹钟以触发BroadCast Recievr(再次接收bradcast接收器启动服务。)
  5. 调用StopSelf会停止您的服务,可以从广播recievr
  6. 重新启动

    请参阅http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html


    //-----Set the alarm to trigger the broadcast reciver-----------------------------
     Intent intent = new Intent(this, MyBroadcastReceiver.class);
          PendingIntent pendingIntent = PendingIntent.getBroadcast(
            this.getApplicationContext(), 234324243, intent, 0);
          AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
          alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
            + (i * 1000), pendingIntent);
          Toast.makeText(this, "Alarm set in " + i + " seconds",
            Toast.LENGTH_LONG).show();
    
    //---------------Call StopSelf here--------------------
    
    //----------------------------------------------------------------------------------
    
    
    
    
    public class MyBroadcastReceiver  extends BroadcastReceiver {
         @Override
         public void onReceive(Context context, Intent intent) {
    
    //-----------write code to start the service--------------------------
         }
    
        }