如何在每个应用程序启动时执行一次某些操作?

Mic*_*Bak 27 android auto-update android-3.0-honeycomb

我想在应用程序中实现更新检查程序,显然我只需要在启动应用程序时显示一次.如果我在onCreate()onStart()方法中进行调用,则每次创建活动时都会显示该调用,这不是一个可行的解决方案.

所以我的问题是:有没有办法做一些事情,比如检查更新,每个应用程序启动/启动一次?

对不起,如果有点难以理解,我很难在这个问题上解释自己.

Vit*_*kov 52

SharedPreferences对我来说似乎是丑陋的解决方案.当您将应用程序构造函数用于此类目的时,它会更加整洁.

您只需要使用自己的Application类,而不是默认类.

public class MyApp extends Application {

    public MyApp() {
        // this method fires only once per application start. 
        // getApplicationContext returns null here

        Log.i("main", "Constructor fired");
    }

    @Override
    public void onCreate() {
        super.onCreate();    

        // this method fires once as well as constructor 
        // but also application has context here

        Log.i("main", "onCreate fired"); 
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您应该在AndroidManifest.xml中将此类注册为您的应用程序类

<application android:label="@string/app_name" android:name=".MyApp"> <------- here
    <activity android:name="MyActivity"
              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>
Run Code Online (Sandbox Code Playgroud)

您甚至可以按"返回"按钮,因此应用程序转到后台,并且不会浪费您的处理器资源,只会浪费内存资源,然后您可以再次启动它,构建器仍然不会激活,因为应用程序尚未完成.

您可以在任务管理器中清除内存,因此将关闭所有应用程序,然后重新启动应用程序以确保再次触发初始化代码.


Yas*_*mar 5

看起来你可能必须做这样的事情

PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);

      int currentVersion = info.versionCode;
      this.versionName = info.versionName;
      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
      int lastVersion = prefs.getInt("version_code", 0);
      if (currentVersion > lastVersion) {
        prefs.edit().putInt("version_code", currentVersion).commit();
       //  do the activity that u would like to do once here.
   }
Run Code Online (Sandbox Code Playgroud)

您可以每次都执行此操作,以检查应用程序是否已升级,因此它仅运行一次以进行应用程序升级