如何在Android一段时间后开始活动?

时间:2015-03-02 10:05:42

标签: android android-activity

我正在开发和Android应用程序,我想启动另一个应用程序(我的第二个应用程序)。我正在做以下代码

 Intent i= new Intent();
 i.setComponent(new ComponentName("my second app package","my class name"));
 startActivity(i);

工作正常。

我希望在3或5秒后隐藏第二个应用程序,因为我遵循以下代码

 Timer t=new Timer();
            t.schedule(new TimerTask() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    Intent i = new Intent("first app package","first app class name" );
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
                }
            }, 5000);

但是这段代码不能正常工作,因为我只期待第二次申请。但其他应用程序运行正常。相反线程我也尝试过Handler,alaram经理也没有成功。请任何人帮助我。

我是否想在我的第二个应用程序中进行任何代码更改或我的代码有什么问题?

谢谢

6 个答案:

答案 0 :(得分:2)

   new Handler().postDelayed(new Runnable() {

                            @Override
                public void run() {
                        // your code to start second activity. Will wait for 3 seconds before calling this method

startActivity(new Intent(FirstActivityClass.this,SecondActivityClass.class));
                }
            }, 3000);

在onCreate of first activity

之后使用上面的代码

答案 1 :(得分:1)

尝试postDelayed或Timer方法

    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        //Do something after 100ms
     //Intent i = new Intent("first app package","first app class name" );
      Intent i = new Intent (this , SecondActivity.class);
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
      }
    }, 100);


// Time method 

import java.util.Timer;

...
Timer timer = new Timer();
timer.schedule(new TimerTask() {
  @Override
  public void run() {
    // Your database code here
  }
}, 2*60*1000);

答案 2 :(得分:0)

试试这个:

try{
    Thread.sleep(3000);
    startActivity(secondActivityIntent);
}catch(Exception e){
   //print error here
}

答案 3 :(得分:0)

您希望第二个应用程序在几秒钟后隐藏,请将此代码放在第二个应用程序主onCreate()的{​​{1}}内:

Activity

答案 4 :(得分:0)

你可以使用线程,但主要的是你必须调用finish()方法来完成当前的活动。

     Thread thread = new Thread( new Runnable() {
        @Override
        public void run() {
            try
            {
                   Thread.sleep(3000);

                }
                Intent intent = new Intent(1stActivity.this, SecondActivity.class);
                startActivity(intent);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            finally {
                finish();
            }
        }
    });

    thread.start();

在try块我把Thread.sleep(3000)你可以改变它在try块中做你的工作

答案 5 :(得分:0)

  handler.post(new Runnable() {

                @Override
                public void run() {
                    //Your Code here
                }

            });

将此代码放入计时器任务的run方法中。它将起作用。希望它会有所帮助。谢谢。