0

我正在尝试使用计时器来刷新互联网上的图像。

这是我的代码:

public class ProjectActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    BannerActivity ba = new BannerActivity(this);
    LinearLayout layout = (LinearLayout)findViewById(R.id.main_layout);
    layout.addView(ba);
}

public class BannerActivity extends ImageButton implements OnClickListener{
    URL url = null;
    public BannerActivity(Context context) {
        super(context);
        setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 300));
        loadimage();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                loadimage();
            }   
            }, 5000, 1000);
    }

    private void loadimage(){
        try {
            url = new URL("http://3.bp.blogspot.com/_9UYLMDqrnnE/S4UgSrTt8LI/AAAAAAAADxI/drlWsmQ8HW0/s400/sachin_tendulkar_double_century.jpg");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        InputStream content = null;
        try {
            content = (InputStream)url.getContent();
        } catch (IOException e) {
            e.printStackTrace();
        }
        final Drawable d = Drawable.createFromStream(content , "src"); 
        setBackgroundDrawable(d);

        setOnClickListener(this);
    }

我得到的错误是这样的:

CalledFromWrongThreadException: Only the original thread that created a view
hierarchy can touch its views.

我是新手,不知道这意味着什么或如何解决它。

4

2 回答 2

1

您要从非 UI 线程中更改 UI,这在 Android 中是不可能的。Instaed od 调用此方法 setBackgroundDrawable(d); 在 Timer 的 run 方法中,将其包围在 runonUiThread() 中。

contextObj.runOnUiThread(new Runnable() {

        public void run() {
            // TODO Auto-generated method stub
            setBackgroundDrawable(d);
        }
    });

尝试获取您的活动的上下文,然后像这样更改您的 LoadImage(),

private void loadimage(){
    try {
        url = new URL("http://3.bp.blogspot.com/_9UYLMDqrnnE/S4UgSrTt8LI/AAAAAAAADxI/drlWsmQ8HW0/s400/sachin_tendulkar_double_century.jpg");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    InputStream content = null;
    try {
        content = (InputStream)url.getContent();
    } catch (IOException e) {
        e.printStackTrace();
    }
    final Drawable d = Drawable.createFromStream(content , "src"); 
    contextObj.runOnUiThread(new Runnable() {

        public void run() {
            // TODO Auto-generated method stub
            setBackgroundDrawable(d);
        }
    });


    setOnClickListener(this);
}
于 2012-06-18T09:21:45.217 回答
0

Activity 类是一个线程。如果您尝试在没有 Handler 的情况下在活动中创建线程,则会给出 ThreadException。因此,添加一个 Handler 来处理这个新线程。

谢谢

于 2012-06-18T09:22:53.110 回答