在线程中执行不同的操作 - android

时间:2016-03-03 08:07:40

标签: android multithreading android-volley timertask

我有条件写每50ms执行一次的服务器调用。 服务器调用必须来自凌空。 但我面临的困难是每个服务器调用都有不同的URL以及如何在线程中传递这些不同的URL,以便每50ms调用一次服务器。?

1 个答案:

答案 0 :(得分:0)

我不是android的专家,但如果你想在50ms之后调用不同的url,这就是我能想到的。如果我错了,请纠正我:)

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {
    private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
    int i=0;
    final String[] urlArray = new String[]{"http://google.com","http://fb.com"};//your url array here

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

        Runnable task = new Runnable() {
            public void run() {
                String currentURL= MainActivity.this.getNextURL();
                new HitWebService().execute(currentURL);
            }
        };
        worker.schedule(task, 50, TimeUnit.SECONDS);
    }

    private String getNextURL(){
        String currentURL= urlArray[i];
        if(i ==  urlArray.length){
            i=0;
        }
        else{
            i++;
        }
        return currentURL;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private class HitWebService extends AsyncTask<String,Void,String> {

        protected void onPreExecute(){
            //do whatever you want with respect to ui
        }

        @Override
        protected String doInBackground(String... params){
            HttpURLConnection connection=null;
            String stringUrl= params[0];
            try {
                URL url= new URL(stringUrl);
                connection=(HttpURLConnection)url.openConnection();
                connection.setRequestMethod("POST");
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                DataOutputStream outputStream=new DataOutputStream(connection.getOutputStream());
                String parameters = "initialise your parameters here, pass parameters also in params and access it like params[1]";

                outputStream.writeBytes(parameters);
                outputStream.flush();
                outputStream.close();

                InputStream inputStream=connection.getInputStream();
                BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer response = new StringBuffer();
                String line;
                while((line=bufferedReader.readLine())!=null){
                    response.append(line);
                }

                bufferedReader.close();
                return response.toString();
            }
            catch (MalformedURLException malformedException){
                return malformedException.toString();
            }
            catch (IOException ioException){
                return ioException.toString();
            }
            finally {
                if(connection !=null){
                    connection.disconnect();
                }
            }
        }

        @Override
        protected void onPostExecute(String response){
            //do whatever you want here
        }
    }
}