如何运行的方法每X秒 [英] How to run a method every X seconds
问题描述
我开发一个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系统中,我有<一个href="https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/nstimer_Class/Reference/NSTimer.html">NSTimer,但在Android中我使用的不是。
In iOS, I have NSTimer, but in Android I don't what to use.
有人有我推荐处理器;另一个建议我 AlarmManager ,但我不知道哪一种方法更适合的有<一个href="https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/nstimer_Class/Reference/NSTimer.html">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
];
我需要的东西是什么样的作品<一href="https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/nstimer_Class/Reference/NSTimer.html">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
}
}
如果它为&lt; 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);
这篇关于如何运行的方法每X秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!