Creating an object of Android Activity class

后端 未结 2 2013
臣服心动
臣服心动 2021-01-15 16:01

I have a class which extends Activity and I am trying to create an object of that class in a normal java class but it\'s throwing me an exception :

相关标签:
2条回答
  • 2021-01-15 16:21

    You should read up on the application fundamentals of android apps

    I cannot think of an example where you would need to create an activity object yourself. you should be using the Context.startActivity() call to start an activity.

    Anyways, to answer your question - an activity implements a message queue (using a Handler) where messages can be sent to the activity's running thread to perform certain tasks. That means the thread which executes Activity code stays around waiting for these messages (an example of these messages are the users' response to your applications UI). In order to do that you need to use a Looper thread which "loops" (or in a way waits) for messages to act on. The main thread for your application which also renders the UI for your application is a looper thread.

    If for some reason you are having the need to create an activity object manually then you should rethink how you are designing your application. Using startActivity is all that is required.

    0 讨论(0)
  • 2021-01-15 16:29

    The handler runs in whatever thread created it. So if you're not creating the instance of the new class in the UI thread then the handler isn't running in the UI thread and you will have a problem.

    I once tried to inflate GUIs in a separate thread for performance reasons. I didn't touch any Window at that point, but when inflating I got the same error message and I just ran Looper.prepare() in my Thread and all was well.

    A Looper runs the message loop of a thread. If you don't call Looper.prepare() (and then Looper.loop()) in a thread, that thread won't have a message loop, so can't have Handler objects that accept messages.

    0 讨论(0)
提交回复
热议问题