我是Android新手。我已经使用处理程序在代码中运行计时器。我试图制作一个计时器,该计时器在时间小于零或为负数时调用新的意图。该程序给出了运行时错误。我在if条件下尝试使用0L。但是程序不起作用。如果我在if条件下使用0而不是0L,则timeToGo的值将继续减小为负。 Game.java没有错误,因为它具有默认的android页面。我认为在处理程序中有另一种调用意图的方法。请帮助解决此问题。谢谢
activity_main文件如下
package com.example.test;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tt1;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L,timeToGo=0L,startTime=0L;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tt1=(TextView) findViewById(R.id.textView1);
startTime=System.currentTimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
public Runnable updateTimerThread=new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
long timeNow = System.currentTimeMillis();
timeToGo = 30 - (timeNow - startTime) / 1000;
tt1=(TextView) findViewById(R.id.textView1);
tt1.setText(timeToGo+"");
if(timeToGo<0L){
Intent intent=new Intent(MainActivity.this,Game.class);
finish();
startActivity(intent);
}
customHandler.postDelayed(this, 0);
}
};
}
最佳答案
为此,您必须在应用程序的主线程上调用startActivity()。而不是来自后台线程。为此,请更改您的处理程序:
private Handler customHandler = new Handler(Looper.getMainLooper());