我想以固定的时间间隔调用函数p(),我已经使用了scheduledatfixedrate方法。当我运行代码时,我得到“Viewroot从错误的线程异常中调用”,如日志中所示。我在函数调用中添加了onuithread实现来解决这个问题,但它没用。
package com.example.flipper;
import java.io.IOException;
import java.util.Date;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.WallpaperManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;
public class MainActivity extends Activity {
Button n,p,apply;
ImageView ivmain;
int imageId;
int i = 0;
TimerTask tt;
Timer t = new Timer();
TextView t1;
View v;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
n = (Button)findViewById(R.id.button1);
p = (Button)findViewById(R.id.button2);
apply = (Button)findViewById(R.id.button3);
ivmain = (ImageView)findViewById(R.id.imageView1);
ivmain.setImageResource(R.drawable.bangalorelogo);
t1 = (TextView)findViewById(R.id.textView1);
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
p();
}
});
}
public void p ()
{
tt = new TimerTask(){
public void run()
{
Random r = new Random();
i = r.nextInt(3);
switch(i)
{
case 0:
ivmain.setImageResource(R.drawable.chennailogo);
break;
case 1:
ivmain.setImageResource(R.drawable.ic_launcher);
break;
case 2:
ivmain.setImageResource(R.drawable.cscaptain);
break;
case 3:
ivmain.setImageResource(R.drawable.chennailogo1);
default:
ivmain.setImageResource(R.drawable.ic_launcher);
break;
}
t1.setText(""+i);
}
};
t.scheduleAtFixedRate(tt, 2000, 1000);
}
答案 0 :(得分:0)
您的方法p()正在UI线程上运行。但是,你的Timer“t”有它自己的线程,所以TimerTask“tt”没有在UI线程上执行;它正在TimerTask线程中执行。要解决这个问题,你可以在UI线程上运行p()并让你的TimerTask执行一个在UI线程上运行的Runnable:
tt = new TimerTask(){
public void run()
{new Runnable() { runOnUiThread(touchViews); } } }
然后将所有逻辑和视图操作放在Runnable“touchViews”中。