0

在我的应用程序中,我尝试设置一个超时函数,我无法 在单独的类中调用处理程序方法。

我的超时课程

 public class Timeout_function {

private Handler mHandler;
Activity activity;

public Timeout_function(Activity activity,Handler mHandler) {
    super();
    this.activity = activity;
    this.mHandler = mHandler;
}

Runnable myTask = new Runnable() {
    @Override
    public void run() {
        Toast.makeText(activity, "Test", 1000).show();
        mHandler.postDelayed(this, 1000);
    }
};

// just as an example, we'll start the task when the activity is started
public void onStart() {
    mHandler.postDelayed(myTask, 1000);
}

// at some point in your program you will probably want the handler to stop
// (in onStop is a good place)
public void onStop() {

    mHandler.removeCallbacks(myTask);
}
}

主类 在主类中我以这种方式调用该方法,但它在运行时显示错误,

Timeout_function timeout = new Timeout_function(this, mHandler);
    timeout.onStart();

如何调用主类中的方法。有人知道请帮我解决这个问题。

4

1 回答 1

0

为什么不使用Service而不是创建一个单独的类?

我会坚持你使用 Service 并onStartCommand()通过调用使用 Handler in of Service启动你的 RunnablestartService(intent);

您可以使用 Handler 将 Runnable 放在onDestroy()Service 的方法中并通过调用来停止 Runnable stopService(intent)

这就是我所做的,它就像一个魅力!

于 2013-04-30T08:02:19.183 回答