在计时器

时间:2017-02-24 09:42:43

标签: android android-activity timer android-service

所以我有这个代码,在具有10秒计时器的服务中有一个倒数计时器。我想要做的是在onFinish()方法中我想自动启动Activity(也称为MainActivity),即使我在应用程序之外。

public class TimeDisplayTimerTask extends TimerTask{
  CountDownTimer timer;

  NotificationCompat.Builder notification;
  private static final String TAG="com.timer";
  private Handler mHandler = new Handler();

  @Override
  public void run() {

    // run on another thread
    mHandler.post(new Runnable() {

      @Override
      public void run() {

          // display toast
         timer = new CountDownTimer(10000, 1000) {
           @Override
           public void onFinish(){

           }

           @Override
           public void onTick(long millisUntilFinished) {
             Log.i(TAG,"" + millisUntilFinished/1000);

           }
         };
         timer.start();
      }

    });

  }
}

4 个答案:

答案 0 :(得分:1)

尝试此操作以在10秒后打开您的主要活动。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
           // launch your main activity here and finish your current activity
        }
    }, 10000);
}

答案 1 :(得分:0)

可能你必须覆盖生命周期方法,并使用PARTIAL_WAKE_LOCK来保持cpu运行,直到你完成执行,以防用户锁定屏幕。

答案 2 :(得分:0)

如果您在服务中,那么只需使用intent启动您的活动。将此代码放在onFinish()方法中:

Intent i = new Intent();
i.setClass(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);

答案 3 :(得分:0)

您需要将活动上下文传递给TimeDisplayTimerTask:

public class TimeDisplayTimerTask extends TimerTask{
 CountDownTimer timer;

 NotificationCompat.Builder notification;
 private static final String TAG="com.timer";
 private Handler mHandler = new Handler();
private Activity mActivity;

public TimeDisplayTimerTask(Activity activity){
    mActivity = activity;
    super();
}

@Override
public void run() {

    // run on another thread
    mHandler.post(new Runnable() {

        @Override
        public void run() {

        // display toast
         timer = new CountDownTimer(10000, 1000) {
            @Override
            public void onFinish(){
                  if (activity != null {
                      Intent startIntent = new Intent(activity,  MainActivity.class);
                      startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        
                      activity.startActivity(startIntent);
                  }    
            }

            @Override
            public void onTick(long millisUntilFinished) {
                Log.i(TAG,"" + millisUntilFinished/1000);

            }

         };
         timer.start();
    }

});

}
}