Hello! 안드로이드

출처

정재곤, 『Do it! 안드로이드 앱 프로그래밍 - 개정 4판』, 이지스퍼블리싱(주)(2017-06-26), 15-126p

http://prolite.tistory.com/975

http://webnautes.tistory.com/1126

https://blog.naver.com/PostView.nhn?blogId=rkdwnsdud555&logNo=220283517171&proxyReferer=https%3A%2F%2Fwww.google.co.kr%2F


01 안드로이드란?

01-1 안드로이드에 대한 이해

안드로이드

  • 구글(Google)에서 만든 스마트폰용 운영체제
  • 아이폰과 마찬가지로 정전 방식 터치 패널 구조를 선택하여 사용자 친화적

01-2 안드로이드의 특징

안드로이드 OS의 주요 특징

  • 오픈 소스
  • 자바 개발 언어
  • 스마트폰을 위한 완벽한 컴포넌트 제공
  • 쉬운 앱 간 연동
  • 다양한 기능 지원
  • ART라는 런타임(Runtime)이 탑재

01-3 안드로이드의 흐름

전 세계 스마트폰 OS 시장 중 안드로이드의 점유율이 ㅅㅌㅊ


01-4 안드로이드의 현재

빠르게 버전이 바뀌고 있음

에코 시스템(Eco System)

  • 단말 OS, 단말 제조사, 이동통신사 그리고 애플리케이션 개발자 등 각 역할을 담당하는 참여자들을 하나로 묶어주는 생태계

02 개발 환경 구축하기

자바 설치 –> 안드로이드 스튜디오 설치 –> SDK 매니저로 플랫폼 추가 설치

  1. 자바 설치과정
  2. 안드로이드 설치과정

03 첫 번째 앱 만들기

03-1 첫 프로젝트 만들기

1. 안드로이드 스튜디오 실행

image

2. Start a new Android Studio prjoect –> Hello

image

3. Phone and Tablet, Minimum SDK 항목 확인

image

4. Empty Activity 선택

image

5. Finish

image

6. 만들어진 Hello 프로젝트

image

7. activity_main.xml 탭 선택

image


에뮬레이터 만들기

1. 툴바에서 AVD Manager 클릭

image

2. Create Virtual Device… 클릭

image

3. Nexus 5 선택

image

4. System Image 선택(책은 Nougat이지만 나는 Oreo를 택함)

image

5. 최종 입력 정보 확인 화면

image

6. 새로 추가된 에뮬리에터가 보이는 AVD Manager –> 실행 아이콘 클릭

image

7. 실행 화면

image

8. 표시된 아이콘 클릭 혹은 Shift + F10으로 Hello앱 실행

image image


첫 번째 앱 뜯어보기

1. MainActivity.java 탭 열기 –> main 함수가 없음

image

package com.example.kai01.hello;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

2. app–>res–>layout–>activity_main.xml 선택

image

3. 하단의 Design, Text 탭에 따라 보이는 내용이 다름

image image

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:layout_width="wrap_content"
        android:layout_height="16dp"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

03-2 하나씩 바꾸어 보기

activity_main.xml에서
android:text="Hello World"
android:text="안녕 안드로이드!"로 변경

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:layout_width="wrap_content"
        android:layout_height="16dp"
        android:text="안녕 안드로이드!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Shift + F10으로 실행

image

위 예시는 activity_main.xmlTextView태그를 조작한 예시
이번엔 TextViewButton으로 바꿈

버튼 높이가 너무 작아
android:layout_height="16dp"
andorid:layout_height="wrap_content"로 바꿨음

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="안녕 안드로이드!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Shift + F10으로 실행

image

버튼에 이벤트 넣는 과정

  1. XML 레이아웃 파일의 버튼에 onClick 속성 값 넣기
  2. 자바 파일에 이벤트 처리 메소드 추가하기

XML 레이아웃 파일의 버튼에 onClick 속성 값 넣기

1. activity_main.xml에서 Design탭 누르기

image

2. 스마트폰 화면에 있는 버튼 선택하기

image

3. 버튼 선택으로 나온 오른쪽 Properties 영역의 onClick 속성 확인

image

4. onClick 속성의 값으로 ‘onButton1Clicked’입력

image

–> 버튼이 클릭되었을 때 onButton1Clicked라는 함수를 실행하라는 의미

5. Text탭을 눌러 XML 코드가 변경된 것을 확인

image

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onButton1Clicked"
        android:text="안녕 안드로이드!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

자바 파일에 이벤트 처리 메소드 추가하기

1. MainActivity.java탭 열기

image

package com.example.kai01.hello;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

2. onCreate() 메소드 밑에 onButton1Clicked() 메소드 추가

image

package com.example.kai01.hello;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

public void onButton1Clicked(View v) {
  Toast.makeText(getApplicationContext(), "시작 버튼이 눌렸어요.", Toast.LENGTH_LONG).show();
  }
}

3. Toast에 뜬 빨간 줄을 Alt + Enter 키를 눌러 없애주기

image

4. Shift + F10으로 실행하고 버튼 클릭하기

image


03-3 여러 개의 버튼에 기능 추가하기

1. 안녕 안드로이드! 버튼 누른 후 키보드 delete 버튼

image

2. Palette 영역에서 버튼을 끌어다 왼쪽 상단에 추가

image

3. 추가된 버튼을 선택한 후 오른쪽 Properties에서 text 속성에 ‘네이버 접속하기’ 입력

4. onClick 속성을 찾고 ‘onButton1Clicked` 입력

image

5. 버튼 하나 더 추가하고 text 속성에는 ‘전화 걸기’, onClicked 속성에는 onButton2Clicked 입력

image

6. 버튼 이벤트를 자바 코드에 추가하기

image

package com.example.kai01.hello;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

    public void onButton1Clicked(View v) {
        Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://m.naver.com"));
        startActivity(myIntent);
    }

    public void onButton2Clicked(View v) {
        Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:010-1000-10000"));
        startActivity(myIntent);
    }
}

7. Shift + F10으로 실행결과 확인

혹시 실행했을 때 버튼이 겹친다면

image

ConstraintLayout이 default이므로 각 버튼의 동그란 부분을 위 그림과 같이 연결해야 함

네이버 접속하기 버튼 눌렀을 때

image

전화 걸기 버튼 눌렀을 때

image

인텐트

  • 안드로이드 플랫폼에게 원하는 것을 말할 때 전달하는 우편물
  • 02-3절에 나올 예정

03-4 새로운 화면 추가한 후 띄워주기

1. 메뉴에서 app 항목 선택 후 오른쪽 마우스 버튼 클릭 후 New–>Activity–>Empty Activity 메뉴 선택

image

2. Activity Name을 MenuActivity로 바꾸기

image

3. activity_menu 파일 열고 화면 가운데에 버튼 추가 후 Properties 창에서 text는 ‘돌아가기’ onClick은 ‘onBackBUttonClicked 입력

image

4. MenuActivity.java에서 onBackuButtonClicked() 메소드 추가하기

image

package com.example.kai01.hello;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MenuActivity extends AppCompatActivity {

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

    public void onBackButtonClicked(View v) {
        Toast.makeText(getApplicationContext(), "돌아가기 버튼을 눌렀어요.", Toast.LENGTH_LONG).show();
        finish();
    }
}

5. manifests 폴더 안 AndoridManifest.xml 내용 확인

image

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

    <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>
        <activity android:name=".MenuActivity"></activity>
    </application>

</manifest>

<activity android:name=".MenuActivity"></activity>가 추가됐음을 확인

6. activity_main.xml에서 “새 화면 띄우기” 버튼 추가하고 onClick은 onButton3Clicked를 입력하기

image

7. MainActivity.java에서 onButton3Cliced() 메소드 추가하기

image

package com.example.kai01.hello;

        import android.content.Intent;
        import android.net.Uri;
        import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

    public void onButton1Clicked(View v) {
        Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://m.naver.com"));
        startActivity(myIntent);
    }

    public void onButton2Clicked(View v) {
        Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:010-1000-10000"));
        startActivity(myIntent);
    }

    public void onButton3Clicked(View v) {
        Intent intent = new Intent(getApplicationContext(), MenuActivity.class);
        startActivity(intent);
    }
}

8. Shift + F10으로 실행결과 확인

image

새 화면 띄우기 버튼 눌렀을 때

image

돌아가기 버튼 눌렀을 때

image


03-5 새로운 프로젝트를 만들 때 다른 종류의 화면 선택해 보기

1. File–>Close Project 선택

2. Start a new Android Studio Project 선택

3. Application name은 Hello5 Company Domain은 그대로

image

4. Add an Activity to Mobile에서 Basic Activity 선택 이후 Finish

image

5. /res/layout 폴더에 XML이 두 개인 것 확인

image

activity_main.xmlcontent_main.xml

6. MainActivity.java에 코드가 더 추가된 것을 확인

image

package com.example.kai01.hello5;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

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

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

        return super.onOptionsItemSelected(item);
    }
}

7. 한 번 실행해보기

image

8. 같은 방법으로 Navigation Drawer Activity를 이용한 Hello6 프로젝트 만들고 살펴보기

만들어보면 XML파일이 네 개고 실행하면 슬라이딩 방식 메뉴가 나옴

image


04 안드로이드 프로젝트와 개발 도구

04-1 안드로이드 최근 버전의 주요 특징

알기 싫으니 Skip

04-2 안드로이드 프로젝트

/java

  • 자바 소스 파일이 들어 있는 폴더
  • /app/src/main 폴더 안에 있음
  • 패키지명과 동일한 하위 폴더들이 만들어짐

/res

  • 리소스 파일이 들어 있는 폴더
  • /app/src/main 폴더 안에 있음
  • XML 레이아웃, 그림 파일, 문자열을 정의한 XML 파일 등이 들어 있음
  • 각 파일의 유형에 따른 하위 폴더들이 만들어져 있음

–> 예: XML 레이아웃 파일은 res/layout 폴더, 그림 파일은 /res/drawable 폴더, 문자열을 정의한 XML 파일은 /res/values 폴더

/build

  • 개발 환경이 자동으로 만들어 내는 소스 파일이 들어가는 폴더
  • 프로젝트 폴더 아래에도 있고 /app 폴더 안에도 있음

/assets

  • 이 폴더는 처음부터 만들어지지 않음
  • 이 폴더에 넣어서 처리하는 파일들을 저장함(동영상 파일)

AndroidManifest.xml

  • 앱에 대한 정보를 담고 있는 파일
  • /app/src/main 폴더 안에 있음
  • 매니페스트라고 부르며 애플리케이션 구성 요소나 권한 등의 정보를 정의함

/java, /res 폴더와 Android Manifest.xml를 자주 씀

소스 파일이 프로젝트로 묶여 빌드되기까지

자바 코드 + 리소스 + 매니페스트 = 하나의 앱

그레이들(gradle)

빌드 과정을 자동으로 진행하며 코드나 리소스 정보가 바뀔 때마다
자동으로 빌드 결과를 만들어 냄

apk

배포를 위해 만들어진 파일의 확장자
패키징(Packaging)과정이 끝나면 만들어지며 플랫폼에 설치하면 런타임에서 실행

안드로이드 스튜디오에서 앱 작성 –> 자바에서 빌드(컴파일)

–> 바이트코드로 변환 및 패키징 –> 안드로이드 커널(LINUX)안 ART 런타임에서 실행

상세 빌드 과정

1. 안드로이드 스튜디오 + 안드로이드 SDK 사용 –> 프로젝트 구성 단계

XML 레이아웃을 만들고 자바 코드를 구성한 후
매니페스트 파일을 편집하는 과정을 포함

2. javac 컴파일러를 이용해 클래스 파일로 컴파일

‘class’확장자를 가진 자바 클래스 파일은 안드로이드의 기본 라이브러리에 종속적

3. 컴파일된 자바 클래스 파일을 dx를 이용해 dex 파일로 만들고

리소스 파일은 필요한 경우 바이너리 파일로 빌드

4. dex 파일과 리소스 파일들은 설치할 수 있는 apk 파일로 만들어짐

–> aapt 개발 도구 이용

개발 단계에서는 인증을 위한 서명이 필요하지 않아 unsigned 상태로 테스트
마켓에 올릴 땐 jarsigner를 이용해 signed 상태로 만들어야 함

5. 다른 사람의 소스파일을 빌드할 때 오류가 발생하는 경우

Gradle Scirpts 폴다 안의 build.gradle(Module:app) 파일 설정 정보 문제

image

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.kai01.hello6"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support:design:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

compileSdkVersion

컴파일할 때에 사용할 SDK 버전을 지정

buildToolsVersion

빌드 도구의 버전
SDK 매니저에서 설치한 Tools의 항목 중
Android SDK Build-tools 모듈의 버전과 일치해야 함

minSdkVersion

프로젝트가 지원하는 최소 SDK 버전을 지정
값이 15라면 API 버전이 15 이전의 단말에서는 앱이 동작 하지 않음

targetSdkVersion

실행을 위해 검증한 SDK가 어떤 것인지를 지정
값이 달라도 실행할 수 있으나 SDK 매니저에는 해당 버전이 있어야 함

__appcomat…

dependencies 안에 들어 있는 항목들 중 하나 예전 단말들을 지원하기 위해 있음


04-3 안드로이드 SDK의 개발 도구

Tools –> Android 메뉴를 눌러서 확인

UI 뷰어

디버그 브리지(Android Debug Bridge, ADB)

나인패치 그리기 도구(Draw 9-Patch)

안드로이드 디바이스 모니터(Android Device Monitor)

요즘 안 씀

그냥 스킵함

05 앱 장터, Play 스토어에 앱 등록하기

스킵

06 실제 단말 연결하기

단말 연결하기

Comments