2017-04-24 115 views
-1

我检查了我的应用程序是否第一次运行,如果应用程序第一次运行,它应该转到另一个活动所谓的介绍,我已经使用了下面的代码,它工作正常如何检查第一次运行的应用程序是否从第一次运行主要活动

 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(); 
    } 

我担心的是,当用户完成应用程序的介绍,它会去我的主要活动或主屏幕,我想要做的一些东西,有也。我怎样才能做到这一点 ?

+0

写清楚故意字。你想在介绍后打开一个新的活动,或者你想仔细检查一下吗? –

+0

上面的代码会在第一次运行应用程序时执行介绍活动。在完成介绍之后,如何从主要活动中检查应用程序是否第一次运行?因为我想在完成介绍之后展示另一件主要活动@AvinashAjayPandey –

+0

我已经为您添加了代码检查它。 –

回答

0

没关系。您必须再次在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. 
0

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

+0

但两者都会执行相同的时间吗? –

+0

我没有得到您的问题,但现在您将在介绍活动和主要活动中检查两次首选项值,但是您将在主要活动中将其值设置为true,而不是介绍 – Badr

+0

我的第一个代码位于主要活动活动只有 –

相关问题