如何运行的方法每X秒方法

2023-09-12 06:19:26 作者:奶味小仙女

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

I'm developing an Android 2.3.3 application and I need to run a method every X seconds.

在iOS系统中,我有NSTimer,但在Android中我使用的不是。

In iOS, I have NSTimer, but in Android I don't what to use.

有人有我推荐处理器;另一个建议我 AlarmManager ,但我不知道哪一种方法更适合的有NSTimer.

Someone have recommend me Handler; another recommend me AlarmManager but I don't know which method fits better with NSTimer.

这是在code我想在Android中实现:

This is the code I want to implement in 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.

你有什么建议我吗?

推荐答案

这真的取决于你需要运行的功能有多长开。

This really depends on how long apart you need to run the function.

如果是10分钟>我会去报警管理。

If it is 10minutes > i would go with Alarm Manager.

// some time when u 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(接收机,过滤器);有关广播接收器的详细信息,请参考官方文档。 广播接收器。

public class MyReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) 
    {
         //do w/e
    }
}

如果它为< 10分钟我会去同一个处理程序。

If it is < 10minutes i would go with a Handler.

Handler h = new Handler();
int delay = 1000; //milliseconds

h.postDelayed(new Runnable(){
    public void run(){
        //do something
        h.postDelayed(this, delay);
    }
}, delay);
 
精彩推荐
图片推荐