如何每X秒运行一个方法

我正在开发一个Android 2.3.3应用程序,我需要每X秒运行一个方法。

在iOS中,我有NSTimer ,但在Android中,我不知道要使用什么。

有人推荐我Handler ; 另一个推荐我AlarmManager,但我不知道哪种方法更适合与NSTimer 。

这是我想在Android中实现的代码:

timer2 = [ NSTimer scheduledTimerWithTimeInterval:(1.0f/20.0f) target:self selector:@selector(loopTask) userInfo:nil repeats:YES ]; timer1 = [ NSTimer scheduledTimerWithTimeInterval:(1.0f/4.0f) target:self selector:@selector(isFree) userInfo:nil repeats:YES ]; 

我需要一些像NSTimer一样的东西。

你推荐我什么?

这实际上取决于你需要多长时间运行该function。

如果它是=> 10分钟→我会去与报警pipe理器。

 // Some time when you want to run Date when = new Date(System.currentTimeMillis()); try{ Intent someIntent = new Intent(someContext,MyReceiver.class); // intent to be launched // note this could be getActivity if you want to launch an activity PendingIntent pendingIntent = PendingIntent.getBroadcast( context, 0, // id, optional someIntent, // intent to launch PendingIntent.FLAG_CANCEL_CURRENT); // PendintIntent flag AlarmManager alarms = (AlarmManager) context.getSystemService( Context.ALARM_SERVICE); alarms.setRepeating(AlarmManager.RTC_WAKEUP, when.getTime(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent); }catch(Exception e){ e.printStackTrace(); } 

然后你通过广播接收器收到这些广播。 请注意,这将需要在您的应用程序清单或通过context.registerReceiver(receiver,filter);注册以太context.registerReceiver(receiver,filter); 方法有关广播接收机的更多信息,请参阅官方文档。 广播接收机 。

 public class MyReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { //do stuffs } } 

如果这是= <10分钟→我会去一个处理程序。

 Handler handler = new Handler(); int delay = 1000; //milliseconds handler.postDelayed(new Runnable(){ public void run(){ //do something handler.postDelayed(this, delay); } }, delay); 

每秒使用计时器…

 new Timer().scheduleAtFixedRate(new TimerTask() { @Override public void run() {} }, 0, 1000);//put here time 1000 milliseconds=1 second 

尝试这个代码每15秒调用一次处理程序,并在活动不可见时停止它

  Handler h = new Handler(); int delay = 15000; //15 seconds Runnable runnable; @Override protected void onResume() { //start handler as activity become visible h.postDelayed(new Runnable() { public void run() { //do something runnable=this; h.postDelayed(runnable, delay); } }, delay); super.onResume(); } @Override protected void onPause() { h.removeCallbacks(runnable); //stop handler when activity not visible super.onPause(); } 

如果你熟悉RxJava,你可以使用Observable.interval(),它非常简洁。

 Observable.interval(60, TimeUnits.SECONDS) .flatMap(new Function<Long, ObservableSource<String>>() { @Override public ObservableSource<String> apply(@NonNull Long aLong) throws Exception { return getDataObservable(); //Where you pull your data } }); 

这样做的缺点是你必须以不同的方式轮询你的数据。 但是,反应式编程方式有很多好处:

  1. 不要通过callback来控制数据,而是创build一个您订阅的数据stream。 这将“轮询数据”逻辑和“将数据填充到用户界面”的逻辑分开,这样就不会混淆“数据源”代码和UI代码。
  2. 使用RxAndroid,你可以在两行代码中处理线程。

     Observable.interval(60, TimeUnits.SECONDS) .flatMap(...) // polling data code .subscribeOn(Schedulers.newThread()) // poll data on a background thread .observeOn(AndroidSchedulers.mainThread()) // populate UI on main thread .subscribe(...); // your UI code 

请看看RxJava。 它有很高的学习曲线,但它会使Android中处理asynchronous调用变得更容易和更清晰。