当前位置: 代码迷 >> Android >> Android服务不以setInexactRepeating开头
  详细解决方案

Android服务不以setInexactRepeating开头

热度:125   发布时间:2023-08-04 12:33:42.0

我正在尝试创建一个服务,该服务每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();
}

}

我究竟做错了什么?

从经验上我发现,对于不精确和精确(19次之前都变得不精确)重复警报,最小时间似乎是30分钟左右。 即使这样,我仍然发现重复警报的时间是极其不可预测的。 例如,当我要求35分钟的时间时,我将以大约35分钟的间隔,相隔几个小时的间隔以及彼此之间几分钟的间隔得到一些警报。

我发现只需要发出一次警报,然后在每次触发警报时重新提交一个新警报,就可以预测得多了。

  相关解决方案