应用有个需求,是定时去服务器获取一个账号是否有新的动态。
就像新浪微博那种,打开客户端,会自动提示有多少个 @ 。
我现在想到的方案是这样:
Timer timer = new Timer(); timer.scheduleAtFixedRate( new TimerTask() { public void run() { try { checkEvent(); Thread.sleep(1000); } catch (Exception ie) { } } }, 1000, 1000 * 30);
不知道还有没有别的更合理的方案
我这样做会不会有什么风险?
求有经验的大侠分享。。。
伊谢尔伦2017-04-17 11:05:19
public class RepeatTaskScheduler extends BroadcastReceiver {
public static final String ACTION = "com.yourcompanyname.appname.action.RepeatTaskSchedule";
@Override
public void onReceive(Context context, Intent intent) {
if (ACTION.equals(action)) {
checkEvent();
}
}
}
//在你想要的地方启动
public class YourActivity extends Activity{
@Override
public void onCreate() {
super.onCreate();
//如果interval的值太大会失效,几个小时没问题
setRepeatTasks(1000, 1000 * 30);
}
private void setRepeatTasks(long triggerTime, long interval) {
AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(RepeatTaskScheduler.ACTION);
//系统中如果有这个pendingIntent 取消
PendingIntent pending = PendingIntent.getBroadcast(this, 0, intent,
PendingIntent.FLAG_NO_CREATE);
if (pending != null) {
am.cancel(pending);
}
pending = PendingIntent.getBroadcast(this, 0, intent, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, triggerTime, interval, pending);
}
}
在AndroidManifest.xml中加入
<receiver android:name=".RepeatTaskScheduler">
<intent-filter>
<action android:name="com.yourcompanyname.appname.action.RepeatTaskSchedule" />
</intent-filter>
</receiver>
代码我没测试过,只介绍思路,有问题留言
伊谢尔伦2017-04-17 11:05:19
考虑用Handler吧
Handler handler; @Override public void onCreate(Bundle savedInstanceState) { // ... handler = new Handler() { @Override public void handleMessage(Message msg) { updateUI(); } }; Thread thread = new Thread() { @Override public void run() { while(true) { Message msg = new Message(); handler.sendMessage(msg); try { sleep(3*1000); // 3 seconds } catch (InterruptedException e) { } } } }; thread.start(); } private synchronized void updateUI() { // ... }