【问题标题】:Send data with URL get in android in while loop在while循环中发送带有URL获取的数据
【发布时间】:2017-04-29 09:56:56
【问题描述】:

我想在运行它时将带有获取 URL 的 a 和 b 发送到 example.com,它可以工作一次。

我想在条件为真期间发送 a 和 b。我使用睡眠,所以连续 5 秒后发送数据。

public class MapsActivity extends FragmentActivity 
      implements OnMapReadyCallback {
public a=0,b=0;
public btn=2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        connect();
    } //end of onCreate
     public void connect() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                communication();
            }
        }).start();
    }
    public void communication() {

        while(btn >0){

            try {
                btn++;
                a++;
                b++;
                URL url = new URL("example.com"+ "?a=" +a+"&b="+b);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                InputStream inputStream = conn.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String data = "", line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    data += line + "\n";
                }

                sleep(5000);

            } catch (MalformedURLException e) {
                Log.e("error", e.toString());
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }//end of while   
    } //end of communication
    }//end of class

【问题讨论】:

    标签: java android android-studio while-loop get


    【解决方案1】:

    我认为Timersleep 好。你可以试试这个:

    Handler handler = new Handler();
    
        Runnable sendRequest = new Runnable() {
            public void run() {
                // your code to send request 
            }
        };
    
    
        new Timer().schedule(new TimerTask() {
    
            @Override
            public void run() {
                handler.post(sendRequest);
            }
        }, 100, 5000);
    

    【讨论】:

      【解决方案2】:

      我建议不要在 Activity 类中这样做。

      创建一个每 n 秒运行一次的后台服务类,在你的情况下让我们说 5 。

      现在创建一个队列。只要条件为真,就在此队列中推送数据。

      一旦后台服务开始运行,它将从队列中读取数据并使用数据进行 api 调用

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-28
        • 1970-01-01
        相关资源
        最近更新 更多