【问题标题】:how to check whether the app running on the on the first time from the main activity如何从主活动中检查应用程序是否在第一次运行
【发布时间】:2017-04-24 13:48:01
【问题描述】:

我已经检查了我的应用程序是否第一次运行,如果应用程序是第一次运行,它应该转到另一个名为 Intro 的活动,我使用了以下代码并且它工作正常

     SharedPreferences preferences=  PreferenceManager.getDefaultSharedPreferences(this);
    if (!preferences.getBoolean("Time",false))
    {


        Intent intent=new Intent("com.hackerinside.jaisonjoseph.radioplanet.Intro");
        startActivity(intent);

        Toast.makeText(getApplicationContext(), "Welcome to Radio Planet ", Toast.LENGTH_LONG).show();
        SharedPreferences.Editor editor=preferences.edit();
        editor.putBoolean("Time",true);
        editor.commit();
    }

我担心的是当用户完成应用程序介绍时,它会转到我的主活动或主屏幕,我也想在那里做一些事情。我该怎么做?

【问题讨论】:

  • 写清楚意向词。你想在介绍之后打开一个新的 Activity 或者你想仔细检查什么?
  • 上面的代码会在应用第一次运行时执行介绍活动。完成介绍后,如何从主活动检查应用程序是否第一次运行?因为我想在完成介绍@AvinashAjayPandey 后从主要活动中展示另一件事
  • 我已添加代码供您检查。

标签: android android-activity sharedpreferences


【解决方案1】:

好的。您必须再次在 mainActivity 中编写相同的内容并检查相同的标签字段。 我将向您解释共享偏好。

将此类创建为外部类。

public class SessionManager {

    // LogCat tag
    private static String TAG = SessionManager.class.getSimpleName();
    // Shared Preferences
    SharedPreferences pref;

    SharedPreferences.Editor editor;
    Context _context;

    // Shared pref mode
    int PRIVATE_MODE = 0;

    // Shared preferences file name
    private static final String PREF_NAME = "PREF_NAME";

    private static final String KEY_IS_FIRSTTIME = "Time";


    public SessionManager(Context context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }


    public void setFirst(boolean isFirst) {

        editor.putBoolean(KEY_IS_FIRSTTIME, isFirst);
        editor.commit();    // commit changes
        Log.d(TAG, "User login session modified!");
    }

    public boolean getFirst() {
        return pref.getBoolean(KEY_IS_FIRSTTIME, false);

    }

}

然后在你的介绍活动中编写代码


 if (new SessionManager(this).getFirst)
    {

       //write code not a first time

      }else{
        Intent intent=new Intent("com.hackerinside.jaisonjoseph.radioplanet.Intro");
        startActivity(intent);

        Toast.makeText(getApplicationContext(), "Welcome to Radio Planet ", Toast.LENGTH_LONG).show();
        new SessionManager(this).setFirst(true);
    }
 with the same code you can check in mainActivity that it's first time or not.

【讨论】:

    【解决方案2】:

    从启动活动中删除editor.putBoolean("Time",true);,并在检查后在主活动中检查它,并将其值设置为true

    【讨论】:

    • 我没有收到您的问题,但现在您将在介绍活动和主要活动中检查偏好值两次,但您将在主要活动而不是介绍中将其值设置为 true
    • ok 从中删除 ( editor.putBoolean("Time",true); ) 并在您想再次检查的活动中再次使用相同的代码,但在此活动中添加 ( editor .putBoolean("Time",true); ) 进行检查后
    猜你喜欢
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 2016-03-29
    • 2018-07-17
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多