Android闹钟不重复

时间:2017-03-19 19:13:53

标签: android service alarmmanager

我已经在这里查看了许多解决方案,但我似乎仍然无法每30秒启动一次服务。 30秒仅用于测试。报警设置代码如下,

    Intent myIntent = new Intent(this, HeartRateService.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this,  0, myIntent, 0);

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.add(Calendar.SECOND, 7); // first time

    long frequency= 60 * 500; // in ms
    alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            (SystemClock.elapsedRealtime() + frequency),
            frequency, pendingIntent);

的manifest.xml

<service android:name=".heart_rate.HeartRateService"/>

我有一个心脏传感器服务,它在可穿戴设备上读取心率15秒,然后我使用stopSelf()停止它。我认为这可能是原因,但即使我把它拿出来,它仍然无效。

private void sendMessage(int heartRate, long dateTime) {
    Log.d(TAG, "sendMessage: ");
    PutDataMapRequest dataMap = PutDataMapRequest.create(WEARABLE_DATA_PATH);
    dataMap.getDataMap().putInt("reading", heartRate);
    dataMap.getDataMap().putLong("date_time", dateTime);
    dataMap.getDataMap().putInt("sensor_type", mHeartSensor.getType());
    PutDataRequest dataRequest = dataMap.asPutDataRequest();
    PendingResult<DataApi.DataItemResult> pendingResult =
            Wearable.DataApi.putDataItem(mGoogleApiClient, dataRequest);

    new HeartRateService.SendMessageToDataLayer(WEARABLE_DATA_PATH, dataRequest).start();

    stopSelf();
}

1 个答案:

答案 0 :(得分:0)

原来我一直都没有开始服务,所以醒来时什么也没做。我创建了这个简单的广播接收器,以便在每个间隔启动服务。浪费了无数个小时,但吸取了教训。

Kevs-MBP:bin kev$ python --version
Python 2.7.13