Android服务不以setInexactRepeating开头

时间:2014-03-08 12:27:58

标签: android android-service alarmmanager

我正在尝试创建一个永久性地每10秒递增一些变量的服务。为此,我使用setInexactRepeating在MainActivity的onCreate中启动它,但是从不创建服务......

public class MainActivity extends Activity {

    Mothership mothership;
    AlarmManager manager; 
    Calendar calendar;
    Intent i;
    PendingIntent pIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mothership = (Mothership) getApplicationContext();
        mothership.initTopBar((ImageView) findViewById(R.id.exposure_eye),(TextView) findViewById(R.id.energy_level), (TextView) findViewById(R.id.human_number));
        mothership.data.changeCurrentActivity(DynamicData.Main);

        manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        i = new Intent(MainActivity.this, TimerService.class);
        pIntent = PendingIntent.getService(this, 0, i, 0); // paramètres à analyser
        calendar = Calendar.getInstance();
        calendar.set(Calendar.SECOND, 10);

        // Service
        manager.cancel(pIntent);
        manager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, calendar.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES/90, pIntent);
}

TimerService只包含2条指令,用于调用变量时的顺序:

public class TimerService extends IntentService {

private final static String TAG = "TimerService";
Mothership mothership;

public TimerService() {
    super(TAG);
}

@Override
protected void onHandleIntent(Intent intent) {
    incEnergy();
    decStealth(); 
}

@Override
public void onCreate() {
    super.onCreate();
    mothership = (Mothership) getApplicationContext();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
    super.onDestroy();
}


public void incEnergy() {
    mothership.data.energyInc(); 
    mothership.topbar.update();
}

public void decStealth() {
    mothership.data.exposureDecrease(); 
    mothership.topbar.update();
}

}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我根据经验发现,对于不精确和精确(前19时全部变得不精确)重复警报,最短时间似乎是大约30分钟。即便如此,我发现重复警报的时机非常难以预测。例如,当我要求35分钟的时间段时,我会在大约35分钟的时间间隔内发出一些警报,相隔几个小时,有些警报在几分钟之内。

我发现只要求一次性警报就更容易预测,然后每次警报触发时重新提交一个新警报。