我正在使用System.NanoTime来跟踪已用时间,但它不会在UI上更新。以下是我的代码:
然而,我正在使用onCreate()
方法做所有事情,我采取的方法可能不够强大,但这就是我想要更多想法的地方。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
long startTime = System.nanoTime();
// ... the code being measured ...
long estimatedTime = (System.nanoTime() - startTime) / 1000000000;
System.out.println(""+estimatedTime);
while (estimatedTime <= 100){
System.out.println(""+estimatedTime);
if(estimatedTime == 1){
TextView tx = (TextView)findViewById(R.id.textView);
tx.setText("Preparing");
}
if(estimatedTime == 2){
TextView tx = (TextView)findViewById(R.id.textView);
tx.setText("Inatializing");
}
if(estimatedTime == 3){
TextView tx = (TextView)findViewById(R.id.textView);
tx.setText("Preparing to install");
}
if(estimatedTime == 4){
TextView tx = (TextView)findViewById(R.id.textView);
tx.setText("Installing");
}
if(estimatedTime == 5){
TextView tx = (TextView)findViewById(R.id.textView);
tx.setText("Installed");
}
if(estimatedTime == 6){
TextView tx = (TextView)findViewById(R.id.textView);
tx.setText("Unzipping packages...");
}
estimatedTime = (System.nanoTime() - startTime) / 1000000000;
}
}
答案 0 :(得分:3)
也许你可以试试:
tx.postInvalidate();
其中tx是您的TextView对象
这一行之后:
estimatedTime = (System.nanoTime() - startTime) / 1000000000;
但是你应该将所有这些代码放在Thread下面。 例如:
new Thread(new Runnable() {
@Override
public void run() {
//your code here
}
}).start();
更新: 使用此更新主线程:
YourActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
//here set text into textView
}
});
答案 1 :(得分:1)
您无法在UI线程中执行此操作作为其阻止。您应该将其移动到AsyncTask。
答案 2 :(得分:1)
使用另一个线程并调用runOnUiThread方法并传递该线程的对象。如下所示
Thread th=new Thread(new Runnable() {
@Override
public void run() {
//put your code here
while (estimatedTime <= 100){
Thread.sleep(1000);
System.out.println(""+estimatedTime);
if(estimatedTime == 1){
TextView tx = (TextView)findViewById(R.id.textView);
tx.setText("Preparing");
}
if(estimatedTime == 2){
TextView tx = (TextView)findViewById(R.id.textView);
tx.setText("Inatializing");
}
if(estimatedTime == 3){
TextView tx = (TextView)findViewById(R.id.textView);
tx.setText("Preparing to install");
}
if(estimatedTime == 4){
TextView tx = (TextView)findViewById(R.id.textView);
tx.setText("Installing");
}
if(estimatedTime == 5){
TextView tx = (TextView)findViewById(R.id.textView);
tx.setText("Installed");
}
if(estimatedTime == 6){
TextView tx = (TextView)findViewById(R.id.textView);
tx.setText("Unzipping packages...");
}
estimatedTime = (System.nanoTime() - startTime) / 1000000000;
}
});
runOnUiThread(TH);
答案 3 :(得分:1)
最好使用Handler延迟某项任务......
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
public void Run(){
//Put your code here. Code will execute after 1000ms
}
}, 1000);