How to create a one-time welcome screen using Android preferences?

做~自己de王妃 提交于 2019-12-03 22:15:36

Try with Application version code. Below is an example code that I have used;

    SharedPreferences sharedPreferences = getSharedPreferences("version", 0);
    int savedVersionCode = sharedPreferences.getInt("VersionCode", 0);

    int appVershionCode = 0;

    try {
        appVershionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;

    } catch (NameNotFoundException nnfe) {
        Log.w(TAG, "$ Exception caz of appVershionCode : " + nnfe);
    }   

    if(savedVersionCode == appVershionCode){
        Log.d(TAG, "$$ savedVersionCode == appVershionCode");
    }else{
        Log.d(TAG, "$$ savedVersionCode != appVershionCode");

        SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
        sharedPreferencesEditor.putInt("VersionCode", appVershionCode);
        sharedPreferencesEditor.commit();

        Builder alertDialogBuilder = new Builder(this);
        alertDialogBuilder.setTitle("Version");
        alertDialogBuilder.setMessage("This is one time show dialog box ");

        alertDialogBuilder.setNeutralButton("Close", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.d(TAG, "$$ onClick");

            }
        });

        alertDialogBuilder.show();
    }

Instead of shared preference you can use below code also i have used this many times it will work perfectly it shows only one time when application start first time

public class SplashActivity extends Activity {
protected boolean _isActive = true;
protected int _splashTime = 3000; //SplashActivity will be visible for 2s
final String TAG = "SplashActivity";


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash_activity);



    //a separate thread to manage splash screen
    final Thread splashThread = new Thread() {

        public void run() {

            try {
                int wait = 0;

                while (_isActive && (_splashTime > wait)) { //will show only on the first time
                    sleep(100);

                    if (_isActive) {
                        wait += 100;
                    }
                }
            } catch (InterruptedException e) {
                Log.d(TAG, e.getMessage());

            } finally {
                startActivity(new Intent(SplashActivity.this, MainActivityAbs.class));
                finish();
            }
        }
    };
    splashThread.start();
}

//if a user clicks on a back btnOrder, do not show splash screen

public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        _isActive = false;
    }
    return true;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!