gpt4 book ai didi

java - 每次打开 Android 应用程序时显示 toast

转载 作者:行者123 更新时间:2023-12-01 22:03:05 25 4
gpt4 key购买 nike

我想在每次打开应用程序时显示欢迎 toast 。上面的代码可以工作,但每次屏幕旋转时它也会显示欢迎 toast 。

       protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(getApplicationContext(), "WELCOME!!!" , Toast.LENGTH_LONG).show();

有没有一种方法可以在每次打开应用程序时仅显示一次 toast ?

list :

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.im.gernan" >
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>
<application
android:name="com.example.im.gernan.MyAppCtx"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
>
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

最佳答案

正如评论中提到的,添加一个标志来指示它是否显示。其中一个地方可以是 Activity 本身,但 Activity 可以在应用程序处于 Activity 状态时完成并重新打开。应用程序上下文的生命周期只知道 onCreate 和 onDestroy 并保留洞应用程序 session ,这是为了让您的 toast 真正只在应用程序启动后出现。

示例:

这可能是一个应用程序上下文类,在 list 中引用为应用程序。

public MyAppCtx extends Application {
public boolean toasted = false;
}

然后在任何 Activity 中您都可以执行以下操作:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

...

if (!((MyAppCtx)getApplicationContext()).toasted) {
Toast.makeText(getApplicationContext(), "WELCOME!!!" , Toast.LENGTH_LONG).show();
((MyAppCtx)getApplicationContext()).toasted = true;
}

...
}

现在,当此 Activity 启动时,它会检查应用程序上下文是否表示欢迎。如果没有,它会显示并设置开关。就这样。玩得开心

关于java - 每次打开 Android 应用程序时显示 toast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33369560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com