仅在首次启动时显示活动

时间:2015-11-21 19:52:48

标签: android sharedpreferences startup

我有这个名为DataActivity的活动,我想让它在我第一次打开我的应用程序时出现,而不是再次出现。我希望我的MainActivity成为我的第一个活动,有人能告诉我我是怎么做到的吗? (我对编码很新,所以会感激一点代码......)谢谢! 亲切的问候! :)

2 个答案:

答案 0 :(得分:1)

尝试以下代码:

public class HelperActivity extends Activity {

    SharedPreferences prefs = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Perhaps set content view here

        prefs = getSharedPreferences("com.mycompany.myAppName", MODE_PRIVATE);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (prefs.getBoolean("firstrun", true)) {
            // Do first run stuff here then set 'firstrun' as false
            // start  DataActivity because its your app first run
            // using the following line to edit/commit prefs
            prefs.edit().putBoolean("firstrun", false).commit();
            startActivity(new Intent(HelperActivity.this , DataActivity.class));
            finish();
        }
        else {
        startActivity(new Intent(HelperActivity.this , MainActivity.class));
        finish();
        }
    }
}

此活动将帮助您确定是否首次运行应用程序并通过在sharedPreference中存储布尔值来启动相应的活动

将此活动设为您的启动器活动。

答案 1 :(得分:0)

您可以将条目保存到SharedPreferences,表示DataActivity已显示一次,然后在DataActivity onCreate()中您可以执行以下操作:

boolean dataShownOnce = checkSharedPreferencesForDataActivityShown();
if (dataShownOnce) {
    // Go to MainActivity
    startActivity(new Intent(this, MainActivity.class);
    finish();
} else {
    // Showing DataActivity for the first time, continue with the normal logic
}

这里有一个关于使用SharedPreferences的非常好的教程:http://developer.android.com/training/basics/data-storage/shared-preferences.html

相关问题