Android - 使用 postDelayed() 调用定期运行方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10845172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android - running a method periodically using postDelayed() call
提问by zolio
I have a situation in an Android app where I want to start a network activity (sending out some data) which should run every second. I achieve this as follows:
我在 Android 应用程序中遇到一种情况,我想启动一个每秒运行一次的网络活动(发送一些数据)。我实现如下:
In the onCreate()
I have the code:
在onCreate()
我有代码:
tv = new TextView(this);
tv.postDelayed(sendData, 1000);
The sendData()
function:
该sendData()
函数:
Handler handler = new Handler();
private Runnable sendData=new Runnable(){
public void run(){
try {
//prepare and send the data here..
handler.removeCallbacks(sendData);
handler.postDelayed(sendData, 1000);
}
catch (Exception e) {
e.printStackTrace();
}
}
};
The problem come in like this: When user presses the back buttons and app comes out (UI disappears) the sendData()
function still gets executed which is what I want. Now when user re-starts the app, my onCreate()
gets called again and I get sendData()
invoked twice a second. It goes on like that. Every time user comes out and starts again, one more sendData()
per second happens.
问题是这样出现的:当用户按下后退按钮并且应用程序出现(UI 消失)时,该sendData()
功能仍然会被执行,这正是我想要的。现在,当用户重新启动应用程序时,我onCreate()
再次被sendData()
调用并且每秒被调用两次。它一直这样。每次用户出来并再次启动时,sendData()
每秒都会发生一次。
What am I doing wrong? Is it my new Handler()
creating problem? What is the best way to handle this? I want one sendData()
call per second until user quits the app (form application manager).
我究竟做错了什么?是我的new Handler()
创作问题吗?处理这个问题的最佳方法是什么?我希望sendData()
每秒调用一次,直到用户退出应用程序(表单应用程序管理器)。
采纳答案by Vipul Shah
Why don't you create service and put logic in onCreate()
. In this case even if you press back button service will keep on executing. and once you enter into application it will not call
onCreate()
again. Rather it will call onStart()
为什么不创建服务并将逻辑放入onCreate()
. 在这种情况下,即使您按下后退按钮,服务也会继续执行。一旦您进入应用程序,它就不会onCreate()
再次调用
。而是会调用onStart()
回答by Saad Asad
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
Toast.makeText(c, "check", Toast.LENGTH_SHORT).show();
handler.postDelayed(this, 2000);
}
}, 1500);
回答by waqaslam
Perhaps involve the activity's life-cycle methods to achieve this:
也许涉及活动的生命周期方法来实现这一点:
Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler.post(sendData);
}
@Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(sendData);
}
private final Runnable sendData = new Runnable(){
public void run(){
try {
//prepare and send the data here..
handler.postDelayed(this, 1000);
}
catch (Exception e) {
e.printStackTrace();
}
}
};
In this approach, if you press back-keyon your activity or call finish();
, it will also stop the postDelayedcallings.
在这种方法中,如果您按Activity 或 call 的返回键finish();
,它也会停止postDelayed调用。
回答by Varun Chandran
You can simplify the code like this.
您可以像这样简化代码。
In Java:
在 Java 中:
new Handler().postDelayed (() -> {
//your code here
}, 1000);
In Kotlin:
在科特林:
Handler().postDelayed({
//your code here
}, 1000)
回答by sharma_kunal
Please check the below its working on my side in below code your handler will run after every 1 Second when you are on same activity
请在下面的代码中检查它在我这边的工作,当您进行相同的活动时,您的处理程序将每 1 秒运行一次
HandlerThread handlerThread = new HandlerThread("HandlerThread");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
runnable = new Runnable()
{
@Override
public void run()
{
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
回答by Dan Alboteanu
Handler h = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what==0){
// do stuff
h.removeMessages(0); // clear the handler for those messages with what = 0
h.sendEmptyMessageDelayed(0, 2000);
}
}
};
h.sendEmptyMessage(0);
回答by Tony
I think you could experiment with different activity flags, as it sounds like multiple instances.
我认为您可以尝试使用不同的活动标志,因为这听起来像是多个实例。
"singleTop" "singleTask" "singleInstance"
"singleTop" "singleTask" "singleInstance"
Are the ones I would try, they can be defined inside the manifest.
是我会尝试的那些,它们可以在清单中定义。
http://developer.android.com/guide/topics/manifest/activity-element.html
http://developer.android.com/guide/topics/manifest/activity-element.html
回答by Folee
You should set andrid:allowRetainTaskState="true"to Launch Activity in Manifest.xml. If this Activty is not Launch Activity. you should set android:launchMode="singleTask"at this activity
您应该在 Manifest.xml中将andrid:allowRetainTaskState="true" 设置为 Launch Activity。如果此活动不是启动活动。你应该在这个活动中设置android:launchMode="singleTask"