【问题标题】:Android code working slower than intendedAndroid 代码运行速度比预期慢
【发布时间】:2014-07-22 23:06:12
【问题描述】:

对不起,我的英语不好, 我正在为学校做一个项目,我必须使用 Android 应用程序通过 WiFi 移动车辆。我实现了我的目标,但我惊讶地发现,大多数时候当我按下任何按钮时,我的车辆都需要一些时间来实际做某事。另一方面,当我快速按下任何按钮几次时,事件会堆叠,之后,即使我没有按下任何按钮,车辆也会移动。不用说,两者都是几个问题。有什么办法可以修复它们吗? Android 应用程序通过 REST API 连接到 Arduino Yun。每次触摸一个按钮,我都会发出一个 HTTP 请求,以便将车辆向前、向后、向左或向右移动。 这是我的代码(尽管是西班牙语,但我认为这是可以理解的):

public class MainActivity extends Activity {
private Button  boton1,
                boton2,
                boton3,
                boton4;
private String  valor;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    configuracion();
}
public void configuracion(){
    StrictMode.ThreadPolicy policy = new StrictMode.
            ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
    establecerBotones();
    try{
    definir("continua/0/0");
    definir("direccion/0/0");
    }
    catch(Exception e){
        Alerta();
    }
}

public void establecerBotones(){ 
    boton1= (Button)findViewById(R.id.boton1);      //all buttons do something similar
    boton1.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int action = event.getAction();
            switch(action){
                case MotionEvent.ACTION_DOWN:
                    v.setPressed(true);
                    conectar("continua/1/0");
                    break;
                case MotionEvent.ACTION_OUTSIDE:
                case MotionEvent.ACTION_UP:
                    v.setPressed(false);
                    try {
                        conectar("continua/0/0");
                    } catch (Exception e) {
                    }
                    break;
            }
            return true;
        }
    });
    boton2= (Button)findViewById(R.id.boton2); 
    boton2.setOnTouchListener(new OnTouchListener() {
    });
    boton3= (Button)findViewById(R.id.boton3); 
    boton3.setOnTouchListener(new OnTouchListener() {
    });
    boton4= (Button)findViewById(R.id.boton4); 
    boton4.setOnTouchListener(new OnTouchListener() {
    });
}

private void conectar(final String selector) {
      new Thread() {
          @Override
          public void run() {
                 try {
                     // code runs in a thread
                       runOnUiThread(new Runnable() {
                              @Override
                              public void run() {
                                  try {
                                    definir (selector);
                                  } catch (Exception e) {
                                    System.out.println("holi");
                                  }
                              }
                       });
                 } catch (final Exception ex) {
                }
          }
   }.start();
}
public void definir(String selector) throws Exception{
    valor = "http://192.168.240.1/arduino/" + selector;
    URL url = new URL(valor);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        leer(in);
        }
    finally {
         urlConnection.disconnect();
        }
}

public void leer(InputStream in) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    if ((reader.readLine()) != "1") throw new IOException(); 
    //Arduino is programmed to print "1" when connection succedes
}

public void Alerta(){                           
    Context context = getApplicationContext();
    CharSequence text = "Conexion erronea";
    int duration = Toast.LENGTH_SHORT;
    Toast toast = Toast.makeText(context, text, duration);
    toast.show();
}

PD:我是编程的初学者,今年我开始纯粹自学 Java(和 android)。我可能在我的代码上做了一些“愚蠢”的错误。我将不胜感激任何帮助或建议。感谢您的阅读。

【问题讨论】:

  • 看起来您正在通过 UI 线程下载数据。看看AsyncTask
  • 我做到了,但我仍然不明白如何应用它以及为什么它会带来好处。

标签: java android performance optimization arduino


【解决方案1】:

您的代码有问题,如 cmets 中所述。如果您在 UI 线程上花费任何时间做一些事情,Android 的行为就会很糟糕。您需要将外部连接移动到单独的线程上,并找到一种通过它进行通信的方法。作为一个新手程序员,你会发现这很难,但是周围有很多代码示例可以提供帮助。

但这(以及您发布的代码)与您的实际问题无关。你有一个“开环”控制机制,你需要闭环。您需要一种方法让受控设备响应一些关于它是否已移动或正在移动的信息,并且您需要相应地修改您的控制策略。

或者,您可以向车辆发送更复杂的命令(如“左 3”或“直行”),并将循环监控留给车辆的车载处理器。

这些都是常见的问题,你会发现大量的通用阅读材料很少搜索。当您有非常具体的问题时,Stack Overflow 可能会提供更好的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-20
    • 2011-08-27
    • 2018-03-09
    • 1970-01-01
    • 2017-01-19
    • 2019-04-23
    • 2021-08-28
    • 1970-01-01
    相关资源
    最近更新 更多