Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement