[JAVA] I tried to make it possible to set the delay for the UDP client of Android by myself

Changes from the last time

In the previous program, the delay time was set to 500 milliseconds, but when measuring the value of the accelerometer, it has been improved so that the delay can be adjusted by yourself in order to shorten the delay time when performing motion detection. ..

Source code

AndroidManifest.xml


<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Please note that it will not work unless you add permission to use the Internet to AndroidManifest.xml. (2 losses)

activity_main.xml


<EditText
        android:id="@+id/IP_Address"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="52dp"
        android:layout_marginEnd="16dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="192.168.0."
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/Port"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="48dp"
        android:layout_marginEnd="16dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="8080"
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/IP_Address" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="280dp"
        android:text="X:"
        android:textSize="32sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="24dp"
        android:text="Y:"
        android:textSize="32sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="24dp"
        android:text="Z:"
        android:textSize="32sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <TextView
        android:id="@+id/X_Data"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="280dp"
        android:text="TextView"
        android:textSize="32sp"
        app:layout_constraintStart_toEndOf="@+id/textView"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/Y_Data"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="TextView"
        android:textSize="32sp"
        app:layout_constraintStart_toEndOf="@+id/textView2"
        app:layout_constraintTop_toBottomOf="@+id/X_Data" />

    <TextView
        android:id="@+id/Z_Data"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="TextView"
        android:textSize="32sp"
        app:layout_constraintStart_toEndOf="@+id/textView3"
        app:layout_constraintTop_toBottomOf="@+id/Y_Data" />

    <TextView
        android:id="@+id/textView7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="230dp"
        android:text="Accelerometer value"
        android:textSize="32sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/Ran"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="87dp"
        android:layout_marginLeft="87dp"
        android:layout_marginBottom="70dp"
        android:text="Start communication"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginBottom="8dp"
        android:text="IP address"
        android:textSize="24sp"
        app:layout_constraintBottom_toTopOf="@+id/IP_Address"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginBottom="8dp"
        android:text="port number"
        android:textSize="24sp"
        app:layout_constraintBottom_toTopOf="@+id/Port"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/End"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="87dp"
        android:layout_marginRight="87dp"
        android:layout_marginBottom="70dp"
        android:text="Communication cancellation"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <ImageView
        android:id="@+id/LED1"
        android:layout_width="75dp"
        android:layout_height="75dp"
        android:layout_marginStart="100dp"
        android:layout_marginLeft="100dp"
        android:layout_marginBottom="150dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:srcCompat="@drawable/en" />

    <ImageView
        android:id="@+id/LED2"
        android:layout_width="75dp"
        android:layout_height="75dp"
        android:layout_marginEnd="100dp"
        android:layout_marginRight="100dp"
        android:layout_marginBottom="150dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:srcCompat="@drawable/en" />

    <TextView
        android:id="@+id/textView6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="352dp"
        android:layout_marginEnd="124dp"
        android:layout_marginRight="124dp"
        android:text="Delay"
        android:textSize="32sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/Delay"
        android:layout_width="159dp"
        android:layout_height="49dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="40dp"
        android:layout_marginRight="40dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="100"
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView6" />

The layout looks like this

MainActivity.java



import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity implements SensorEventListener{

    private SensorManager sensorManager;
    private TextView X_Data_TextView;   //Accelerometer X value
    private TextView Y_Data_TextView;   //Accelerometer Y value
    private TextView Z_Data_TextView;   //Accelerometer Z value
    private float data_X,data_Y,data_Z;
    private String Data;
    private Timer timer1,timer2;
    private mTimerTask1 timerTask1;
    private mTimerTask2 timerTask2;
    private Handler handler = new Handler();
    private Handler handler1 = new Handler();
    private long Delay;
    ImageView LED1,LED2;


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

        sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
        X_Data_TextView = findViewById(R.id.X_Data);
        Y_Data_TextView = findViewById(R.id.Y_Data);
        Z_Data_TextView = findViewById(R.id.Z_Data);

        LED1 = findViewById(R.id.LED1);
        LED2 = findViewById(R.id.LED2);
        LED1.setImageResource(R.drawable.en);
        LED2.setImageResource(R.drawable.en);

        Button ran = findViewById(R.id.Ran);
        Button end = findViewById(R.id.End);

        ran.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(null != timer1){
                    timer1.cancel();
                    timer1 = null;
                }

                String delay = ((EditText)findViewById(R.id.Delay)).getText().toString();
                Delay = Long.parseLong(delay);

                timer1 = new Timer();
                timerTask1 = new mTimerTask1();
                timer1.schedule(timerTask1,0, Delay);

                timer2 = new Timer();
                timerTask2 = new mTimerTask2();
                timer2.schedule(timerTask2,0,Delay);
            }
        });

        end.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if(null != timer1){
                    timer1.cancel();
                    timer1 = null;
                }
                final String address = ((EditText) findViewById(R.id.IP_Address)).getText().toString();
                String port = ((EditText) findViewById(R.id.Port)).getText().toString();
                int Port = Integer.parseInt(port);
                String exit = "exit";
                byte buf[] = new byte[exit.length()];

                try {
                    buf = exit.getBytes("SHIFT_JIS");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                InetSocketAddress inetSocketAddress = new InetSocketAddress(address, Port);
                final DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length, inetSocketAddress);

                AsyncTask<DatagramPacket, Void, Void> task = new AsyncTask<DatagramPacket, Void, Void>() {
                    @Override
                    protected Void doInBackground(DatagramPacket... datagramPackets) {
                        DatagramSocket datagramSocket = null;
                        try {
                            datagramSocket = new DatagramSocket();
                            datagramSocket.send(datagramPackets[0]);
                            datagramSocket.close();
                        } catch (SocketException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                };
                task.execute(datagramPacket);

            }
        });

    }



    @Override
    protected void onResume(){
        super.onResume();
        //Event Listener registration
        Sensor accel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener((SensorEventListener) this,accel,SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onPause(){
        super.onPause();
        //Event Listener unregistered
        sensorManager.unregisterListener((SensorEventListener) this);
    }

    @Override
    public void onSensorChanged(SensorEvent event){
        if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
            X_Data_TextView.setText(String.format("%.3f",500+(event.values[0])*25));
            Y_Data_TextView.setText(String.format("%.3f",500+(event.values[1])*25));
            Z_Data_TextView.setText(String.format("%.3f",500+(event.values[2]) *25));
            Data = (500+event.values[0]*25) + " " +
                    (500+event.values[1]*25) + " " +
                    (500+event.values[2]*25);

            data_X= (500+event.values[0]*25);
            data_Y= (500+event.values[1]*25);
            data_Z= (500+event.values[2]*25);


        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy){

    }

    private class mTimerTask2 extends TimerTask{
        @Override
        public void run() {
            handler.post(new Runnable() {
                @Override
                public void run() {
                        if (data_X >= 700) {
                            LED1.setImageResource(R.drawable.en_gleen);
                        } else if (data_X <= 300) {
                            LED1.setImageResource(R.drawable.en);
                        } else if (data_Y >= 700) {
                            LED2.setImageResource(R.drawable.en_red);
                        } else if (data_Y <= 300) {
                            LED2.setImageResource(R.drawable.en);
                        } else if (data_Z >= 700) {
                            LED1.setImageResource(R.drawable.en_gleen);
                            LED2.setImageResource(R.drawable.en_red);
                        } else if (data_Z <= 300) {
                            LED1.setImageResource(R.drawable.en);
                            LED2.setImageResource(R.drawable.en);
                        }
                }
            });
        }

    }
    private class mTimerTask1 extends TimerTask{
        @Override
        public void run(){

            handler.post(new Runnable() {
                @Override
                public void run() {
                    final String address = ((EditText) findViewById(R.id.IP_Address)).getText().toString();
                    String port = ((EditText) findViewById(R.id.Port)).getText().toString();
                    int Port = Integer.parseInt(port);
                    byte buf[] = new byte[Data.length()];

                    try {
                        buf = Data.getBytes("SHIFT_JIS");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                    InetSocketAddress inetSocketAddress = new InetSocketAddress(address, Port);
                    final DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length, inetSocketAddress);


                    AsyncTask<DatagramPacket, Void, Void> task = new AsyncTask<DatagramPacket, Void, Void>() {
                        @Override
                        protected Void doInBackground(DatagramPacket... datagramPackets) {
                            DatagramSocket datagramSocket = null;

                            try {
                                datagramSocket = new DatagramSocket();
                                datagramSocket.send(datagramPackets[0]);
                                datagramSocket.close();
                            } catch (SocketException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                            return null;
                        }

                    };
                    task.execute(datagramPacket);
                }
            });

        }
    }
}

Recommended Posts

I tried to make it possible to set the delay for the UDP client of Android by myself
I tried to investigate the mechanism of Emscripten by using it with the Sudoku solver
I tried to make a client of RESAS-API in Java
[Java] I tried to make a maze by the digging method β™ͺ
Since the Rspec command is troublesome, I tried to make it possible to execute Rspec with one Rake command
I tried to make full use of the CPU core in Ruby
I don't know anything, I tried to make TODO while studying ruby ​​on rails for 3 days by myself
I tried to set tomcat to run the Servlet.
I tried to summarize the state transition of docker
05. I tried to stub the source of Spring Boot
I tried to reduce the capacity of Spring Boot
[VBA] I tried to make a tool to convert the primitive type of Entity class generated by Hibernate Tools to the corresponding reference type.
I tried to make the sample application into a microservice according to the idea of the book "Microservice Architecture".
[For Swift beginners] I tried to summarize the messy layout cycle of ViewController and View
[SwiftUI] I tried to find out how it changes for each specified location of background
I tried to implement the like function by asynchronous communication
I tried to introduce Bootstrap 4 to the Rails 6 app [for beginners]
I tried to summarize the basics of kotlin and java
[Swift] I tried to implement the function of the vending machine
I tried to summarize the basic grammar of Ruby briefly
I tried to build the environment little by little using docker
I tried to build the environment of WSL2 + Docker + VSCode
I was inspired by the article for newcomers, so make a note of it so that you don't forget your original intentions.
I tried to make the "Select File" button of the sample application created in the Rails tutorial cool
I tried to take a look at the flow of Android development environment construction with Android Studio
I tried to solve the problem of "multi-stage selection" with Ruby
I tried to build the environment of PlantUML Server with Docker
The story of Collectors.groupingBy that I want to keep for posterity
I tried to deepen my understanding of object orientation by n%
I tried to make an Android application with MVC now (Java)
I want to limit the input by narrowing the range of numbers
I tried to check the operation of gRPC server with grpcurl
I tried to summarize the methods of Java String and StringBuilder
I tried to make it an arbitrary URL using routing nesting
[Android] Dynamically set the height of ListView with copy (for beginners)
I tried to solve the problem of Google Tech Dev Guide
The story of making it possible to build a project that was built by Maven with Ant
I tried to explain the method
I tried to make a sample program using the problem of database specialist in Domain Driven Design
I don't really understand the difference between swift Error and NSError, so I tried to summarize it myself.
I tried to make a parent class of a value object in Ruby
I tried to make a simple face recognition Android application using OpenCV
I want to display the number of orders for today using datetime.
I tried to summarize the stumbling points when developing an Android application
I tried connecting the dot counter to the MZ platform by serial communication
I tried to summarize the key points of gRPC design and development
The story of releasing the Android app to the Play Store for the first time.
I tried to visualize the access of Lambda β†’ Athena with AWS X-Ray
How to make the schema of the URL generated by Rails URL helper https
I want you to use Enum # name () for the Key of SharedPreference
Is it possible to put the library (aar) in the Android library (aar) and use it?
I tried to measure and compare the speed of GraalVM with JMH
I tried to make a program that searches for the target class from the process that is overloaded with Java
Since the docker-desktop preview for m1 came out, I tried to face it with my macbook pro 15inch
Since the image of the lock screen of Windows 10 is beautiful, I wanted to make it a slide show of wallpaper
I tried to summarize the methods used
I tried to implement the Iterator pattern
I tried to summarize the Stream API
Amicable numbers, perfect numbers, excess numbers, deficient numbers, palindromic numbers I tried to make various numbers of programs
[RxSwift] I want to deepen my understanding by following the definition of Observable
I tried to implement a function equivalent to Felica Lite with HCE-F of Android