从函数库中的异步回调

发布于 2024-12-29 18:44:45 字数 2169 浏览 1 评论 0原文

我正在编写我的第一个 Android 应用程序,这也是我对 Java 编程语言的介绍,因此我对一些非常基本的概念感到困惑。

我的计划是建立一个充满 php 函数的服务器,并将所有 php 调用放在一个静态函数库中。如果可以简化这个问题,我可以将该静态类更改为单例。

在一个 Activity 中,我进行以下调用:

phpCalls.VerifyAccount(userName, password);

在 phpCalls 静态类中,我得到以下代码:

    PHP_AsyncTask validateAccountTask = new PHP_AsyncTask();
    validateAccountTask.execute(new String[] {DOMAIN + PHP_confirm_account_exists, username, password});

抱歉

private static class PHP_AsyncTask extends AsyncTask<String, Void, String>{
    //This class should take the full URL of the php function to call and return the string result. Somehow.
    @Override
    protected String doInBackground(String... args)
    {
        String response = "";

        try
        {
            String url = args[0];
            String username = args[1];
            String password = args[2];
            URL validateURL = new URL(url);
            String credentials = "Basic " + new String(Base64.encode((username + ":" + password).getBytes(), Base64.NO_WRAP)) ;

            //TODO: handle 501 result
            HttpURLConnection conn = (HttpURLConnection)validateURL.openConnection();
            conn.setDoOutput(true);
            conn.setRequestProperty("Authorization",credentials);

            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;

            while ((line = reader.readLine()) != null)
            {
                response += line;
            }
            reader.close();
        }
        catch (IOException ioe)
        {
            ioe.printStackTrace();
        }

        return response;
    }


    @Override
    protected void onPostExecute(String result)
    {
        //have something happen when the php returns - need to pass the result somewhere
    }

,如果代码的格式不太理想 - 我不是 Stackoverflow 上的常规发布者。

无论如何,我试图确定如何最好地处理 php 调用的结果 - 它作为结果返回到 PHP_AsyncTask 类的 onPostExecute 函数,但我需要以某种方式将其传递回 UI 线程。显然,我无法在活动中创建指向函数的指针并将其传递给异步类。有没有办法在我的活动中创建一个侦听器并将其传递,以便我可以将 PHP_AsyncTask 的结果传递回我的活动?或者我完全找错了树——我应该追求一些更好的方法吗?

I'm putting together my first Android application, which is also my introduction to the Java programming language, and so I'm stumbling over what may be some very basic concepts.

My plan is to set up a server full of php functions and place all the php calls within a single static function library. I could change that static class to singleton if it simplifies this issue.

From within an activity, I'm making the following call:

phpCalls.VerifyAccount(userName, password);

and within the phpCalls static class, I've got the following code:

    PHP_AsyncTask validateAccountTask = new PHP_AsyncTask();
    validateAccountTask.execute(new String[] {DOMAIN + PHP_confirm_account_exists, username, password});

and

private static class PHP_AsyncTask extends AsyncTask<String, Void, String>{
    //This class should take the full URL of the php function to call and return the string result. Somehow.
    @Override
    protected String doInBackground(String... args)
    {
        String response = "";

        try
        {
            String url = args[0];
            String username = args[1];
            String password = args[2];
            URL validateURL = new URL(url);
            String credentials = "Basic " + new String(Base64.encode((username + ":" + password).getBytes(), Base64.NO_WRAP)) ;

            //TODO: handle 501 result
            HttpURLConnection conn = (HttpURLConnection)validateURL.openConnection();
            conn.setDoOutput(true);
            conn.setRequestProperty("Authorization",credentials);

            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;

            while ((line = reader.readLine()) != null)
            {
                response += line;
            }
            reader.close();
        }
        catch (IOException ioe)
        {
            ioe.printStackTrace();
        }

        return response;
    }


    @Override
    protected void onPostExecute(String result)
    {
        //have something happen when the php returns - need to pass the result somewhere
    }

Sorry if the formatting on the code is less than ideal - I'm not a regular poster on Stackoverflow.

Anyway, I'm trying to determine how best to handle the result from the php call - it's being returned to the onPostExecute function of the PHP_AsyncTask class as result, but I need to somehow pass it back to the UI thread. Apparently I can't create a pointer to a function within my activity and pass that through to the async class. Is there a way to create a listener within my activity and pass that along so that I can pass the result from PHP_AsyncTask back to my activity? Or am I completely barking up the wrong tree - is there some preferable approach which I should be pursuing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

も让我眼熟你 2025-01-05 18:44:45

1) onPostExecute is 在 UI 线程中

2) 您可以将指针传递给接口,而不是指向函数的指针。例如,如果您有这样的接口,

public interface Listener{
    public void someFunc(String response);
}

您可以将实现该接口的任何类作为参数传递。例如,如果您的方法是,

public void sendRequest(Listener listener);

您可以将您的类作为listener传递:

public class SomeClass implements Listener{
    public void someFunc(String response){
        //do stuff
    }
}

就像PS一样

sendRequest(new SomeClass());

,我在答案中没有使用AsyncTask,但我希望您能明白这一点

1) onPostExecute is in UI thread

2) Instead of pointer to function you can pass pointer to interface. For example, if you have have such interface

public interface Listener{
    public void someFunc(String response);
}

you can pass as parameter any class that implements that interface. For example if your method is

public void sendRequest(Listener listener);

you can pass as listener your class:

public class SomeClass implements Listener{
    public void someFunc(String response){
        //do stuff
    }
}

like that

sendRequest(new SomeClass());

PS I didn't use AsyncTask in my answer, but I hope you'll get the idea

匿名。 2025-01-05 18:44:45

所以我现在还没有办法对此进行测试,但这就是我要做的。

为侦听器创建一个接口

public interface MyListener {
    public void onDone(String response);
}

从活动中调用VerifyAccount,如下所示

phpCalls.VerifyAccount(userName,password, new MyListener() {
    @Override
    public void onDone(String response) {
        //do stuff
    }
});

然后更改 PHP_AsyncTask 的构造函数以接受一个参数,即您创建的接口。更改VerifyAccount 的方法签名以获取附加参数并将其传递到您创建的新PHP_AsyncTask 中。

private static class PHP_AsyncTask extends AsyncTask<String, Void, String>{ 
    private MyListener listener;
    public PHP_AsyncTask (MyListener listener) {
        this.listener = listener;
    }

   .....

   @Override
   protected void onPostExecute(String result)
   {
      listener.onDone(result);
   }
}

So I don't have anyway to test this out right now but here is what I would do.

Create an interface for the listener

public interface MyListener {
    public void onDone(String response);
}

From the activity call VerifyAccount like so

phpCalls.VerifyAccount(userName,password, new MyListener() {
    @Override
    public void onDone(String response) {
        //do stuff
    }
});

Then change the constructor for PHP_AsyncTask to take in one paramater, the interface you created. Change the method signature for VerifyAccount to take the additional parameter and pass it into the new PHP_AsyncTask you created.

private static class PHP_AsyncTask extends AsyncTask<String, Void, String>{ 
    private MyListener listener;
    public PHP_AsyncTask (MyListener listener) {
        this.listener = listener;
    }

   .....

   @Override
   protected void onPostExecute(String result)
   {
      listener.onDone(result);
   }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文