首页 > 解决方案 > onCreate() 中的无限循环

问题描述

我有以下代码:

应用程序A

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    Intent i = getIntent();
    if (i.hasExtra("Key")) {
        Intent i1 = new Intent();
        i1.putExtra("Key", someValue);
        i1.setComponent(new ComponentName("com.example.AppB", "com.example.AppB.MainActivity"));
        startActivity(i1);
        finishAffinity();
    }
}

应用程序B

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    // The following code executes only on a new install of the app
    Intent i = new Intent();
    i.putExtra("Key", "1");
    i.setComponent(new ComponentName("com.example.AppA", "com.example.AppA.MainActivity");
    starActivity(i);
    finishAffinity();
    
    // The following keeps executing in an endless loop
    Intent i1 = getIntent();
    if (i1.hasExtra("Key")) {
        long temp = i1.getLongExtra("Key", -1);
        recreate();
    }
}

一切正常(我成功地从 AppA 获得了值),除了上面注释的代码一直在无限循环中执行。我试图更改recreate()startActivity(getIntent())and finish(),但得到了相同的结果。

标签: javaandroidandroid-intent

解决方案


您是说以下代码仅在应用程序的新安装时执行,但是您是否对其进行了实际检查?根据我的这段代码片段,您似乎只是在两个应用程序之间来回传递数据,这就是您看到“无限循环”的原因。

如果不是这种情况,并且您实际上在启动任何一个应用程序之前进行了一些检查,我会在您使用removeExtra("Key").


推荐阅读