简体   繁体   English

从Asynctask启动Activity

[英]start Activity from Asynctask

I know this question has been answered several times before and i have read most of them but i do not understand why they are not working for me. 我知道这个问题已经被回答了好几次了,我已经阅读了大多数,但是我不明白为什么他们对我不起作用。

I am building sort of a Webcrawler, therefore i have an Asynctask that parses the HTML code to my desired Variables in one class. 我正在构建某种Webcrawler,因此我有一个Asynctask,可将HTML代码解析为一个类中所需的变量。

I know want to start the Asynctask vie OnClick which is not the Problem, but i want to start a different Activity after the Asynctask has parsed the HTML Code. 我知道要启动Asynctask vie OnClick,这不是问题,但我想在Asynctask解析HTML代码后启动其他Activity。

Since it is an Asynctask i thought it would be best to start the Actitivty in the OnPostExecute of it. 由于它是一个Asynctask,所以我认为最好在它的OnPostExecute中启动Actitivty。

My code is very simple and basic but i dont know why i have problems with it. 我的代码非常简单和基本,但是我不知道为什么会有问题。

@Override
    protected void onPostExecute(String result){
        if(dialog.isShowing()){
            dialog.dismiss();
        }
        startActivity(new Intent(context, DetailView.class));
    }

the context is a variable in which i have the context of the MainActivity and that works perfectly fine for me at different points in the Asynctask to create a Toast. 上下文是一个变量,在其中我具有MainActivity的上下文,并且在Asynctask中创建Toast的不同点上对我来说工作正常。

DetailView.class is the Actitivity i want to start which works fine from the MainActivity but not at this place. DetailView.class是我要启动的Actitivity,可以从MainActivity正常工作,但不能在此位置工作。

The problem is that the Compiler tells me he expects android.app.Activity and the actual Argument is "new Intent(context, DetailView.class)" 问题是编译器告诉我他期望android.app.Activity,而实际参数是“ new Intent(context,DetailView.class)”

I am sorry for such a simple and already often answered Question but i dont know how to get it to work. 对于如此简单且已经经常回答的问题,我感到抱歉,但我不知道如何使它正常工作。

Thank you for any Answer. 谢谢您的回答。

Perfect Blackbelt, My outer class didnt extend Activity, that was the solution. 完美的黑带,我的外部类没有扩展Activity,这就是解决方案。 Thx 谢谢

You can't update UI on background thread. 您无法在后台线程上更新UI。 Showing toast and dialog is a way of update UI. 显示吐司和对话框是更新UI的一种方式。

You can publishProgress(...) in method doInBackground() and update UI in onProgressUpdate() 您可以在方法doInBackground()发布publishProgress(...) ,并在onProgressUpdate()更新UI。

Problem solved: 问题解决了:

context.startActivity(new Intent(context, DetailView.class));

This works now, but I don't know why. 现在可以使用,但是我不知道为什么。

There are lots of answers but I use this for my apps: 有很多答案,但是我将其用于我的应用程序:

Intent intent = new Intent(mContext, mainmenu.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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