gpt4 book ai didi

java - 在不使用 Runnable 和 Timer 类的情况下定期调用方法

转载 作者:行者123 更新时间:2023-11-30 03:14:19 24 4
gpt4 key购买 nike

我想知道是否可以在不使用 Runnable 和 Timer 类的情况下定期调用方法。简而言之,如何在根本不创建新线程的情况下调用方法?谢谢。

最佳答案

I was wondering if it is possible to have a periodically call of a method, without using Runnable and Timer class

虽然您可以避免使用 Timer,但您将需要某些会定期触发的东西。

例如,您可以有一个确实有效的 Runnable,然后在任何 View(或 Handler) 安排自己在未来再次运行:

/***
Copyright (c) 2012 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.

From _The Busy Coder's Guide to Android Development_
http://commonsware.com/Android
*/

package com.commonsware.android.post;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class PostDelayedDemo extends Activity implements Runnable {
private static final int PERIOD=5000;
private View root=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
root=findViewById(android.R.id.content);
}

@Override
public void onResume() {
super.onResume();

run();
}

@Override
public void onPause() {
root.removeCallbacks(this);

super.onPause();
}

@Override
public void run() {
Toast.makeText(PostDelayedDemo.this, "Who-hoo!", Toast.LENGTH_SHORT)
.show();
root.postDelayed(this, PERIOD);
}
}

(来自 this sample project)

关于java - 在不使用 Runnable 和 Timer 类的情况下定期调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20403787/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com