我想使用AsyncTask创建启动画面。具体来说,在doInBackground()方法中,我使用静态方法Thread.sleep(),然后创建了一个intent,将app重定向到另一个activity。我没有收到任何错误,但该应用并没有改变活动。我的代码是:
/***This class redirects the user to the 'MainActivity'. ***/
class RedirectToMainActivityTask extends AsyncTask<Void, Void, Void>
{
protected Void doInBackground(Void... params)
{
try
{
Thread.sleep( 2 * 1000 );
}
catch ( InterruptedException e )
{
Log.e( "MAINACTIVITY-ERROR", e.getMessage());
showTheError( "Error while starting MainActivity: " + e.getMessage() );
}
Intent intent = new Intent( getApplicationContext(), MainActivity.class );
intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
startActivity( intent );
finish();
return null;
}
}
答案 0 :(得分:2)
您是否尝试过使用处理程序? :
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent( getApplicationContext(), MainActivity.class );
intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
startActivity( intent )
}
}, 2000); //time you want to wait until MainActivity start
答案 1 :(得分:1)
尝试将以下代码放在OnPostExecute()方法
中 Intent intent = new Intent( getApplicationContext(), MainActivity.class );
intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
startActivity( intent );
答案 2 :(得分:1)
确保您在清单中添加了活动
<activity android:name="com.example.listissue.SecondActivity"/>
也不要打电话给完()
private class RedirectToMainActivityTask extends AsyncTask<Void, Void, Void>
{
protected Void doInBackground(Void... params)
{
try
{
Thread.sleep( 2 * 1000 );
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result)
{
Intent intent = new Intent( getApplicationContext(), SecondActivity.class );
intent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
startActivity( intent );
}
}