每X秒如何运行方法

问题描述 投票:100回答:8

我正在开发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这样的东西。

您向我推荐什么?

android timer nstimer
8个回答
152
投票

这实际上取决于您需要运行该功能多长时间。

如果是=> 10分钟→我将使用警报管理器。

// 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);方法注册以太坊。有关广播接收器的更多信息,请参阅官方文档。 Broadcast Receiver

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

92
投票

每秒使用计时器...

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

54
投票

[您可以尝试使用此代码每隔15秒通过onResume()调用处理程序,并在活动不可见时通过onPause()停止该处理程序。

Handler handler = new Handler();
Runnable runnable;
int delay = 15*1000; //Delay for 15 seconds.  One second = 1000 milliseconds.


@Override
protected void onResume() {
   //start handler as activity become visible

    handler.postDelayed( runnable = new Runnable() {
        public void run() {
            //do something

            handler.postDelayed(runnable, delay);
        }
    }, delay);

    super.onResume();
}

// If onPause() is not included the threads will double up when you 
// reload the activity 

@Override
protected void onPause() {
    handler.removeCallbacks(runnable); //stop handler when activity not visible
    super.onPause();
}

15
投票

如果您熟悉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. 而不是通过回调控制数据,而是创建您订阅的数据流。这将“轮询数据”逻辑和“用数据填充UI”逻辑的关注分开,这样您就不会将“数据源”代码和UI代码混在一起。
  2. 使用RxAndroid,您只需2行代码即可处理线程。

    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中处理异步调用变得更加轻松和整洁。


3
投票
    new CountDownTimer(120000, 1000) {

        public void onTick(long millisUntilFinished) {
            txtcounter.setText(" " + millisUntilFinished / 1000);

        }

        public void onFinish() {

            txtcounter.setText(" TimeOut  ");
            Main2Activity.ShowPayment = false;
            EventBus.getDefault().post("go-main");

        }

    }.start();

2
投票

这里我在活动的onCreate()中重复使用了一个线程,在某些情况下计时器不允许所有操作,线程是解决方案

     Thread t = new Thread() {
        @Override
        public void run() {
            while (!isInterrupted()) {
                try {
                    Thread.sleep(10000);  //1000ms = 1 sec
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            SharedPreferences mPrefs = getSharedPreferences("sam", MODE_PRIVATE);
                            Gson gson = new Gson();
                            String json = mPrefs.getString("chat_list", "");
                            GelenMesajlar model = gson.fromJson(json, GelenMesajlar.class);
                            String sam = "";

                            ChatAdapter adapter = new ChatAdapter(Chat.this, model.getData());
                            listview.setAdapter(adapter);
                           // listview.setStackFromBottom(true);
                          //  Util.showMessage(Chat.this,"Merhabalar");
                        }
                    });

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    t.start();

如果需要,可以通过]停止它>

@Override
protected void onDestroy() {
    super.onDestroy();
    Thread.interrupted();
    //t.interrupted();
}

0
投票

使用Kotlin,我们现在可以为此创建通用函数!


0
投票

Here可能对使用Rx Java

© www.soinside.com 2019 - 2024. All rights reserved.