无法使用处理程序

时间:2015-07-29 19:02:38

标签: android android-intent

我是android新手。我已经使用处理程序在我的代码中运行计时器。我试图制作一个计时器,当时间小于零或是否为负时调用新意图。该程序给出了运行时错误。如果有条件,我尝试使用0L。但程序不起作用。如果我在if条件下使用0而不是0L那么值timeToGo继续减少为负。 Game.java没有错误,因为它有默认的android页面。我认为在处理程序中调用intent有不同的方法。请帮忙解决这个问题。谢谢

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);
        }
    };

 }

1 个答案:

答案 0 :(得分:1)

为此,您必须在应用程序的主线程上调用startActivity()。而不是来自后台线程。为此,请更改处理程序:

  private  Handler customHandler = new Handler(Looper.getMainLooper());