在哪里放置Android应用程序初始化代码?

时间:2014-05-21 21:00:43

标签: android process android-activity

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

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

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

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

现在想象一下,当用户导航到另一个应用程序或其他东西时,用户点击了按钮并将应用程序置于后台。

过了一段时间,由于OS资源策略,应用程序进程可能会被杀死。

当我返回应用程序时,该过程重新启动,但只有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是Application的日志标记。 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.

谢谢。

1 个答案:

答案 0 :(得分:0)

使用SharedPreferences存储您要设置以供其他活动使用的主要数据类型。这些值可以通过您应用中的任何其他活动进行检索,并且无论是否有任何活动被破坏都可以使用。

例如,要在名为“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");