从asynctask类调用onPostExecute方法中的活动

时间:2017-04-22 10:50:42

标签: java php android

我在使用标题中的方法时遇到问题。 在我的Android应用程序项目中,当我从.php脚本收到成功的消息时,我想使用此方法启动新活动。从php脚本正确接收消息,但无论我尝试过什么,我都无法在onPostExecute方法上启动新活动。 这就是它看起来我的代码的方式,有经验的人可以看看它并告诉我,这有什么不对。 提前感谢您的时间。

public class BackGround extends AsyncTask<String, Void, String> {


    Context ctx;

  BackGround(Context  context)
    {
        this.ctx=context;
    }

    @Override
    protected String doInBackground(String... params) {
        String name = params[0];
        String password = params[1];

        String data = "";
        int tmp;

        try {
            URL url = new URL("http://webserver.xy/login_wellness.php");
            String urlParams = "email=" + name + "&password=" + password;

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setDoOutput(true);

            OutputStream os = httpURLConnection.getOutputStream();
            os.write(urlParams.getBytes());
            os.flush();
            os.close();
            InputStream is = httpURLConnection.getInputStream();
            while ((tmp = is.read()) != -1) {
                data += (char) tmp;
            }
            is.close();
            httpURLConnection.disconnect();

            return data;

        } catch (MalformedURLException e) {
            e.printStackTrace();
            return "Exception: " + e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            return "Exceptionn: " + e.getMessage();
        }

    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onPostExecute(String result) {       
    if(result.equals("success"))

    {
        Toast.makeText(ctx,"onpost excute",Toast.LENGTH_LONG).show();        
        Intent intent = new Intent(ctx,MainActivity.class);
       // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ctx.startActivity(intent);  
    }

    Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();
    }

}

2 个答案:

答案 0 :(得分:0)

将构造函数更改为

BackGround(Context  context)
{
    this.ctx=context.getApplicationContext();
}

然后

Intent intent = new Intent(ctx,MainActivity.class);
//intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(intent); 

希望这有帮助。

答案 1 :(得分:0)

如果您使用的是单独的类,则只需通过构造函数传递该类。

例如,

您的异步类:

您的构造函数:

    if(result.equals("success")) {
    Toast.makeText(ctx,"onpost excute",Toast.LENGTH_LONG).show();        
    Intent intent = new Intent(ctx,mIntentclass.class);
    ctx.startActivity(intent);  

}
   Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();
}

@覆盖         protected void onPostExecute(String result){

BackGround background = new BackGround(context,MainActivity);

您的需要课程

你只是打电话到你想要的地方?

{{1}}

希望对你有所帮助!