I'm developing an Android 2.3.3 application and I need to run a method every X seconds.
我正在开发一个Android 2.3.3应用程序,我需要每隔X秒运行一个方法。
In iOS, I have NSTimer, but in Android I don't know what to use.
在iOS中,我有NSTimer,但在Android中我不知道该使用什么。
Someone have recommend me Handler; another recommend me AlarmManager but I don't know which method fits better with NSTimer.
有人推荐我Handler;另一个推荐我AlarmManager,但我不知道哪种方法更适合NSTimer。
This is the code I want to implement in Android:
这是我想在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
];
I need something what works like NSTimer.
我需要一些像NSTimer一样的东西。
What do you recommend me?
你有什么推荐我的?
5 个解决方案
#1
121
This really depends on how long apart you need to run the function.
这实际上取决于运行该功能需要多长时间。
If it is => 10 minutes → I would go with Alarm Manager.
如果=> 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();
}
And then you receive these broadcasts via broadcast receiver. Note that this will need to be registered ether in your application manifest or via context.registerReceiver(receiver,filter);
method For more information on Broadcast Receivers please refer to official Docs. Broadcast Receiver.
然后你通过广播接收器接收这些广播。请注意,这需要在应用程序清单中注册ether或通过context.registerReceiver(receiver,filter);方法有关广播接收器的更多信息,请参阅官方文档。广播接收器。
public class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent)
{
//do stuffs
}
}
If it is =< 10minutes → I would go with a Handler.
如果= <10分钟→我会使用Handler。
Handler handler = new Handler();
int delay = 1000; //milliseconds
handler.postDelayed(new Runnable(){
public void run(){
//do something
handler.postDelayed(this, delay);
}
}, delay);
#2
76
Use Timer for every second...
每秒使用Timer ......
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {}
}, 0, 1000);//put here time 1000 milliseconds=1 second
#3
27
try this code to call handler every 15 seconds and stop it when activity not visible
尝试此代码每15秒调用一次处理程序,并在活动不可见时停止它
Handler h = new Handler();
int delay = 15*1000; //1 second=1000 milisecond, 15*1000=15seconds
Runnable runnable;
@Override
protected void onResume() {
//start handler as activity become visible
h.postDelayed( runnable = new Runnable() {
public void run() {
//do something
h.postDelayed(runnable, delay);
}
}, delay);
super.onResume();
}
@Override
protected void onPause() {
h.removeCallbacks(runnable); //stop handler when activity not visible
super.onPause();
}
#4
7
If you are familiar with RxJava, you can use Observable.interval(), which is pretty neat.
如果您熟悉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
}
});
The downside of this is that you have to architect polling your data in a different way. However, there are a lot of benefits to the Reactive Programming way:
这样做的缺点是您必须以不同的方式构建轮询数据。但是,Reactive Programming方式有很多好处:
- Instead of controlling your data via a callback, you create a stream of data that you subscribe to. This separates the concern of "polling data" logic and "populating UI with your data" logic so that you do not mix your "data source" code and your UI code.
- 您可以创建您订阅的数据流,而不是通过回调控制数据。这就分散了“轮询数据”逻辑和“用数据填充UI”逻辑的关注,这样就不会混淆“数据源”代码和UI代码。
-
With RxAndroid, you can handle threads in just 2 lines of code.
使用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
Please check out RxJava. It has a high learning curve but it will make handling asynchronous calls in Android so much easier and cleaner.
请查看RxJava。它具有很高的学习曲线,但它将使处理Android中的异步调用变得更加容易和清晰。
#5
0
Here I used a thread in onCreate() an Activity repeatly, timer does not allow everything in some cases Thread is the solution
这里我在onCreate()和一个Activity中重复使用一个线程,在某些情况下,计时器不允许所有内容线程是解决方案
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();
In case it needed it can be stoped by
如果它需要它可以停止
@Override
protected void onDestroy() {
super.onDestroy();
Thread.interrupted();
//t.interrupted();
}
#1
121
This really depends on how long apart you need to run the function.
这实际上取决于运行该功能需要多长时间。
If it is => 10 minutes → I would go with Alarm Manager.
如果=> 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();
}
And then you receive these broadcasts via broadcast receiver. Note that this will need to be registered ether in your application manifest or via context.registerReceiver(receiver,filter);
method For more information on Broadcast Receivers please refer to official Docs. Broadcast Receiver.
然后你通过广播接收器接收这些广播。请注意,这需要在应用程序清单中注册ether或通过context.registerReceiver(receiver,filter);方法有关广播接收器的更多信息,请参阅官方文档。广播接收器。
public class MyReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent)
{
//do stuffs
}
}
If it is =< 10minutes → I would go with a Handler.
如果= <10分钟→我会使用Handler。
Handler handler = new Handler();
int delay = 1000; //milliseconds
handler.postDelayed(new Runnable(){
public void run(){
//do something
handler.postDelayed(this, delay);
}
}, delay);
#2
76
Use Timer for every second...
每秒使用Timer ......
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {}
}, 0, 1000);//put here time 1000 milliseconds=1 second
#3
27
try this code to call handler every 15 seconds and stop it when activity not visible
尝试此代码每15秒调用一次处理程序,并在活动不可见时停止它
Handler h = new Handler();
int delay = 15*1000; //1 second=1000 milisecond, 15*1000=15seconds
Runnable runnable;
@Override
protected void onResume() {
//start handler as activity become visible
h.postDelayed( runnable = new Runnable() {
public void run() {
//do something
h.postDelayed(runnable, delay);
}
}, delay);
super.onResume();
}
@Override
protected void onPause() {
h.removeCallbacks(runnable); //stop handler when activity not visible
super.onPause();
}
#4
7
If you are familiar with RxJava, you can use Observable.interval(), which is pretty neat.
如果您熟悉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
}
});
The downside of this is that you have to architect polling your data in a different way. However, there are a lot of benefits to the Reactive Programming way:
这样做的缺点是您必须以不同的方式构建轮询数据。但是,Reactive Programming方式有很多好处:
- Instead of controlling your data via a callback, you create a stream of data that you subscribe to. This separates the concern of "polling data" logic and "populating UI with your data" logic so that you do not mix your "data source" code and your UI code.
- 您可以创建您订阅的数据流,而不是通过回调控制数据。这就分散了“轮询数据”逻辑和“用数据填充UI”逻辑的关注,这样就不会混淆“数据源”代码和UI代码。
-
With RxAndroid, you can handle threads in just 2 lines of code.
使用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
Please check out RxJava. It has a high learning curve but it will make handling asynchronous calls in Android so much easier and cleaner.
请查看RxJava。它具有很高的学习曲线,但它将使处理Android中的异步调用变得更加容易和清晰。
#5
0
Here I used a thread in onCreate() an Activity repeatly, timer does not allow everything in some cases Thread is the solution
这里我在onCreate()和一个Activity中重复使用一个线程,在某些情况下,计时器不允许所有内容线程是解决方案
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();
In case it needed it can be stoped by
如果它需要它可以停止
@Override
protected void onDestroy() {
super.onDestroy();
Thread.interrupted();
//t.interrupted();
}