gpt4 book ai didi

android - 如何在应用程序启动时执行代码

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:14:16 26 4
gpt4 key购买 nike

我有一个小的 android 应用程序,我想在应用程序启动时执行一些代码。

我该怎么做?我是 Android 开发的新手。

最佳答案

我也遇到过类似的情况。我只需要执行一次方法,但 onCreate()onStart()onResume() 方法对我不起作用,因为那些当设备旋转时和在其他情况下调用方法。

所以我决定扩展 Application 并在我的自定义应用程序类的 onCreate() 中运行该方法,因为这每次应用程序启动只运行一次- up 并且因为任务不需要长时间运行

这是一个例子:

public class CustomApp extends Application {
public CustomApp() {
// This method fires only once per application start.
}

@Override
public void onCreate() {
super.onCreate();
// This method fires once as well as constructor
// & here we have application context

//Method calls
StaticClass.oneMethod(); // static method
Foo f = new Foo();
f.fooMethod(); // instance method
}
}

下一步是告诉 Android 我们有一个自定义的 Application 类。我们通过在 applcation 标签的“android:name”属性中引用自定义应用程序类来实现。像这样:

<manifest ...
<application
android:name="com.package.example.CustomApp">
<activity>
<!-- activity configuration-->
</activity>
...
<activity>
<!-- activity configuration-->
</activity>
</application>
</manifest>

...对于任何可能对您有帮助的人!

关于android - 如何在应用程序启动时执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9026917/

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