我当前的代码采用JSON响应,解析它,然后将值显示为一个活动的值。如何将它们分成线程?

发布于 2025-01-19 16:49:49 字数 2800 浏览 0 评论 0原文

(注意:我正在使用Android射击库作为网络连接),

public class PostureActivity extends AppCompatActivity {
private static final String LOG_TAG = PostureActivity.class.getName();

private static final String EMB_URL = "https://api.thingspeak.com/channels/xxxxxxx/feed/last.json?round=1";

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

@Override
protected void onResume() {
    super.onResume();
    connect(); // call at the start

    final Handler handler = new Handler();
    Runnable scrape = new Runnable() {
        @Override
        public void run() {
            connect(); // call every x ms
            handler.postDelayed(this, 3000);
        }
    };
    handler.postDelayed(scrape, 3000);
}


private void connect() {
    MySingleton.getInstance(this.getApplicationContext()).getRequestQueue();

    JsonObjectRequest collectData = new JsonObjectRequest(
            Request.Method.GET, // HTTP method
            EMB_URL, // URL string that returns the desired JSON // TODO: change appropriate url
            null, // optional JSON to send as request
            response -> { // retrieved data
                try {
                    JSONObject myResponse = new JSONObject(response.toString());

                    // TODO: cast to double to show the average
                    String ultrasonic = myResponse.getString("field1");
                    String flex1 = myResponse.getString("field2");
                    String flex2 = myResponse.getString("field3");
                  
                    TextView neck = findViewById(R.id.neck_number);
                    TextView back = findViewById(R.id.back_number);
                    TextView butt = findViewById(R.id.butt_number);

                    neck.setText(ultrasonic);
                    back.setText(flex1);
                    butt.setText(flex2);

                } catch (JSONException e) { // what if response is null?
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Response values are empty.", Toast.LENGTH_LONG).show();
                    finishAffinity();
                    finishAndRemoveTask();
                }
            },
            error -> { // retrieved error/failure
                error.printStackTrace();
                Toast.makeText(getApplicationContext(), "Could not connect to website.", Toast.LENGTH_LONG).show();
                finishAffinity();
                finishAndRemoveTask();
            }
    );
    MySingleton.getInstance(this).addToRequestQueue(collectData);
}

如您所见,Connect()基本上是检索,解析和显示数据,然后通过处理程序运行它。如何拆分代码,以使整个函数不简单地填充UI线程?在异步任务之外,我对处理程序/循环器或Java线程并不熟悉,因此我希望我能指出正确的方向,以便如何更好地优化功能。

(note: I'm using the Android Volley library for the network connection)

public class PostureActivity extends AppCompatActivity {
private static final String LOG_TAG = PostureActivity.class.getName();

private static final String EMB_URL = "https://api.thingspeak.com/channels/xxxxxxx/feed/last.json?round=1";

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

@Override
protected void onResume() {
    super.onResume();
    connect(); // call at the start

    final Handler handler = new Handler();
    Runnable scrape = new Runnable() {
        @Override
        public void run() {
            connect(); // call every x ms
            handler.postDelayed(this, 3000);
        }
    };
    handler.postDelayed(scrape, 3000);
}


private void connect() {
    MySingleton.getInstance(this.getApplicationContext()).getRequestQueue();

    JsonObjectRequest collectData = new JsonObjectRequest(
            Request.Method.GET, // HTTP method
            EMB_URL, // URL string that returns the desired JSON // TODO: change appropriate url
            null, // optional JSON to send as request
            response -> { // retrieved data
                try {
                    JSONObject myResponse = new JSONObject(response.toString());

                    // TODO: cast to double to show the average
                    String ultrasonic = myResponse.getString("field1");
                    String flex1 = myResponse.getString("field2");
                    String flex2 = myResponse.getString("field3");
                  
                    TextView neck = findViewById(R.id.neck_number);
                    TextView back = findViewById(R.id.back_number);
                    TextView butt = findViewById(R.id.butt_number);

                    neck.setText(ultrasonic);
                    back.setText(flex1);
                    butt.setText(flex2);

                } catch (JSONException e) { // what if response is null?
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Response values are empty.", Toast.LENGTH_LONG).show();
                    finishAffinity();
                    finishAndRemoveTask();
                }
            },
            error -> { // retrieved error/failure
                error.printStackTrace();
                Toast.makeText(getApplicationContext(), "Could not connect to website.", Toast.LENGTH_LONG).show();
                finishAffinity();
                finishAndRemoveTask();
            }
    );
    MySingleton.getInstance(this).addToRequestQueue(collectData);
}

As you can see, connect() essentially retrieves, parses, and displays the data, and I run it via a handler. How do split the code so that this entire function doesn't simply populate the UI thread? I'm not very familiar with handler/loopers or java threads outside of async tasks, so I was hoping that I could be pointed in the right direction as to how to optimize the function better.

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文