我正在开发一个 Android 应用程序,我想每 30 秒更新一次背景。
我使用了一个计时器,它可以工作,但只有一次!应用程序第二次崩溃。
public Timer mTimer = null;
public void loadColor()
{
setContentView(R.layout.color);
cur_scr = (LinearLayout) findViewById(R.id.colorScreen);
}
public void onClick(View v) throws InterruptedException
{
int id = v.getId();
switch (id)
{
case R.id.nextColor:
loadColor();
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
Random gen = new Random();
cur_scr.setBackgroundColor(Color.argb(255, gen.nextInt(256), gen.nextInt(256), gen.nextInt(256)));
}
}, 0, 2000);
break;
}
}
日志猫:
05-10 15:46:12.325: W/dalvikvm(346): threadid=9: thread exiting with uncaught exception (group=0x40015560)
05-10 15:46:12.344: E/AndroidRuntime(346): FATAL EXCEPTION: Timer-0
05-10 15:46:12.344: E/AndroidRuntime(346): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
05-10 15:46:12.344: E/AndroidRuntime(346): at android.view.ViewRoot.checkThread(ViewRoot.java:2932)
05-10 15:46:12.344: E/AndroidRuntime(346): at android.view.ViewRoot.invalidateChild(ViewRoot.java:642)
05-10 15:46:12.344: E/AndroidRuntime(346): at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:668)
05-10 15:46:12.344: E/AndroidRuntime(346): at android.view.ViewGroup.invalidateChild(ViewGroup.java:2511)
05-10 15:46:12.344: E/AndroidRuntime(346): at android.view.View.invalidate(View.java:5279)
05-10 15:46:12.344: E/AndroidRuntime(346): at android.view.View.setBackgroundDrawable(View.java:7626)
05-10 15:46:12.344: E/AndroidRuntime(346): at android.view.View.setBackgroundColor(View.java:7516)
05-10 15:46:12.344: E/AndroidRuntime(346): at com.haxad0x.tools.Core$1.run(Core.java:162)
05-10 15:46:12.344: E/AndroidRuntime(346): at java.util.Timer$TimerImpl.run(Timer.java:284)
05-10 15:46:14.194: D/AndroidRuntime(346): Shutting down VM
05-10 15:46:14.194: W/dalvikvm(346): threadid=1: thread exiting with uncaught exception (group=0x40015560)
05-10 15:46:14.194: I/Process(346): Sending signal. PID: 346 SIG: 9
请帮我!多谢你们!
case R.id.nextColor:
loadColor();
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
runOnUiThread(new Runnable()
{
public void run() {
Random gen = new Random();
cur_scr.setBackgroundColor(Color.argb(255, gen.nextInt(256), gen.nextInt(256), gen.nextInt(256)));
}
});
}
}, 0, 2000);
break;
代码以这种方式工作。我只有一个问题:它是一个长代码吗?我是说; 它会因为所有空隙而影响性能吗?我可以缩短它吗?