【问题标题】:Where to put Android application initialisation code?Android应用程序初始化代码放在哪里?
【发布时间】:2014-05-21 21:00:43
【问题描述】:

关于 Android 应用程序初始化的快速问题。 初始化任务通常放在主要活动的 onCreate/onResume 方法中。

现在的问题是,我不能保证主活动代码总是运行。

例如: 我的 MainActivity 带有一个通过使用意图触发 AnotherActivity 的按钮:

this.startActivity(new Intent(this, AnotherActivity.class)

现在假设用户点击了按钮,当用户向前导航到另一个应用程序或其他东西时,应用程序被置于后台。

一段时间后,由于操作系统资源策略,应用程序进程可能会被杀死。

当我返回应用程序时,进程会重新启动,但只有 AnotherActivity 被实例化并“运行”。所以跳过了初始化代码。

我认为 Application.onCreate 可能是一个不错的选择,但它不应该包含太多耗时的代码。

我接到了一个项目,其主要活动是 SplashActivity,它初始化一些核心应用程序组件,有时,在进程重新启动后,应用程序会因为这种行为而中断。

会发生这样的事情:

05-21 23:14:30.992 D/TESTAPP (22340): onCreate
05-21 23:14:31.002 D/TESTMAIN(22340): onCreate(null)
05-21 23:14:31.032 D/TESTMAIN(22340): onStart
05-21 23:14:31.032 D/TESTMAIN(22340): onResume
05-21 23:14:36.922 D/TESTMAIN(22340): onPause
05-21 23:14:36.932 D/TESTOTHER(22340): onCreate(null)
05-21 23:14:36.932 D/TESTOTHER(22340): Message: Hello World
05-21 23:14:36.952 D/TESTOTHER(22340): onStart
05-21 23:14:36.952 D/TESTOTHER(22340): onResume
05-21 23:14:37.342 D/TESTMAIN(22340): onSaveInstanceState
05-21 23:14:58.312 D/TESTOTHER(22340): onPause
05-21 23:14:58.812 D/TESTOTHER(22340): onSaveInstanceState
05-21 23:19:47.342 D/TESTAPP (24928): onCreate
05-21 23:19:47.342 D/TESTOTHER(24928): onCreate(not null)
05-21 23:19:47.342 D/TESTOTHER(24928): Message: null
05-21 23:19:47.392 D/TESTOTHER(24928): onStart
05-21 23:19:47.392 D/TESTOTHER(24928): onRestoreInstanceState
05-21 23:19:47.392 D/TESTOTHER(24928): onResume

TESTAPP 是应用程序的日志标记。 TESTMAIN 用于主要活动。 另一个从主活动按钮启动的 TESTOTHER

将应用程序置于后台后(见 23:14:58)我通过运行其他一些应用程序对操作系统施加了一些内存压力,几分钟后进程被杀死(我不确定进程是否由于内存问题或超时而被杀死)。

无论如何,我使用 adb shell 和 ps 命令来发现进程何时消失,然后导航回应用程序(参见 23:19:47)。没有 TESTMAIN 的踪迹。

主要活动只是将一些静态字符串设置为 Hello World。 该字符串被另一个活动消耗。随着进程重新启动,Hello World 消失了。

代码:

public class StaticContainer {
    public static String Message;
}

public class MyApplication extends Application {
    private static final String TAG = "TESTAPP";

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate");
        super.onCreate();
    }
}

public class MainActivity extends Activity {
    private static final String TAG = "TESTMAIN";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, String.format("onCreate(%s)", savedInstanceState == null ? "null" : "not null"));
        StaticContainer.Message = "Hello World";

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

    @Override
    public void onResume() {
        Log.d(TAG, "onResume");

        super.onResume();
    }

    @Override
    public void onPause() {
        Log.d(TAG, "onPause");

        super.onPause();
    }

    @Override
    public void onStart() {
        Log.d(TAG, "onStart");

        super.onStart();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        Log.d(TAG, "onSaveInstanceState");

        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        Log.d(TAG, "onRestoreInstanceState");

        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            Button other = (Button)rootView.findViewById(R.id.other);
            other.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), OtherActivity.class);
                    getActivity().startActivity(intent);
                }
            });

            return rootView;
        }
    }
}

public class OtherActivity extends Activity {
    private static final String TAG = "TESTOTHER";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, String.format("onCreate(%s)", savedInstanceState == null ? "null" : "not null"));
        Log.d(TAG, "Message: " + StaticContainer.Message);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other);

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
        }
    }
    ...the rest is the same as for the MainActivity (the only item missing is the button and its handler.

谢谢。

【问题讨论】:

  • 你能贴出你所指的代码吗?
  • 我刚做了。谢谢。
  • 代码或多或少是 Eclipse 模板项目 + 额外的日志记录 + 启动另一个活动的按钮。

标签: android process android-activity


【解决方案1】:

使用SharedPreferences 存储您想要设置以供其他活动使用的原始数据类型。这些值可以由您应用中的任何其他 Activity 检索,并且无论任何 Activity 被破坏,它们都保持可用。

例如,要在名为“app_values”的共享首选项中设置一个字符串值:

SharedPreferences sharedPreferences = getSharedPreferences("app_values", MODE_PRIVATE);
sharedPreferences.edit().putString("my_key_string", "Hello World").commit();

从名为“app_values”的共享首选项中检索该字符串值:

SharedPreferences sharedPreferences = getSharedPreferences("app_values", MODE_PRIVATE);
String myString = sharedPreferences.getString("my_key_string", "Default value if key not found");

【讨论】:

  • 是的,在某些情况下使用 SharedPreferences 可能是一种解决方案。但我使用简单的静态字符串属性仅用于演示目的。我的初始化代码更复杂,它涉及通过提供上下文、设置其他一些静态成员来初始化服务。它们中的大多数不能放入 SharedPreferences 中。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2017-09-07
  • 2016-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-25
  • 2018-12-01
相关资源
最近更新 更多