'안드로이드 앱 만들기'에 해당되는 글 43건

  1. 2020.09.08 VideoView
  2. 2020.09.07 BroadCastReceiver
  3. 2020.09.06 RelativeLayout (랠러티브레이아웃)
  4. 2020.09.02 Login & Register
  5. 2020.09.01 Linear Layout (1)
  6. 2020.08.30 Button Selector
  7. 2020.08.30 Start Activity For Result
  8. 2020.08.29 바텀 네비게이션 뷰(인스타 하단 바)
  9. 2020.08.29 google map
  10. 2020.08.29 뒤로가기 두번 눌러 앱 종료

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">

    <VideoView
        android:id="@+id/videoView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

----------------------------

 

 

----------------------------

MainActivity.java

package com.example.videoview;

import androidx.appcompat.app.AppCompatActivity;

import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {

    private VideoView videoView; // 비디오를 실행할 수 있게 도와주는 뷰
    private MediaController mediaController; // 재생이나 정지와 같은 미디어 제어 버튼부를 담당
    private String videoURL = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4";

    @Override
    protected void onCreate(Bundle savedInstanceState) { // 앱이 첫 실행 됐을때 이곳을 수행
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        videoView = findViewById(R.id.videoView); // 비디오 뷰 아이디 연결
        mediaController = new MediaController(this);
        mediaController.setAnchorView(videoView);
        Uri uri = Uri.parse(videoURL);
        videoView.setMediaController(mediaController); // 미디어 제어 버튼부 세팅팅
        videoView.setVideoURI(uri); // 비디오 뷰의 주소를 설정
        videoView.start(); // 비디오 실행
    }
}

----------------------------

 

 

----------------------------

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.videoview">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true"> <!-- 이 코드가 있어야 http 주소를 불러옴 -->
        <activity android:name=".MainActivity"
            android:screenOrientation="landscape"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

----------------------------

'안드로이드 앱 만들기' 카테고리의 다른 글

Firebase Recycler View  (0) 2020.09.12
Constraint Layout  (0) 2020.09.10
BroadCastReceiver  (0) 2020.09.07
RelativeLayout (랠러티브레이아웃)  (0) 2020.09.06
Login & Register  (0) 2020.09.02
Posted by khon98
,

BroadCastReceiver

와이파이 인터넷 네트워크 체크할 때 주로 사용하는 4대 컴포넌트 중에 하나

 

textStyle

bold - 굵게

italic - 기울기를 주는 글씨체

normal - 일반 기본 글씨체

 

Intent의 종류

명시적 Intent

암시적 Intent

 

Intent 와 IntentFilter의 차이점

Intent - 기능을 가져와 쓰는 것

IntentFilter - Intent와 반대

 

---------------------------------------

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">

    <TextView
        android:id="@+id/tv_state"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="khon"
        android:textSize="30sp"
        android:textColor="#38EFEF"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

---------------------------------------

 

 

---------------------------------------

MainActivity.java

package com.example.broadcastreceiver;

import androidx.appcompat.app.AppCompatActivity;

import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    public static TextView tv_state;
    private NetworkReceiver receiver;

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

        tv_state = findViewById(R.id.tv_state);

        // 브로드 캐스트 리시버 등록
        IntentFilter filter = new IntentFilter();
        receiver = new NetworkReceiver();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        registerReceiver(receiver,filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 브로드 캐스트 리시버 해제
        unregisterReceiver(receiver);
    }
}

---------------------------------------

 

 

java파일 생성

---------------------------------------

NetworkReceiver.java

package com.example.broadcastreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;

public class NetworkReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // 네트워크 상태 값 받아오기
        if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
            NetworkInfo info = (NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
            NetworkInfo.DetailedState state = info.getDetailedState();
            if (state == NetworkInfo.DetailedState.CONNECTED) { // 네트워크 연결 상태이면...
                MainActivity.tv_state.setText("네트워크 연결 완료");
            } else if (state == NetworkInfo.DetailedState.DISCONNECTED) { // 네트워크 연결 해제이면...
                MainActivity.tv_state.setText("네트워크 연결 해제");
            }
        }
    }
}

---------------------------------------

 

 

---------------------------------------

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.broadcastreceiver">
    
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

'안드로이드 앱 만들기' 카테고리의 다른 글

Constraint Layout  (0) 2020.09.10
VideoView  (0) 2020.09.08
RelativeLayout (랠러티브레이아웃)  (0) 2020.09.06
Login & Register  (0) 2020.09.02
Linear Layout (1)  (0) 2020.09.01
Posted by khon98
,

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

    <TextView
        android:id="@+id/tv_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:textColor="#39D689"
        android:text="khon"/>

    <TextView
        android:id="@+id/tv_2"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="khon01"/>

    <TextView
        android:id="@+id/tv_3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/tv_2"
        android:layout_centerInParent="true"
        android:textSize="20sp"
        android:text="khon"/>

    <TextView
        android:id="@+id/tv_4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:textSize="20sp"
        android:textColor="#39D689"
        android:text="khon"/>

    <TextView
        android:id="@+id/tv_5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:textSize="20sp"
        android:textColor="#39D689"
        android:text="khon"/>

</RelativeLayout>

'안드로이드 앱 만들기' 카테고리의 다른 글

VideoView  (0) 2020.09.08
BroadCastReceiver  (0) 2020.09.07
Login & Register  (0) 2020.09.02
Linear Layout (1)  (0) 2020.09.01
Button Selector  (0) 2020.08.30
Posted by khon98
,

volley - 서버 통신 관련해서 필요한 라이브러리(전송, 다운로드 관련 라이브러리)

 

-----------------------------------

AndrioidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.registerlogin">

    <uses-permission android:name="android.permission.INTERNET"/> <!-- 인터넷 권한 설정-->

    <application
        android:usesCleartextTraffic="true"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".RegisterActivity" />
        <activity android:name=".MainActivity">

        </activity>
    </application>

</manifest>

-----------------------------------

 

 

-----------------------------------

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">

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:text="Hello World!"
        android:textSize="30sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="아이디"
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView5" />

    <TextView
        android:id="@+id/tv_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="TextView"
        android:textSize="30sp"
        app:layout_constraintEnd_toEndOf="parent"
        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="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="비밀번호"
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tv_id" />

    <TextView
        android:id="@+id/tv_pass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="TextView"
        android:textSize="30sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView3" />

</androidx.constraintlayout.widget.ConstraintLayout>

-----------------------------------

 

 

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=".RegisterActivity">

    <EditText
        android:id="@+id/et_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="200dp"
        android:layout_marginEnd="8dp"
        android:ems="10"
        android:hint="아이디"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/et_pass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="비밀번호"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="@+id/et_id"
        app:layout_constraintStart_toStartOf="@+id/et_id"
        app:layout_constraintTop_toBottomOf="@+id/et_id" />

    <EditText
        android:id="@+id/et_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="이름"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="@+id/et_pass"
        app:layout_constraintStart_toStartOf="@+id/et_pass"
        app:layout_constraintTop_toBottomOf="@+id/et_pass" />

    <EditText
        android:id="@+id/et_age"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="나이"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="@+id/et_name"
        app:layout_constraintStart_toStartOf="@+id/et_name"
        app:layout_constraintTop_toBottomOf="@+id/et_name" />

    <Button
        android:id="@+id/btn_register"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="회원가입"
        app:layout_constraintEnd_toEndOf="@+id/et_age"
        app:layout_constraintStart_toStartOf="@+id/et_age"
        app:layout_constraintTop_toBottomOf="@+id/et_age" />
</androidx.constraintlayout.widget.ConstraintLayout>

-----------------------------------

 

 

xml 파일 추가

-----------------------------------

activity_login.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=".LoginActivity">

    <EditText
        android:id="@+id/et_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="200dp"
        android:layout_marginEnd="8dp"
        android:ems="10"
        android:hint="아이디"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/et_pass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="8dp"
        android:ems="10"
        android:hint="비밀번호"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/et_id" />

    <Button
        android:id="@+id/btn_login"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="로그인"
        app:layout_constraintEnd_toEndOf="@+id/et_pass"
        app:layout_constraintStart_toStartOf="@+id/et_pass"
        app:layout_constraintTop_toBottomOf="@+id/et_pass" />

    <Button
        android:id="@+id/btn_register"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="회원가입"
        app:layout_constraintEnd_toEndOf="@+id/btn_login"
        app:layout_constraintStart_toStartOf="@+id/btn_login"
        app:layout_constraintTop_toBottomOf="@+id/btn_login" />
</androidx.constraintlayout.widget.ConstraintLayout>

-----------------------------------

 

 

java 파일은

LoginActivity

LoginRequest

MainActivity

RegisterActivity

RegisterRequest 순서로 있어야 함

-----------------------------------

LoginActivity.java

package com.example.registerlogin;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

public class LoginActivity extends AppCompatActivity {
    private EditText et_id, et_pass;
    private Button btn_login, btn_register;

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

        et_id = findViewById(R.id.et_id);
        et_pass = findViewById(R.id.et_pass);

        btn_login = findViewById(R.id.btn_login);
        btn_register = findViewById(R.id.btn_register);

        // 회원가입 버튼 클릭 시 수행
        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // EditText에 현재 입력 되어있는 값을 가져온다
                String userID = et_id.getText().toString();
                String userPass = et_pass.getText().toString();

                Response.Listener<String> responseLintener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            boolean success = jsonObject.getBoolean("success");
                            if (success) { // 로그인에 성공한 경우
                                String userID = jsonObject.getString("userID");
                                String userPass = jsonObject.getString("userPassword");

                                Toast.makeText(getApplicationContext(), "로그인에 성공하였습니다", Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                intent.putExtra("userID", userID);
                                intent.putExtra("userPass", userPass);
                                startActivity(intent);
                            } else { // 로그인에 성공한 경우
                                Toast.makeText(getApplicationContext(), "로그인에 실패하였습니다", Toast.LENGTH_SHORT).show();
                                return;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };
                LoginRequest loginRequest = new LoginRequest(userID, userPass, responseLintener);
                RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
                queue.add(loginRequest);
            }
        });

    }
}

-----------------------------------

 

 

-----------------------------------

LoginRequest

package com.example.registerlogin;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

import java.util.HashMap;
import java.util.Map;

public class LoginRequest extends StringRequest {

    // 서버 URL 설정(php 파일 연동)
    final static private String URL = "http://khon01.dothome.co.kr/Login.php";
    private Map<String, String> map;

    public LoginRequest(String userID, String userPassword, Response.Listener<String> listener) {
        super(Method.POST, URL, listener, null);

        map = new HashMap<>();
        map.put("userID", userID);
        map.put("userPassword", userPassword);
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return map;
    }
}

-----------------------------------

 

 

-----------------------------------

MainActivity.java

package com.example.registerlogin;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView tv_id, tv_pass;

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

        tv_id = findViewById(R.id.tv_id);
        tv_pass = findViewById(R.id.tv_pass);

        Intent intent = getIntent();
        String userID = intent.getStringExtra("userID");
        String userPass = intent.getStringExtra("userPass");

        tv_id.setText(userID);
        tv_pass.setText(userPass);
    }
}

-----------------------------------

 

 

-----------------------------------

RegisterActivity.java

package com.example.registerlogin;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

public class RegisterActivity extends AppCompatActivity {

    private EditText et_id, et_pass, et_name, et_age;
    private Button btn_register;

    @Override
    protected void onCreate(Bundle savedInstanceState) { // 액티비티 시작시 처음으로 실행되는 생명주기
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        // 아이디 값 찾아주기
        et_id = findViewById(R.id.et_id);
        et_pass = findViewById(R.id.et_pass);
        et_name = findViewById(R.id.et_name);
        et_age = findViewById(R.id.et_age);

        // 회원가입 버튼 클릭 시 수행
        btn_register = findViewById(R.id.btn_register);
        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // EditText에 현재 입력 되어있는 값을 가져온다
                String userID = et_id.getText().toString();
                String userPass = et_pass.getText().toString();
                String userName = et_name.getText().toString();
                int userAge = Integer.parseInt(et_age.getText().toString());

                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            boolean success = jsonObject.getBoolean("success");
                            if (success) { // 회원등록에 성공한 경우
                                Toast.makeText(getApplicationContext(), "회원 등록에 성공하였습니다", Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                                startActivity(intent);
                            } else { // 회원등록에 성공한 경우
                                Toast.makeText(getApplicationContext(), "회원 등록에 싪패하였습니다", Toast.LENGTH_SHORT).show();
                                return;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };

                // 서버로 Volley를 이용해서 요청을 함
                RegisterRequest registerRequest = new RegisterRequest(userID, userName ,userPass, userAge, responseListener);
                RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
                queue.add(registerRequest);

            }
        });
    }
}

-----------------------------------

 

 

-----------------------------------

RegisterRequest.java

package com.example.registerlogin;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

import java.util.HashMap;
import java.util.Map;

public class RegisterRequest extends StringRequest {

    // 서버 URL 설정(php 파일 연동)
    final static private String URL = "http://khon01.dothome.co.kr/Register.php";
    private Map<String, String> map;

    public RegisterRequest(String userID, String userPassword, String userName, int userAge, Response.Listener<String> listener) {
        super(Method.POST, URL, listener, null);

        map = new HashMap<>();
        map.put("userID", userID);
        map.put("userPassword", userPassword);
        map.put("userName", userName);
        map.put("userAge", userAge + "");
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return map;
    }
}

'안드로이드 앱 만들기' 카테고리의 다른 글

BroadCastReceiver  (0) 2020.09.07
RelativeLayout (랠러티브레이아웃)  (0) 2020.09.06
Linear Layout (1)  (0) 2020.09.01
Button Selector  (0) 2020.08.30
Start Activity For Result  (0) 2020.08.30
Posted by khon98
,

LinearLayout - 층을 쌓아서 만들어 가는 개념

특징 - 기본적으로 orientation을 지정할 수 있음

orientation을 따로 지정해 주지 않으면 기본값은 horizontal이 됨

vertical(세로 방향) - 부모 태그를 감싸고 있는 LinearLayout은 세로 방향으로 흘러 가자 라는 뜻

horizontal(가로 방향) - 텍스트 뷰를 여려개 놨을 때 표시 되는 값이 가로 방향으로 가자 라는 뜻

 

match_parent - 부모의 크기 만큼 화면을 지원해라 라는 뜻

wrap_content - LInearLayout이 감싸고 있는 content만큼의 크기로 세로 조절 해라 라는 뜻

width - 가로

heigh - 세로

 

gravity 기본 값은 left

 

background - 컬러 코드, 레이아웃의 색상 변경이나 사진을 추가 함

 

레이아웃이나 특정 위젯의 길이를 지정 해줄때는 dp값을 사용

텍스트 뷰 같이 글짜 크기를 지정 할 때는 sp 사용

 

textStyle - 기본 값은 normal

 

----------------------------------

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:orientation="vertical"
    android:background="#A2FFE9"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:src="@mipmap/ic_launcher_round"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textColor="#165E7E"
            android:gravity="center"
            android:textSize="30sp"
            android:textStyle="bold|italic"
            android:text="khon"/>

        <ImageView
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:src="@mipmap/ic_launcher_round"/>

    </LinearLayout>

</LinearLayout>

'안드로이드 앱 만들기' 카테고리의 다른 글

RelativeLayout (랠러티브레이아웃)  (0) 2020.09.06
Login & Register  (0) 2020.09.02
Button Selector  (0) 2020.08.30
Start Activity For Result  (0) 2020.08.30
바텀 네비게이션 뷰(인스타 하단 바)  (0) 2020.08.29
Posted by khon98
,

iconfinder - 아이콘 이미지 다운로드하는 곳

 

우측 gradle 탭 옆에 Design에 들어가서 Palette 밑에 Button 끌어다 옮기기

Component Tree에 text view 삭제

Button 크기 조정 후 text 이름과 width 설정

 

-------------------------------

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="200dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="128dp"
        android:background="@drawable/selector_button"
        android:text="Button"
        android:textColor="#ffffff"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        tools:text="khon" />

    <Button
        android:id="@+id/button2"
        android:layout_width="128dp"
        android:layout_height="129dp"
        android:background="@drawable/selector_button_img"
        android:text=""
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.397" />

</androidx.constraintlayout.widget.ConstraintLayout>

-------------------------------

 

 

xml 파일 생성

-------------------------------

selector_button_img.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/no">

    </item>

    <item android:state_pressed="false" android:drawable="@drawable/mercy">

    </item>
</selector>

-------------------------------

 

 

xml 파일 생성

-------------------------------

selector_button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape>
            <solid android:color="#B0BCFF"/>
            <corners android:radius="10dp"/>
        </shape>
    </item>

    <item android:state_pressed="false">
        <shape>
            <solid android:color="#536DFE"/>
            <corners android:radius="10dp"/>
        </shape>
    </item>
</selector>

-------------------------------

'안드로이드 앱 만들기' 카테고리의 다른 글

Login & Register  (0) 2020.09.02
Linear Layout (1)  (0) 2020.09.01
Start Activity For Result  (0) 2020.08.30
바텀 네비게이션 뷰(인스타 하단 바)  (0) 2020.08.29
google map  (0) 2020.08.29
Posted by khon98
,

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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_comback"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:text="값을 가져와 주세요"/>

    <Button
        android:id="@+id/btn_go"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="go"/>

</LinearLayout>

--------------------------------

 

 

--------------------------------

MainActivity.java

package com.example.comeback;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private TextView tv_comback;
    private Button btn_go;

    private static final int REQUEST_CODE = 777; // 상수 값을 선언 (상수 - 항상 같은 수, 변하지 않을 수)

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

        tv_comback = findViewById(R.id.tv_comback);
        btn_go = findViewById(R.id.btn_go);

        btn_go.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), SubActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Toast.makeText(getApplicationContext(), "수신 성공", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "수신 실패", Toast.LENGTH_SHORT).show();
        }

        if (requestCode == REQUEST_CODE) {
            String resultTxt = data.getStringExtra("comback");
            tv_comback.setText(resultTxt);
        }

    }
}

--------------------------------

 

 

java 파일 생성

--------------------------------

SubActivity.java

package com.example.comeback;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class SubActivity extends AppCompatActivity {

    private EditText et_comback;
    private Button btn_close;

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

        et_comback  = findViewById(R.id.et_comback);
        btn_close = findViewById(R.id.btn_close);

        btn_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("comback", et_comback.getText().toString()); // 입력 폼에 적은 값 담아주기
                setResult(RESULT_OK, intent); // 결과 값 설정
                finish(); // 현재 액티비티 종료
            }
        });
    }
}

--------------------------------

 

 

--------------------------------

activity_sub.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"
    tools:context=".SubActivity">

    <EditText
        android:id="@+id/et_comback"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="Main으로 보낼 값을 입력해주세요"/>

    <Button
        android:id="@+id/btn_close"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="종료"/>

</LinearLayout>

--------------------------------

'안드로이드 앱 만들기' 카테고리의 다른 글

Linear Layout (1)  (0) 2020.09.01
Button Selector  (0) 2020.08.30
바텀 네비게이션 뷰(인스타 하단 바)  (0) 2020.08.29
google map  (0) 2020.08.29
뒤로가기 두번 눌러 앱 종료  (0) 2020.08.29
Posted by khon98
,

ConstraintLayout - 제약을 두는 레이아웃

 

아이콘 불러오기

1. drawable 폴더에서 마우스 우클릭

2. new에서 Vector Asset

3. Clip Art에서 이미지 선택

 

네비게이션 뷰와 프레임 레이아웃 설정

네비게이션 뷰

1. 우측 상단에 Design 탭 클릭

2. 좌측 Palette 있는 검색창에 bottomNavigationView 메인 화면으로 드래그

3. 맨 밑으로 옮기기

 

프레임 레이아웃

1. 우측 상단에 Design 탭 클릭

2. 좌측 Palette있는 검색창에 FrameLayout 메인 화면으로 드래그

 

---------------------------

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">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavi"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:itemIconTint="#CC3A3A"
        app:itemTextColor="#000000"
        app:layout_constraintBottom_toBottomOf="parent"
        app:menu="@menu/bottom_menu"
        tools:layout_editor_absoluteX="1dp" />

    <FrameLayout
        android:id="@+id/main_frame"
        android:layout_width="match_parent"
        android:layout_height="659dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0">

    </FrameLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

---------------------------

 

 

xml 파일 생성

---------------------------

farg1.xml

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1번화면 입니다"
        android:textSize="40sp"/>

</LinearLayout>

같은 xml 파일 4개 생성 후 1번 화면 입니다를 각 번호로 바꾸기

---------------------------

 

 

---------------------------

MainActivity.java

package com.example.bottomnavi;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.view.MenuItem;

import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MainActivity extends AppCompatActivity {

    private BottomNavigationView bottomNavigationView; // 바텀 네비게이션 뷰
    private FragmentManager fm;
    private FragmentTransaction ft;
    private Frag1 frag1;
    private Frag2 frag2;
    private Frag3 frag3;
    private Frag4 frag4;
    private Frag5 frag5;

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

        bottomNavigationView = findViewById(R.id.bottomNavi);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.action_airplane:
                        setFrag(0);
                        break;
                    case R.id.action_bike:
                        setFrag(1);
                        break;
                    case R.id.action_favorite:
                        setFrag(2);
                        break;
                    case R.id.action_navigation:
                        setFrag(3);
                        break;
                    case R.id.action_policy:
                        setFrag(4);
                        break;

                }
                return true;
            }
        });
        frag1 = new Frag1();
        frag2 = new Frag2();
        frag3 = new Frag3();
        frag4 = new Frag4();
        frag5 = new Frag5();
        setFrag(0); // 첫 fragment 화면을 무엇으로 지정해줄 것인지 선택
    }

    // fragment 교체가 일어나는 실행문
    private void setFrag(int n) {
        fm = getSupportFragmentManager();
        ft = fm.beginTransaction();
        switch (n) {
            case 0:
                ft.replace(R.id.main_frame, frag1);
                ft.commit();
                break;
            case 1:
                ft.replace(R.id.main_frame, frag2);
                ft.commit();
                break;
            case 2:
                ft.replace(R.id.main_frame, frag3);
                ft.commit();
                break;
            case 3:
                ft.replace(R.id.main_frame, frag4);
                ft.commit();
                break;
            case 4:
                ft.replace(R.id.main_frame, frag5);
                ft.commit();
                break;
        }
    }

}

---------------------------

 

 

java 파일 생성

---------------------------

Frag1.java

package com.example.bottomnavi;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class Frag1 extends Fragment {

    private View view;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.frag1, container, false);

        return view;
    }
}

같은 자바 파일 4개 생성후 (R.layout.frag1, container, false) 이 부분에 frag1을 각 번호로 바꾸기

---------------------------

'안드로이드 앱 만들기' 카테고리의 다른 글

Button Selector  (0) 2020.08.30
Start Activity For Result  (0) 2020.08.30
google map  (0) 2020.08.29
뒤로가기 두번 눌러 앱 종료  (0) 2020.08.29
mp3  (0) 2020.08.29
Posted by khon98
,

1. 구글맵 콘솔 검색

 

2. Maps SDK for Android 클릭

사용 클릭

 

3. 좌측에 사용자 인증 정보 클릭

API 및 서비스의 사용자 인증 정보 클릭

사용자 인증 정보 만들기 클릭

API 키 클릭

키 제한 클릭

 

4. 애플리케이션 제한사항에서 Android 앱 체크

 

5. Android 앱의 사용량 제한

패키지 이름 설정

- 안드로이드 스튜디오 MainActivity.java 파일에서 패키지 이름을 복사 (package com...... 으로 시작되는 코드)

 

6. SHA1 지문 추가

CMD 실행 > SHA1 서명 인증키 받는 커맨드 입력

- CMD(명령프롬프트 창)에서 SHA1 서명 인증키 받는 커맨드

"C:\Program Files\Android\Android Studio\jre\bin\keytool" -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

 

7. API 제한사항에서 키 제한 체크

Maps SDK for Android 선택

 

8. API Key 복사

 

9. 저장

 

10. 메타 데이터 추가

AndroidManifest.xml

<meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyDfqqusA5ZcIevs9TyBCpuRMmJq-uAd-iA"/> // API 키 복사한거 붙여넣기

 

11. Google Play services 라이브러리 패키지 설치

안드로이드 스튜디오 상단 메유에 Tools 클릭

SDK Manager 클릭

SDK Tools 에서 Google Play services 체크 후 Apply 클릭하고 설치

 

------------------------------------

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"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/googlemap"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.MapFragment"/>

</LinearLayout>

------------------------------------

 

 

------------------------------------

MainActivity.java

package com.example.googlemap;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;


import android.app.FragmentManager;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {

    private FragmentManager fragmentManager;
    private MapFragment mapFragment;


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

        fragmentManager = getFragmentManager();
        mapFragment = (MapFragment)fragmentManager.findFragmentById(R.id.googlemap);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        LatLng location = new LatLng(46.057171, 14.505591); // 류블랴나
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.title("류블랴나");
        markerOptions.snippet("해외");
        markerOptions.position(location);
        googleMap.addMarker(markerOptions);

        // googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 16));
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(location, 16));
    }
}

------------------------------------

 

 

------------------------------------

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.googlemap">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyDfqqusA5ZcIevs9TyBCpuRMmJq-uAd-iA"/>

    </application>

</manifest>

------------------------------------

 

 

------------------------------------

build.gradle (:app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.1"

    defaultConfig {
        applicationId "com.example.googlemap"
        minSdkVersion 28
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
    implementation 'com.google.android.gms:play-services-maps:17.0.0'
    implementation 'com.google.android.gms:play-services-location:17.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

}

'안드로이드 앱 만들기' 카테고리의 다른 글

Start Activity For Result  (0) 2020.08.30
바텀 네비게이션 뷰(인스타 하단 바)  (0) 2020.08.29
뒤로가기 두번 눌러 앱 종료  (0) 2020.08.29
mp3  (0) 2020.08.29
로딩화면 만들기  (0) 2020.08.28
Posted by khon98
,

MainActivity.java

package com.example.backbutton;

import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    /* back 버튼을 눌렀을때 타임을 0으로 설정
    long은 int보다 자료 데이터가 더 긴 형태 */
    private long backBtnTime = 0;

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

    /* super.onBackPressed를 타게 되면 실제로 back 버튼을 눌렀을때 super.onBackPressed에 의해서
    뒤로가기 활성화가 됨 */
    @Override
    public void onBackPressed() {
        long cutTime = System.currentTimeMillis();
        long gapTime = cutTime - backBtnTime; // 현재 시간을 가져와서 back 버튼을 누른 시간을 빼줌

        // 0이 gatTime보다 작거나 같고 gapTime이 2000(mil)보다 작거나 같을때
        if (0 <= gapTime && 2000 >= gapTime) {
            super.onBackPressed();
        }
        // 만약 저 경우의 수가 아니라면 backbBtnTime은 현재시간으로 됨
        else {
            backBtnTime = cutTime;
            Toast.makeText(this, "한번 더 누르면 종료 됩니다.", Toast.LENGTH_SHORT).show();
        }
    }
}

'안드로이드 앱 만들기' 카테고리의 다른 글

바텀 네비게이션 뷰(인스타 하단 바)  (0) 2020.08.29
google map  (0) 2020.08.29
mp3  (0) 2020.08.29
로딩화면 만들기  (0) 2020.08.28
Spinner 드롭 다운  (0) 2020.08.28
Posted by khon98
,