0

I've 2 layouts: MainActivity.xml, MenuActivity.xml. I want to load the MenuActivity from AsyncTask of the 1-st. Here's the UPDATED code:

class InternetCheck extends AsyncTask<Activity, Void, Boolean> {
    public Activity act=new Activity();


    protected Boolean doInBackground(Activity... activities) {

        boolean status=false;

        act=activities[0];
        String rurl=act.getString(R.string.url_test);


        try 

        {

        URL url = new URL(rurl);

            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1000 * 20); // mTimeout is in seconds
                    urlc.connect();
            if (urlc.getResponseCode() == 200) {
                status=true;
            }

        }
            catch (MalformedURLException e1) {
                status=false;
            } 

            catch (IOException e) {
                status=false; 
            }

        return status;

    }


    protected void onPostExecute(Boolean result) {


        if (result==false) {
            MainActivity mActivity = (MainActivity) act;
            mActivity.ShowNoConnectionButton();
        }
        else
        {
            Intent intent = new Intent(act, MenuActivity.class);
            act.startActivity(intent);
            //setContentView(R.layout.menu_activity);

        };


    }


}

If result is false we show button from UI class, and if it's true, we must load the second activity. For startActivity(intent) I get error: the method is undefined for type InternetCheck. Also is it all right with Intent parameters and calling UI method ShowNoConnectionButton from AsyncTask? It's rather difficult to understand what we must put in Intent parameters and how to get these.

BUT IT STOPS THE APP WITH ERROR.

The second screen class:

public class MenuActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu_activity);

    }


}
4

1 回答 1

0

在您的 AsyncTask 类的构造函数中,您应该接受上下文(启动异步任务的活动实例)作为参数并将其保存在成员变量中,然后在 onPostExecute 中将其用作 context.startActivity()。

这意味着您应该为 AsyncTask 定义一个构造函数,而不是使用默认的无参数构造函数。

更新:看到你的完整代码后,我建议如下:

您不应自行构建活动。

class InternetCheck extends AsyncTask<Activity, Void, Boolean> {

    private MainActivity act;

    public InternetCheck(Activity activity) {
        this.act = (MainActivity)activity;
    }
...


protected void onPostExecute(Boolean result) {


        if (result==false) {
            act.ShowNoConnectionButton();
        }
        else
        {
            Intent intent = new Intent(act, MenuActivity.class);
            act.startActivity(intent);
        };

    }
...
}
于 2013-07-06T19:46:57.820 回答