开发者

Android: Instantiate a Handler in a TimerTask within a Service

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();
            Lo开发者_如何学运维g.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;
    }

}


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜