【问题标题】:Heavy optimization issues Android Java重度优化问题 Android Java
【发布时间】:2015-09-03 15:00:09
【问题描述】:

我知道这肯定是一个过于笼统的问题,但我开发的应用程序中有令人难以置信的延迟和“跳帧”,几乎无法使用。我不是要你浏览整个代码,但也许快速浏览一下可能会“点亮”更有经验的程序员,比如“哦,这就是为什么,在这里优化”

谢谢!如果问题太笼统和非法,我会删除它

编辑:感谢 Dean Wild,我发现了错误在哪里,但我不知道如何解决它

           LoginIstance.getIst().setLog(user.getText().toString(), password.getText().toString());
            HttpLogin connection = new HttpLogin(LoginIstance.getIst().getLog()[0],LoginIstance.getIst().getLog()[1]);

            connection.execute();
            while(connection.finish()){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {

                }
            }
            match = connection.getStringa();

看起来这是搞乱我的应用程序的部分。在做其他事情之前,我需要连接 AsyncTask 结束,但正如那个人所说,它冻结了我的 UI 线程。如何在不使用 thread.sleep 的情况下实现这一目标?

【问题讨论】:

标签: java android


【解决方案1】:

看一眼你的MainActivity我看到如下代码

                LoginIstance.getIst().setLog(user.getText().toString(), password.getText().toString());
                HttpLogin connection = new HttpLogin(LoginIstance.getIst().getLog()[0],LoginIstance.getIst().getLog()[1]);

                connection.execute();
                while(connection.finish()){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {

                    }
                }
                match = connection.getStringa();

您似乎正在使用connection.execute() 执行网络调用,我认为这是异步的(这是一件好事)。但是随后您将使用 Thread.sleep 运行一个 while 循环,直到网络操作完成。此代码在 UI 线程上运行,这些 Thread.sleep 调用将导致您的 UI 完全锁定。

您似乎对 Android 中的 UI 线程缺乏基本的了解,因此我怀疑您在整个代码库中都犯了这些错误。

尝试阅读this

为了记录,这个特定问题可以通过传递 connection.execute 某种接口回调来解决,该回调在操作完成后执行。

例子:

// create a callback interface
interface NetworkCallback {
    void onNetworkCallFinished();
}

// pass in your interface to the network call
HttpLogin connection = new HttpLogin("...", "...", new NetworkCallback(){
    void onNetworkCallFinished(){
        // now your data will be there
        match = connection.getStringa();
    }
});

connection.execute

// change your HttpLogin to take a reference to this callback
public HttpLogin(String s1,String s2, NetworkCallback callback){
    usr=s1;
    pss=s2;
    this.callback = callback;
}

// in your network call, override onPostExecute and notify the callback
@Override
protected void onPostExecute(String result) {
    callback.onNetworkCallFinished();
}  

【讨论】:

  • 您好!谢谢你的回答:) 是的,我在整个代码中都犯了这个错误,但我不确定你的意思。我应该将什么传递给异步网络操作?
  • 我无法在 onNetworkCallFinished 方法中访问连接本身
猜你喜欢
  • 2020-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多