如何从Unity Activity调用以前的Android Activity

时间:2011-10-13 12:49:05

标签: android unity3d back-button

我的主要活动有一个启动UnityActivity的按钮。我需要完成UnityActivity并返回之前的活动。按下后退按钮时,它会关闭整个应用程序。

我该怎么办?谢谢!

修改

我使用Qualcomm增强现实(Unity Extension)中的AR播放器。 我只有一项主要活动是从Qualcomm增强现实中启动AR播放器。

主要活动

public class Main extends Activity {
/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void onBtnStartClick(final View v) {
        Intent i= new Intent(this,ArPart.class);
        startActivity(i);
    }
}

AR播放器活动

public class ArPart extends QCARPlayerActivity {
/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
             finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}

3 个答案:

答案 0 :(得分:4)

我发现使用被覆盖的onBackPressed()最容易,但要做到这一点,您还必须在Unity项目中进行更改:

void Update ()
{
    if (Input.GetKeyUp (KeyCode.Escape)) {

        AndroidJavaClass jc = new AndroidJavaClass ("com.unity3d.player.UnityPlayer"); 
        AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject> ("currentActivity"); 
        jo.Call ("onBackPressed");
    }
}

然后,在您的活动类中:

@Override
public void onBackPressed() {

    // Handle the activity however you want,
    // what you do here will be executed when the back button is pressed
}

此外,请记住,为了使其按预期工作,UnityPlayer对象无法暂停 - 您应该在处理后退按钮事件后暂停它。

从这个帖子中获得@Frank Nguyen的信用:Can't pass back event from Unity to android library jar

答案 1 :(得分:0)

使用以下代码

@Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        //super.onBackPressed();
        finish();
    }

答案 2 :(得分:0)

按照以下方式执行以下操作:

 Intent i=new Intent(unityActivity.this,mainActivity.class); // the names of activity as per you program.
    startActivity(i);
finish();