Android 在应用程序启动时,使活动仅显示一次
我有以下类,SplashActivity.java:Android 在应用程序启动时,使活动仅显示一次,android,sharedpreferences,Android,Sharedpreferences,我有以下类,SplashActivity.java: public class SplashScreen extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentV
public class SplashScreen extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread timer = new Thread(){
public void run(){
try{
sleep(5000);
}catch(InterruptedException e)
{
e.printStackTrace();
}
finally{
Intent tutorial = new Intent(SplashScreen.this, TutorialOne.class);
startActivity(tutorial);
}
}
};
timer.start();
}
}
我希望此活动仅在应用首次安装到移动设备上时加载一次。作为android的新手,我对此一无所知。我在一些地方读到要使用SharedReferences
,但不理解实现。关于这个活动的一点是,当第一次使用这个活动时,它必须充当一个启动器
,这让我很困惑。因为在清单文件中,我声明了另一个活动,在我的例子中是MainPage.java
。那么我如何实现这个逻辑呢??我是否需要调用主页中的splash活动
,还是必须执行其他操作??请帮助别人
如果可能,有人可以写下实现此逻辑的代码吗?将此代码添加到onCreate方法中
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if(pref.getBoolean("activity_executed", false)){
Intent intent = new Intent(this, TutorialOne.class);
startActivity(intent);
finish();
} else {
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
}
除非您清除Android上设置的数据,否则每次执行应用程序时都会保留SharedReference。
第一次将从保存在此类首选项(ActivityPREF)上的布尔值(activity_executed)中获取值
如果没有找到任何值,它将返回false,因此我们必须编辑首选项并将值设置为true。
下一次执行将启动活动TutorialOne
finish()
关于您的清单,您可以将此活动设置为
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
每次执行应用程序时,都会启动此活动,但由于上设置了true,“activity\u executed”
将使用startActivity启动一个新活动
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if(pref.getBoolean("activity_executed", false)){
} else {
Intent intent = new Intent(this, TutorialOne.class);
startActivity(intent);
finish();
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
}
我想应该是这样 @Pragnani我想把它作为一次性的东西。。。比如,如果应用程序是第一次安装在移动设备上,那么启动屏幕就会显示出来。只有代码的答案通常是不被接受的。请尝试解释它的作用以及为什么它可以工作,以便OP和其他人可以从itI中学习。我把它与else分支混淆了,为什么在它已经为真时将变量设置为真?它不是真的,第一个条件检查SharedReferences中是否存在。默认情况下,第一次返回false,因此必须在else分支将其设置为true。下一次,第一个条件将返回true。