android轮询3秒执行一次,android – ScheduledThreadPoolExecutor用于定期任务(使用Retrofit)只需触发一次而不再重复...

我有以下代码用于每隔X秒从服务器轮询未读通知计数

我通过App.onCreate()中的ScheduledThreadPoolExecutor启动此过程

Log.d("XXX","Requesting Notification count from server ...");

被调用一次(我可以在Logcat中看到),但两个Retrofit回调函数都没有被调用(实际上没有Retrofit调试日志).更重要的是,“从服务器请求通知计数……”永远不会再次打印(即周期性任务没有运行)

我正在使用Retrofit进行其他webservice调用(在用户输入时)并且它们工作正常(我可以在logcat中看到传入和传出的请求/响应)

public class App extends Application {

private ScheduledExecutorService scheduleTaskExecutor;

...

@Override

public void onCreate() {

super.onCreate();

//region Set up the periodic notification count listener task

scheduleTaskExecutor= Executors.newScheduledThreadPool(2);

scheduleTaskExecutor.scheduleAtFixedRate(new PeriodicNotifCountFetchTask(),5,TimeUnit.SECONDS);

//endregion

}

class PeriodicNotifCountFetchTask implements Runnable {

@Override

public void run() {

Log.d("XXX","Requesting Notification count from server ...");

EMRestClient.getmEMRestService().getNotificationCount(new Callback() {

@Override

public void success(NotificationCount response,Response unused) {

int unreadNotifCount = response.getCount();

Log.d("XXX","Successfully fetched notification count,unread = " + response.getCount());

if (unreadNotifCount>0){

// call listener to repaint menu

for (NewNotificationListener x :notifListeners){

x.onNewNotificationReceived(response.getCount());

}

}

}

@Override

public void failure(RetrofitError error) {

Log.d("XXX","Failed to fetch notification count from server");

}

});

}

}

}

代码的改进部分在这里:

@POST("/notification/notification_count/")

void getNotificationCount(Callback callback);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值