【问题标题】:Unable to start different Activity from launcher-type Activity无法从启动器类型的 Activity 启动不同的 Activity
【发布时间】:2017-04-25 20:13:35
【问题描述】:

我遇到了一个有趣的问题:我有一个带有 Theme.NoDisplay(无 UI)的启动器类型的 Activity,它应该根据某些条件启动不同的 Activity,即使我正在调用 startActivity(),它也不会如果应用程序是通过启动器图标启动的,则不会启动其中任何一个(它确实启动了LauncherActivity,但随后没有错误/异常而死)。

但是

如果我通过 ADB 启动 LauncherActivity 或向 startActivity() 添加延迟,它似乎工作得很好。

这是一个代码 sn-p。

public class LauncherActivity extends Activity {

private Handler handler = new Handler();
private SharedPreferences preferences;

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

    preferences = getSharedPreferences(App.getContext().getString(R.string.preferences_name), MODE_PRIVATE);
    int pesel = preferences.getInt(App.getContext().getString(R.string.pref_pesel), 0);
    String password = preferences.getString(App.getContext().getString(R.string.pref_password), "");

    Intent intent;

    if (pesel != 0 && !password.isEmpty()) {
        // TODO: server-side password check
        intent = new Intent(this, MainActivity.class);
    } else {
        intent = new Intent(this, RegisterActivity.class);
    }

    Intent startIntent = getIntent();
    intent.setAction(startIntent.getAction());
    intent.setFlags(startIntent.getFlags());
    if (startIntent.getExtras() != null)
        intent.putExtras(startIntent.getExtras());

    final Intent readyIntent = intent;

    /*
    THIS DOENS"T WORK (WORKS IF STARTED VIA ADB THOUGH)
    */
    startActivity(readyIntent);

    /*
    THIS HOWEVER DOES WORK (ALWAYS)
    */
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            startActivity(readyIntent);
        }
    }, 5000);

    finish();
}

}

【问题讨论】:

  • 向我们展示您的清单?

标签: android android-activity activity-lifecycle


【解决方案1】:

其实我自己也找到了解决办法。

我在关注this blog post,解释为什么我们应该在onResume() 之前调用finish() Theme.NoDisplay 活动。

为了解决我的问题,我做了这样的事情,它似乎有效:

@Override
protected void onDestroy() {
    super.onDestroy();
    if (isFinishing() && intent != null) {
        startActivity(intent);
    }
}

很遗憾,我没有明确解释原因,但无论如何我都会把它留在这里,可能会对某人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-01
    • 2019-03-08
    • 2021-07-24
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多