C
C
Cyrill45052018-11-04 16:33:17
Android
Cyrill4505, 2018-11-04 16:33:17

Getting data from the Android server without pressing a button, how to organize?

Hello. Please tell me how (and which one) to organize the receipt of data from the server without pressing a button in the android application. At the moment there is an application that receives data from the server by pressing a button. I would like to get rid of this and receive data, for example, once every n seconds. I'm using OkHttp.
here is an example of my shit code)

public class MainActivity extends AppCompatActivity {

    Button button;
    TextView getTemperature;
    private OkHttpClient client;

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

        button = findViewById(R.id.submitButton);
        getTemperature = findViewById(R.id.getTemperature);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getWeb();
            }
        });
        client = new OkHttpClient();
    }

    private void getWeb(){
        Request request = new Request.Builder().url("http://192.168.0.23:3000").build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        getTemperature.setText("в работе возникла ошибка, скорее всего отсутствует интернет");
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            getTemperature.setText(response.body().string());
                        }
                       catch (IOException ioe){
                           getTemperature.setText("r");
                       }
                    }
                });
            }
        });
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Egor, 2018-11-04
@Cyrill4505

Create a background timer for loading data:

AsyncLoaderTimer bgTimer = new AsyncLoaderTimer(); //новое поле класса MainActivity

    class AsyncLoaderTimer extends AsyncTask<Long, Void, Void> {//класс фонового таймера

        @Override
        protected Void doInBackground(Long... longs) {
            while (isCancelled()) {
                try {
                    Thread.sleep(longs[0]);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                publishProgress();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            getWeb();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        bgTimer.execute(2_000L); //интервал миллисекунд
    }

    @Override
    protected void onStop() {
        super.onStop();
        bgTimer.cancel(false);
    }

The way you want to implement updating the data is not the best practice. You'd better look at how to implement such client/server solutions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question