-1

这就是我想要完成但严重失败的事情。

我需要:

-启动服务

- 做一些任务

-设置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();
4

1 回答 1

1

你缺少的是广播接收器

流量应该是

  1. 启动服务。
  2. 创建广播接收器
  3. 在服务中执行任务
  4. 设置警报触发广播接收器(在接收到广播接收器时再次启动服务。)
  5. 调用 StopSelf 它将停止您的服务,该服务可以从广播接收器重新启动

请参考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--------------------------
     }

    }
于 2013-10-11T11:28:51.310 回答