2011年9月27日 星期二

[Android] Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag

Error Message

Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

(發生在 content provider 中開啟 activity 時?)


Solution

Android has 4 components: Activity, Service, ContentProvider and Broadcast.

When Android needs to activate one of this components from your application, it looks if there is already existing running process with your application.

If not, then Android starts new process, initializes it, then it initializes your custom Application instance. And then it activates one of needed components.



Now, let's consider next scenario:

your application declared content provider in AndroidManifest.xml, and Android just about to start your application so you can provide some data to another foreground application.
and Android just about to start your application so you can provide some data to another foreground application.
Content Provider request is sent

  1. Your application wasn't running, and Android starts new process for it.
  2. Your custom Application instance is created
  3. Application.onCreate() is called.
  4. You start an activity
  5. Your Content Provider receives request

Somebody just wanted to connect to your content provider, but your application started an Activity instead. Same true for starting background Service and sometimes broadcast receivers.

Activity entends Context, and Override startActivity(). 如果使用 activity 中的 startActivity(),不會有任何限制,而如果使用 Context 的 startActivity(),就必須是在另一個新的 task. (?)

That's because you need to start new task when Activity is started outside of Activity context. But I strongly recommend to not start Activity from your Application'sonCreate().

Because Android guarantees that Application will be created only once and before any other component


* Reference
- startActivity的requires new task异常解析 - Android - mobile - ITeye论坛
- Android Application vs Activity - Stack Overflow **

沒有留言:

張貼留言