• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Alarm not repeating

croninberg

Newbie
Oct 24, 2016
35
5
I've looked at a number of solutions on here but I still can't seem to get the alarm to start a service every 30 seconds. 30 Seconds is only for testing. The alarm setting code is as follows,

Java:
ntent 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);

Basically I want the wearable to wake up and run a heart sensor service, which runs for 10 seconds then stops as follows by using selfStop() within the service.

Java:
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();
}

I really don't get why this doesn't work, as I literally copied the code from the Android tutorial Google have up.
 
Turns out I was never starting my service all along, so it was doing nothing when waking. I created this simple broadcast receiver to start the service at each interval. Countless hours wasted but a lesson learned.

Java:
public class HeartRateServiceStarter extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent service = new Intent(context, HeartRateService.class);
        context.startService(service);
    }
}
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones