Question

I'm trying to use a service to make a regular call to my API. The asynchronous class I use to make external HTTP calls returns information to a handler which is passed in.

A simplified version below dies on the line where the Handler is instantiated (without a stack trace). Any idea why? Is there a better way I should be doing this?

package com.fred.services;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class NotificationService extends Service {

    private static final String TAG = "com.fred.services NotificationService";

    public long delay = 0;
    public long period_in_minutes = 10;
    public long period = 1000*60*period_in_minutes;

    private Timer timer = null;
    private TimerTask task = new TimerTask() {
        @Override
        public void run() {
            Handler h;
            Log.i(TAG, "now you see it");
            h = new Handler();
            Log.i(TAG, "now you don't");
        }
    };

    @Override
    public void onCreate(){
        super.onCreate();
        if (timer == null) startservice();
    }

    private void startservice() {
        if (timer == null) timer = new Timer();
        timer.scheduleAtFixedRate(task, delay, period);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

}
Was it helpful?

Solution

Is there a better way I should be doing this?

Use AlarmManager and an IntentService. This allows your code to stay out of memory except during the moments when it is actually adding value to the user (i.e., accessing your Web service).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top