0

I have an application installed in my device. I am trying to launch this application A from the buttonclick of another application B using the following code:

Button buttonStart = (Button)findViewById(R.id.buttonStart);
    buttonStart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setClassName("co.abc.android.test",
                    "co.abc.android.test.Abc");
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);

        }
    });

Following is my issue:

  • I launch application A

  • I press home button

  • From application B's button onclick, I launch app A again

  • Press return button to exit application A, which was now launched from app B
  • Eventhough I exit the application A on pressing return button, I am again taken to the main activity of app A, which I had launched initially.

On referring for this issue, I have read in many places that using Intent.FLAG_ACTIVITY_CLEAR_TOP would resolve this. But since I call app A's intent from a place in which I have no access to its context, it gives me the following error.

01-01 00:09:54.694: ERROR/AndroidRuntime(283): *** FATAL EXCEPTION IN SYSTEM PROCESS: WindowManagerPolicy
    android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
    at android.app.ContextImpl.startActivity(ContextImpl.java:884)
    at com.android.internal.policy.impl.LockScreen$DialerMethods.onTrigger(LockScreen.java:218)
    at com.android.internal.widget.multiwaveview.Dialer$2.run(Dialer.java:366)
    at android.os.Handler.handleCallback(Handler.java:605)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at com.android.server.wm.WindowManagerService$PolicyThread.run(WindowManagerService.java:752)

How can I resolve this issue, such that when I press the return button, I do not see the same activity(if launched before) again?

Any help is much appreciated.

4

2 回答 2

1

尝试添加内部onClick方法:

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
于 2012-07-03T13:17:16.453 回答
0

启动另一个应用程序的最佳方式是这样的:

Intent intent = new Intent();
intent.setClassName("co.abc.android.test", "co.abc.android.test.Abc");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(intent);

这模拟了当用户从可用应用程序列表中选择应用程序时 Android 所做的事情。

假设“co.abc.android.test.Abc”是该应用程序的根活动(即:带有 intent-filter 的活动ACTION_MAIN/CATEGORY_LAUNCHER),这将启动应用程序(如果它尚未运行)或只是带来应用程序从后台到前台(如果它已经在运行)。

于 2012-08-24T17:01:20.947 回答