危险混合启动+共享首选项

时间:2015-11-08 12:55:44

标签: android android-intent sharedpreferences splash-screen

我有一个Splash活动,其中通过意图我希望将用户重定向到不同的类,具体取决于它是否是第一次访问该应用程序。

除非真的很慢,否则会崩溃

public class MainActivity extends Activity {

    private long splashDelay = 1500;
    int counter;
    SharedPreferences app_preferences;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
        counter = app_preferences.getInt("counter", 1);
        System.out.println("count is..." +counter);

        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                finish();
                if(counter==1){
                    Intent in = new Intent(MainActivity.this, Attempt.class);
                    startActivity(in);
                }
                else{
                    Intent intent = new Intent().setClass(MainActivity.this, MainPage.class);
                    startActivity(intent);
                }
                SharedPreferences.Editor editor = app_preferences.edit();
                editor.putInt("counter", +(counter+1));
                editor.commit();
            }
        };

        Timer timer = new Timer();
        timer.schedule(task, splashDelay);
    }
}

基本上logcat一直在继续,红色波浪的顶部表示“执行停止未恢复的活动:{yo.laststage / yo.laststage.MainPage}”

1 个答案:

答案 0 :(得分:0)

我编码过多,简化了这一切。 如果有人感兴趣,我想要实现的是在MainActivity.class中有一个SPLASH页面,并检查它是否是第一次运行应用程序。 如果是,则应用程序会自动重定向到One.Class ELSE(又名它不是第一次),它会自动重定向到Two.Class。

不要忘记在Manifest中宣布您的活动

MainActivity.class:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    Thread timerThread = new Thread(){
        public void run(){
            try{
                sleep(3000);
            }catch(InterruptedException e){
                e.printStackTrace();
            }finally{

                Boolean isFirstRun = getSharedPreferences("PREFERENCES", MODE_PRIVATE).getBoolean("isfirstrun", true);
                if (isFirstRun){

                    Intent intent = new Intent(MainActivity.this, One.class);
                    startActivity(intent);

                    getSharedPreferences("PREFERENCES", MODE_PRIVATE).edit().putBoolean("isfirstrun", false).commit();
                }
                else{
                    Intent intent = new Intent(MainActivity.this,Two.class);
                    startActivity(intent);
                }

            }
        }
    };
    timerThread.start();




}

@Override
protected void onPause() {

    super.onPause();
    finish();
}
}
相关问题