0

我通过在android中使用处理程序创建了可运行任务的定期执行,但是我想在该定期任务执行中传递一个参数,我尝试了两种方法来传递一个参数,

1 - 通过在方法中声明一个类

void Foo(String str) {
    class OneShotTask implements Runnable {
        String str;
        OneShotTask(String s) { str = s; }
        public void run() {
            someFunc(str);
        }
    }
    Thread t = new Thread(new OneShotTask(str));
    t.start();
}

2 - 并将其放入一个函数中

String paramStr = "a parameter";
Runnable myRunnable = createRunnable(paramStr);

private Runnable createRunnable(final String paramStr){

    Runnable aRunnable = new Runnable(){
        public void run(){
            someFunc(paramStr);
        }
    };

    return aRunnable;

}

可以在带有参数的 Runnable 上找到上述 2 种方法的参考?

下面是我使用 1 方法的代码,但无论我使用 1 还是 2 方法,通过在周期性可运行任务中传递参数,仍然存在两个问题,

1 个问题 - 每次代码重复时,我的类中的计数器变量都会被覆盖。如果我在类和方法之外将这个计数器变量定义为全局变量而不是局部变量,那么它可以正常工作,但这不是我的要求。

2 问题 - 假设通过使用计数器变量作为全局变量解决了 1 问题,然后计数器在第一次执行后递增,在第二次执行时,它取消注册传感器,即 mSensorListener,但它无法使用此命令删除进一步的回调,

// Removes pending code execution
staticDetectionHandler.removeCallbacks(staticDetectionRunnableCode(null));

上面的这个命令也不能与 onPause 方法一起使用,它仍然会在这个命令执行后定期执行?我无法理解发生了什么,有人可以为此提供解决方案吗?下面是我的代码,

Runnable staticDetectionRunnableCode(String str){

    class staticDetectionRunnableClass implements Runnable{
        String str;
        private int counter = 0;

        staticDetectionRunnableClass(String str){
            this.str = str;
        }

        @Override
        public void run() {
            // Do something here
            Log.e("", "staticDetectinoHandler Called");

            Debug.out(str + " and value of " + counter);

            // Repeat this runnable code block again every 5 sec, hence periodic execution...
            staticDetectionHandler.postDelayed(staticDetectionRunnableCode(str), constants.delay_in_msec * 5);  // for 5 second

            if(counter >= 1){
                // Removes pending code execution
                staticDetectionHandler.removeCallbacks(staticDetectionRunnableCode(null));

                // unregister listener
                mSensorManager.unregisterListener(mSensorListener);
            }
            counter++;
        }
    }

    Thread t = new Thread(new staticDetectionRunnableClass(str));
    return t;
}
4

0 回答 0