'분류 전체보기'에 해당되는 글 256건

* MainActivity.java

public class MainActivity extends AppCompatActivity {

    EditText editText;
    TextView textView;

    Handler handler = new Handler();

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

        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String urlStr = editText.getText().toString();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        request(urlStr);
                    }
                }).start();
            }
        });
    }

    public void request(String urlStr) {
        try {
            StringBuilder builder = new StringBuilder();

            URL url = new URL(urlStr);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            if (conn != null) {
                conn.setConnectTimeout(10000);
                conn.setRequestMethod("GET");
                conn.setDoInput(true);

                int resCode = conn.getResponseCode();

                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line = null;
                while (true) {
                    line = reader.readLine();
                    if (line == null) {
                        break;
                    }

                    builder.append(line + "\n");
                }

                reader.close();
                conn.disconnect();
            }

            println("응답 : " + builder.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void println(final String data) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                textView.append(data + "\n");
            }
        });
    }

}

* activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="http://www.google.com" />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="요청" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/textView"
                android:textSize="20dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>

    </ScrollView>

</LinearLayout>

* AndroidManifest.xml

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

'android' 카테고리의 다른 글

gson 사용법  (0) 2020.02.04
Volley 사용법  (0) 2020.02.04
Socket 통신(Thread 필수)  (0) 2020.02.04
AsyncTask 사용법  (0) 2020.02.04
Thread 사용법  (0) 2020.02.04
블로그 이미지

디츠

“말은 쉽지, 코드를 보여줘.” “Talk is cheap. Show me the code.” – 리누스 토르발스(Linus Torvalds)

,

* MainActivity.java

public class MainActivity extends AppCompatActivity {

    EditText input1;
    TextView output1;

    int port = 5001;

    Handler handler = new Handler();

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

        input1 = findViewById(R.id.input1);
        output1 = findViewById(R.id.output1);

        Button sendButton = findViewById(R.id.sendButton);
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String data = input1.getText().toString();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        send(data); // data 변수 접근을 위해 final 선언
                    }
                }).start();
            }
        });

        Button startServerButton = findViewById(R.id.startServerButton);
        startServerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        startServer();
                    }
                }).start();
            }
        });
    }

    public void startServer() {
        try {
            ServerSocket server = new ServerSocket(port);

            while (true) {
                Socket socket = server.accept();
                InetAddress clientHost = socket.getInetAddress();
                int clientPort = socket.getPort();
                println("클라이언트 연결됨 : " + clientHost + ", " + clientPort);

                ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
                String input = (String) inputStream.readObject();
                println("데이터 받음 : " + input);

                ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
                outputStream.writeObject(input + " from server.");
                outputStream.flush();
                println("데이터 보냄");

                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void println(final String data) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                output1.append(data + "\n");
            }
        });
    }

    public void send(String data) {
        try {
            Socket socket = new Socket("localhost", port);

            ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
            outputStream.writeObject(data);
            outputStream.flush();

            ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
            String input = (String) inputStream.readObject();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

* activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#80D8FF"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView"
            android:textSize="30sp"
            android:layout_marginBottom="30dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="클라이언트" />

        <EditText
            android:id="@+id/input1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName" />

        <Button
            android:id="@+id/sendButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="전송" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#FFFF8D"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView2"
            android:textSize="30sp"
            android:layout_marginBottom="30dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="서버" />

        <Button
            android:id="@+id/startServerButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="서버 시작" />

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/output1"
                    android:textSize="20sp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </LinearLayout>
            
        </ScrollView>

    </LinearLayout>

</LinearLayout>

* AndroidManifest.xml

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

'android' 카테고리의 다른 글

Volley 사용법  (0) 2020.02.04
HttpURLConnection 사용법  (0) 2020.02.04
AsyncTask 사용법  (0) 2020.02.04
Thread 사용법  (0) 2020.02.04
키패드 닫기  (0) 2020.02.03
블로그 이미지

디츠

“말은 쉽지, 코드를 보여줘.” “Talk is cheap. Show me the code.” – 리누스 토르발스(Linus Torvalds)

,

AsyncTask 사용법

android 2020. 2. 4. 14:59

* MainActivity.java

public class MainActivity extends AppCompatActivity {

    ProgressBar progressBar;

    int value;

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

        progressBar = findViewById(R.id.progressBar);

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BackgroundTask task = new BackgroundTask();
                task.execute();
            }
        });
    }

    class BackgroundTask extends AsyncTask<Integer, Integer, Integer> {

        @Override
        protected void onPreExecute() {
            value = 0;
            progressBar.setProgress(value);
        }

        @Override
        protected void onPostExecute(Integer integer) {
            progressBar.setProgress(0);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            progressBar.setProgress(values[0].intValue());
        }

        @Override
        protected Integer doInBackground(Integer... integers) {
            while (isCancelled() == false) {
                value++;

                if (value >= 100) {
                    break;
                }

                publishProgress(value);

                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    //
                }
            }

            return value;
        }

    }

}

* activity_main.xml

public class MainActivity extends AppCompatActivity {

    ProgressBar progressBar;

    int value;

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

        progressBar = findViewById(R.id.progressBar);

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BackgroundTask task = new BackgroundTask();
                task.execute();
            }
        });
    }

    class BackgroundTask extends AsyncTask<Integer, Integer, Integer> {

        @Override
        protected void onPreExecute() {
            value = 0;
            progressBar.setProgress(value);
        }

        @Override
        protected void onPostExecute(Integer integer) {
            progressBar.setProgress(0);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            progressBar.setProgress(values[0].intValue());
        }

        @Override
        protected Integer doInBackground(Integer... integers) {
            while (isCancelled() == false) {
                value++;

                if (value >= 100) {
                    break;
                }

                publishProgress(value);

                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    //
                }
            }

            return value;
        }

    }

}

 

'android' 카테고리의 다른 글

HttpURLConnection 사용법  (0) 2020.02.04
Socket 통신(Thread 필수)  (0) 2020.02.04
Thread 사용법  (0) 2020.02.04
키패드 닫기  (0) 2020.02.03
SeekBar 사용법  (0) 2020.02.03
블로그 이미지

디츠

“말은 쉽지, 코드를 보여줘.” “Talk is cheap. Show me the code.” – 리누스 토르발스(Linus Torvalds)

,

Thread 사용법

android 2020. 2. 4. 01:17

* MainActivity.java

public class MainActivity extends AppCompatActivity {

    TextView textView;
    Handler handler = new Handler();

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

        textView = findViewById(R.id.textView);

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BackgroundThread thread = new BackgroundThread();
                thread.start();
            }
        });
    }

    class BackgroundThread extends Thread {
        int value = 0;

        public void run() {
            for (int i = 0; i < 100; i++) {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    //
                }

                value++;
                Log.d("MyThread", "value : " + value);

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        textView.setText("값 : " + value);

                    }
                });

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        textView.setText("값 : " + value);
                    }
                }, 5000);
            }
        }
    }

}

'android' 카테고리의 다른 글

Socket 통신(Thread 필수)  (0) 2020.02.04
AsyncTask 사용법  (0) 2020.02.04
키패드 닫기  (0) 2020.02.03
SeekBar 사용법  (0) 2020.02.03
입력된 url을 WebView로 열기  (0) 2020.02.03
블로그 이미지

디츠

“말은 쉽지, 코드를 보여줘.” “Talk is cheap. Show me the code.” – 리누스 토르발스(Linus Torvalds)

,

키패드 닫기

android 2020. 2. 3. 23:41

* MainActivity.java

public class MainActivity extends AppCompatActivity {

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

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
            }
        });
    }

}

* activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="키패드 닫기"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.083" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button"
        app:layout_constraintVertical_bias="0.173" />
    
</androidx.constraintlayout.widget.ConstraintLayout>

* AndroidManifest.xml

<activity android:windowSoftInputMode="stateHidden">

'android' 카테고리의 다른 글

AsyncTask 사용법  (0) 2020.02.04
Thread 사용법  (0) 2020.02.04
SeekBar 사용법  (0) 2020.02.03
입력된 url을 WebView로 열기  (0) 2020.02.03
Spinner 사용법  (0) 2020.02.03
블로그 이미지

디츠

“말은 쉽지, 코드를 보여줘.” “Talk is cheap. Show me the code.” – 리누스 토르발스(Linus Torvalds)

,

SeekBar 사용법

android 2020. 2. 3. 23:30

* MainActivity.java

public class MainActivity extends AppCompatActivity {

    TextView textView;

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

        textView = findViewById(R.id.textView);

        SeekBar seekBar = findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                textView.setText("지정된 값 : " + progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

    }

}

* activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/textView"
        android:layout_marginTop="50dp"
        android:textSize="30sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="지정한 값" />

</LinearLayout>

'android' 카테고리의 다른 글

Thread 사용법  (0) 2020.02.04
키패드 닫기  (0) 2020.02.03
입력된 url을 WebView로 열기  (0) 2020.02.03
Spinner 사용법  (0) 2020.02.03
RecyclerView 리스트(문자목록, 통화목록 ..)  (0) 2020.02.03
블로그 이미지

디츠

“말은 쉽지, 코드를 보여줘.” “Talk is cheap. Show me the code.” – 리누스 토르발스(Linus Torvalds)

,