简体   繁体   中英

How to call startActivity method inside a Asynchronous function

I am trying out the android tutorial from their site and tried modifying the MainActivity to change to DisplayMessageActivity after it fetches a webpage.

The problem is I cant access the intent variable inside the callback nor can I define it their (I am new to android and Java).

Here's what I am trying to do: gist

I am using this library. If I leave out all the intent related code the url is fetched. Can anyone explain why this is not working or point me to right direction ? I have tried to do with with the defaultHTTPClient but cant even seem to fetch the page with that.

You need a context from which you generate and start the new Intent.

I guess your AsyncTask gets created by an Activity or Service. During the construction pass a reference of the Activity or Service to the AsyncTask and store it there in a member variable.

At the point where you want to start the new Activity use the reference to the Activity or Service to create the Intent and start the Activity. Just make sure you do all that in a Runnable that you pass to Activity.runOnUIThread(Runnable), because depending on the VM of the android device you might or might not be able to create an Activity from any other thread than the UIThread, while it will always be possible from the UIThread.

Good Luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM