我正在尝试使用服务来定期调用我的 API。我用来进行外部 HTTP 调用的异步类将信息返回给传入的处理程序。
下面的简化版本死在 Handler 被实例化的行(没有堆栈跟踪)。知道为什么吗?我应该这样做有更好的方法吗?
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;
}
}