Here is my code:
这是我的代码:
public class MainActivity extends AppCompatActivity {
Runnable runnable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
runnable=new Runnable() {
@Override
public void run() {
Log.i("hello","runnable") ;
}
};
}
}
Why is it not printing log? Do I need a handler and then pass runnable object in it? Does run()
method runs only once?
为什么不打印日志?我需要一个处理程序,然后传递runnable对象吗? run()方法只运行一次吗?
1 个解决方案
#1
3
Currently you just define your runnable, but it will be never called. There are some ways how you can use a runnable e.g. in a thread or also in a Handler.
目前你只是定义了你的runnable,但它永远不会被调用。有一些方法可以使用runnable例如在线程中或在处理程序中。
Here is an example for a Thread where you cannot update the UI:
以下是无法更新UI的Thread示例:
new Thread(runnable).start();
If you need to update the UI you should use a Handler like this:
如果您需要更新UI,您应该使用这样的处理程序:
new Handler().post(runnable); // do as soon as possible
new Handler().postDelayed(runnable, 300); // do it after 300ms
Normally it doesn't make sense but you can use your runnable also as a kind of callback like this:
通常它没有意义,但你可以使用你的runnable作为一种回调,如下所示:
runnable.run();
A runnable can been used multiple times by using that three examples above multiple times.
通过多次使用上述三个示例,可以多次使用可运行的运行。
#1
3
Currently you just define your runnable, but it will be never called. There are some ways how you can use a runnable e.g. in a thread or also in a Handler.
目前你只是定义了你的runnable,但它永远不会被调用。有一些方法可以使用runnable例如在线程中或在处理程序中。
Here is an example for a Thread where you cannot update the UI:
以下是无法更新UI的Thread示例:
new Thread(runnable).start();
If you need to update the UI you should use a Handler like this:
如果您需要更新UI,您应该使用这样的处理程序:
new Handler().post(runnable); // do as soon as possible
new Handler().postDelayed(runnable, 300); // do it after 300ms
Normally it doesn't make sense but you can use your runnable also as a kind of callback like this:
通常它没有意义,但你可以使用你的runnable作为一种回调,如下所示:
runnable.run();
A runnable can been used multiple times by using that three examples above multiple times.
通过多次使用上述三个示例,可以多次使用可运行的运行。