hello 디바이스 만들기
프로그래밍 첨하면 아무나 다하는 hello.c를 만들어 보겠다.

#include <linux/init.h>

#include <linux/module.h>

MODULE_LICENSE("Dual BSD/GPL");


static int __init hello_init(void) {

        printk(KERN_ALERT "Hello, world\n");

        return 0;

}

static void __exit hello_exit(void) {

        printk(KERN_ALERT "Goodbye, world\n");

}

module_init(hello_init);

module_exit(hello_exit);

뭐하는 설명 안해도 다 알만한 프로그램이다.
여기서 기존의 프로그램과 다른점은 printf 대신 printk 를 썻다는 것이다.
저 코드들은 커널 에서 실행되기때문에 유저스페이스의 함수를 사용할 수 없다.
그래서 stdio 같은것들을 인클루드 하면 안된다. 모두 커널상의 함수를 사용해야한다.
printk 역시 커널 함수로 printf와 거의 유사한 기능을 한다.

중간에 __init 과 __exit 가 좀 수상쩍어 보인다.
이것은 필수는 아니지만 써주는게 좋다. 그 이유는 커널에게 시작할때 한번 끝날때 한번 실행하는 함수라고 알려서 실행되고 바로 메모리에서 삭제하도록 할 수있다.

MODULE_LICENSE 는 라이센스를 지정하는 부분인데 이부분이 재미있다.
여기에 들어갈 수 있는 스트링은 아래와 같다.

"GPL"  ,  "GPL v2"  ,  "GPL and additional rights"  ,  "Dual BSD/GPL"  ,  "Dual MPL/GPL"

"Proprietary"

 사실 MODULE_LICENSE 는 옵션이다. 그러나 지정하지 않은 모듈을 적재시 "오염 상태" 가 된다.

makefile 만들기

KERNELDIR ?= /lib/modules/$(shell uname -r)/build

PWD := $(shell pwd)

obj-m := hello.o


default:

        $(MAKE) -C $(KERNELDIR) M=$(PWD) modules


clean:

        rm *.ko *.o Module.* modules.* *.mod.c

KERNELDIR 에는 커널헤더 경로가 들어가기 때문에 위와 같은 명령을 사용하면 헤더의 경로를 가져올 수 있다.
자 이제 make 를 실행해 보자.

root@cranix-desktop:~/work/drivers# make

make -C /lib/modules/2.6.31-20-generic-pae/build M=/root/work/drivers modules

make[1]: Entering directory `/usr/src/linux-headers-2.6.31-20-generic-pae'

  CC [M]  /root/work/drivers/hello.o

  Building modules, stage 2.

  MODPOST 1 modules

  CC      /root/work/drivers/hello.mod.o

  LD [M]  /root/work/drivers/hello.ko

make[1]: Leaving directory `/usr/src/linux-headers-2.6.31-20-generic-pae'

위와 같이 나오면 제대로 컴파일 된 것이고 hello.ko 파일이 생겼을 것이다.
ko 란 커널 오브젝트의 약자로서 2.6 넘어오면서 커널오브젝트와 다른 오브젝트를 구분하기위해 생긴것이다.


hello 디바이스 적재및 삭제

root@cranix-desktop:~/work/drivers# insmod hello.ko

root@cranix-desktop:~/work/drivers# lsmod |grep hello

hello                   1052  0

root@cranix-desktop:~/work/drivers# rmmod hello

root@cranix-desktop:~/work/drivers# lsmod |grep hello

root@cranix-desktop:~/work/drivers#  

위와같이 디바이스 드라이버는 insmod 와 rmmod 로 적재와 삭제를 하고 lsmod 로 리스트를 볼 수 있다.



커널로그 보기
분명 적재는 했는데 printk 로 출력한 메시지는 어떻게 볼 수 있을까?

root@cranix-desktop:~/work/drivers# dmesg

...

...

[ 2747.649737] Hello, world

[ 2759.753311] Goodbye, world

메시지가 쭈욱 나오는데 제일 아래보면 원하던 메시지를 볼 수 있을 것이다.



by cranix 2010. 3. 18. 23:50

curl 로 repo 스크립트 받기

안드로이드는 수많은 개발자가 참여하는 오픈소스 시스템이다.

이러한 시스템을 관리해주는 유틸은 git 를 사용하는데 그러다 보니 전체 소스가 한꺼번에 관리되지 않는다.

그래서 웹상에 소스를 한꺼번에 다운로드 받을수 있는 스크립트를 작성해 놓고 curl 로 다운받아가게 한 것이다.

# apt-get install curl

# curl http://android.git.kernel.org/repo >repo

# chmod 755 repo

이제 repo 라는 스크립트가 생겼을 것이다.

편하게 하기위해서는 repo 가 있는 디렉토리를 PATH 로 잡아놓으면 된다.

 

 

repo 를 사용해서 소스받기

repo 는 결국 git 를 사용하기 때문에 git 를 먼저 설치해야 한다.

 # apt-get install git-core

git-core 가 없다면 repo 를 실행했을때 "No such file or directory" 오류가 떨어질 것이다.

 

repo 를 이용해서 다운받으려면 init 과 sync 옵션을 사용하면 된다.

# mkdir android_src

# cd android_src

# repo init -u git://android.git.kernel.org/platform/manifest.git

# repo sync

repo 를 실행하기 전에 먼저 소스가 저장될 디렉토리를 만들고 그안에서 init 과 sync 작업을 하도록 하자.

repo init 옵션은 마지막에 -b (branch) 옵션으로 원하는 버전의 소스를 받을수 있다. 위 처럼 아무것도 안쓴다면 최신버전을 다운받게 된다.

그리고 init 을 실행 할 때 이름, 메일주소 등을 물어보는데 적당히 적어주면 된다.

init 작업은 실제로 소스를 다운받지 않기 때문에 빠른 시간안에 끝난다. sync 에서 비로소 소스를 다운받기 때문에 상당히 시간이 걸린다. 인터넷이 빨라도 최소한 한시간은 잡아야 한다.

 

by cranix 2010. 3. 18. 10:35
들어가며
어제 새벽까지 설치하고 일하러 갔더니 완전 제정신이 아니었다.
오늘은 얼른하고 자야겠다.
일단 오늘 할것을 생각해 보자.

  폰트, vim, eclipse, ...


폰트셋팅
처음 우분투 설치할때는 폰트가 맘에든다고 생각했지만,
계속 쓰다보니 별로 맘에 안들었다.
일단 터미널 폰트부터 바꿔보자.
폰트는 한컴에서 만든 네이버사전체와 고정폭 Lucida Sans Typewriter 폰트를 받도록 하자.

 함초롬체 : http://www.haansoft.com/hnc/event/ham/index.htm

 네이버사전체 : http://cndic.naver.com/static/fontInstall

 고정폭 Lucida Sans Typewriter 체 : # apt-get install sun-java6-fonts

다 받았으면 아래와 같이 폰트 디렉토리의 truetype 디렉토리에 회사별로 디렉토리를 만들고 ttf 파일을 이동시키자.
일단 아래와같이 폰트에 디렉토리를 만들고 폰트캐시를 업데이트 하자.

 # mkdir /usr/share/fonts/truetype/han

 # mv *.ttf /usr/share/fonts/truetype/han

 # fc-cache -v

그럼 이제 폰트를 바꿔보자.
시스템전체의 글꼴을 설정하려면 아래 메뉴로 가서 변경하자.

 시스템 -> 기본설정 -> 모양새 -> 폰트


VI 셋팅
일단 VI 는 먼저 vim 을 설치하도록 하자.
그다음 홈 디렉토리 아래에 .vimrc 파일을 만들고 아래와 같이 저장하자.

set autoindent          "자동 들여쓰기

set cindent             "C 프로그래밍 할때 자동으로 들여쓰기

set smartindent         "좀 더 똑똑한 들여쓰기

set nobackup            "백업파일을 만들지 않는다.

set number              "라인번호를 출력한다.

"폰트 설정

set fenc=utf-8

set fencs=utf-8,cp949,cp932,euc-jp,shift-jis,big5,latin1,ucs-2le

set nocp                " vi 와 호환성을 없애고 vim 만 쓸수있게


filetype on  "파일 종류를 자동으로 인식

set ru "커서의 위치를 항상 보이게함

set sc "완성중인 명령을 표시


set background=dark

colorscheme elflord

filet plugin indent on "파일종류 자동으로 인식

syntax on "알아서 하이라이팅

set title "제목표시

set novisualbell

set hlsearch "검색어 하이라이트

set wmnu "탭 누르면 자동완성 가능한 목록 나옴


if has("gui_running") "gui 시작이면 시작시 크기 설정

   set lines=50

   set co=125

endif

참고로  /etc/skel 디렉토리는 사용자가 생성될 때마다 복사하기 때문에 거기에 .vimrc 를 옮겨놓으면 나중에 편해진다.


오픈오피스 글자 깨지는거 수정
오픈오피스를 켰더니 글자가 깨져서 얼마전에 내가 적었던 포스트를 검색해서 수정했다.
이 블로그에서 "오픈오피스" 로 검색하면 나올것이다.


마치며
얼른 하려고 했는데 또 한시가 넘어버렸다.ㅜ
내일은 이클립스 설정이나 해야겠다.

by cranix 2010. 3. 18. 00:19

 

리눅스 관련해서 작업할 일이 점점 많아지다 보니 리눅스의 필요성을 느꼈다.

그래서 설치하기로 마음먹었다.

 

하드디스크 정리

일단 용량이 있어야 설치를 하니까 가장 먼저 하드디스크 정리를 했다.

약 100기가 정도의 용량을 확보했다.

 

 

파티션 매직 프로그램으로 파티션 변경

다음은 리눅스에서 쓰게하기 위해서 남은 용량파티션을 삭제할 필요가 있었다.

이것은 파티션 매직이라는 프로그램으로 했었는데 유료 라서 무료 프로그램을 찾다보니 파티션 마스터 라는 프로그램이 검색되었다.

홈페이지는 아래와 같다.

http://www.easeus.com/download.htm

설치하고 파티션을 설정후 재부팅 하면 되는데 재부팅시에 상당히 오래걸렸다.

 

 

USB메모리로 우분투 설치하기

CD 롬을 지금 구할수 없기에 USB 메모리로 우분투를 설치하기로 하였다.

구글링 결과 아래 사이트를 발견했다.

http://myubuntu.tistory.com/entry/904-우분투-USB드라이브에-이식해서-설치하기

나와 같은 생각을 하는사람이 많나보다.

전용 프로그램까지 존재하니까 말이다.

UNetbootin 이라는 프로그램인데 아래 사이트에서 찾을 수 있다.

http://unetbootin.sourceforge.net/

 

일단 UI 는 맘에 든다.

 

그러나 이거 역시 시간이 좀 오래걸린다.

원래 USB 보다 씨디롬이 빨랐던가?

얼른 우분투가 뜨는 모습을 보고 싶지만 오늘은 이만 접어야겠다.

내일 회사가야 하니까.


설치완료

지금은 새벽 2시.

내일 회사가야 하지만 깔고 싶은 마음이 더 컸다.ㅜㅜ

그래도 결과는 성공적이다.

처음에 바이오스 부팅이 안되는줄 알았는데 이상하게 내 바이오스는 F8 을 눌러줘야지 부팅선택 화면이 나와서 USB 로 부팅할수 있게 되어있다.

부팅하니 바로 UNetbootin  화면이 뜨면서 설치가 된다.


결국 우분투 부팅화면까지 보고야 말았다.

이제 진짜 자야지.


'알짜정보 > Linux server' 카테고리의 다른 글

cent os java 설치  (56) 2011.01.02
cent os 기본정보 확인  (24) 2010.12.30
ubuntu 터미널 한글깨질때  (749) 2010.02.01
ubuntu 오픈오피스 글자 깨질때  (787) 2010.02.01
fedora 10 에다가 vncserver 설치하기 (수정)  (31) 2009.08.10
by cranix 2010. 3. 17. 01:28
1. 커널 다운로드

# git clone git://android.git.kernel.org/kernel/common.git kernel_goldfish

# cd kernel_goldfish

# git checkout --track -b android-goldfish-2.6.29 origin/android-goldfish-2.6.29

# git branch

 
2. 컴파일 하기

 # make goldfish_defconfig ARCH=arm

# vi Makefile 아래 수정

  193   ARCH := arm

  194   CROSS_COMPILE  := [안드로이 sdk 경로]/prebuilt/linux-x86/toolchain/arm-eabi-4.2.1/bin/arm-eabi-

# make zImage

 

'알짜정보 > Android' 카테고리의 다른 글

안드로이드 소스 컴파일 하기  (48) 2010.03.21
android 소스 다운로드 받기  (40) 2010.03.18
android 커널부팅부터 액티비티까지  (21) 2010.03.12
AlertDialog 와 Toast  (45) 2010.03.01
SharedPreferences  (1016) 2010.03.01
by cranix 2010. 3. 16. 20:04
안드로이드는 커널 부팅후 /init 을 실행해 준다.
그 후 부터 home activity 가 뜰때까지의 과정을 분석해 보았다.

kernel boot
init.c:main() - init process 실행
app_main.cpp:main() - zygote service 실행
AndroidRuntime.cpp:start() - java VM 실행
ZygoteInit.java:main()
SystemServer.java:main()
system_init.cpp:system_init()
SystemServer.java:init2()
ServerThread.run()
ActivityManagerService.java:startRunning()
systemReady()
resumeTopActivityLocked()
startHomeActivityLocked()
startActivityLocked()

- system_init.cpp 의 main() 에서는 SurfaceFlinger, AudioFlinger, MediaPlayerService, CameraService, AudioPolicyService 등 C++ 과 연동되어진 서비스들이 실행된다.

- SystemServer.java:ServerThread.run() 에서는 안드로이드 프레임웍 자바단에서 쓰이는 모든 서비스가 실행 및 등록 된다.

'알짜정보 > Android' 카테고리의 다른 글

android 소스 다운로드 받기  (40) 2010.03.18
goldfish 커널 다운로드 및 컴파일 하기  (818) 2010.03.16
AlertDialog 와 Toast  (45) 2010.03.01
SharedPreferences  (1016) 2010.03.01
Activity 간의 통신  (121) 2010.02.25
by cranix 2010. 3. 12. 11:39
- 현 리눅스의 커널버젼 알아보기
- # uname -r

- 우분투에서 apt-cache 으로 현재의 리눅스 커널 소스를 검색하기
- # apt-cache search linux-source-*

- 우분투에서 apt-get 으로 검색한 커널 설치하기
- # apt-get install linux-source-2.6.xxxx..

- 받아진 커널 소스 압축풀기
- /usr/src 디렉토리 안에 커널소스 파일이 들어있다.
- ex) # tar -xjf linux-source-2.6.31.tar.bz2

- 커널 컴파일 하기
- # make menuconfig 명령으로 커널설정을 먼저 한다.
- # make

by cranix 2010. 3. 3. 09:12

이번 포스트에서는 안드로이드에서 쉽게 메시지를 보여 줄 수 있는 두 가지 클래스에 대해서 알아 도록 하겠다.

프로그램은 아래와 같다.

이 프로그램은 AlertDialog 와 Toast 메시지를 띄우는 프로그램이다.

 

먼저 레이아웃 소스를 보자.

 

- main.xml

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

    <Button android:layout_height="wrap_content" android:id="@+id/dialogBtn"
        android:layout_gravity="center" android:layout_width="200px"
        android:text="AlertDialog"></Button>
    <Button android:layout_height="wrap_content"
        android:layout_gravity="center" android:layout_width="200px"
        android:id="@+id/toastBtn" android:text="Toast"></Button>

</LinearLayout>

 

 

다음은 Activity 소스를 보자.

 

- MainActivity.java

package net.cranix.android.uitest;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button dialogBtn = (Button)findViewById(R.id.dialogBtn);
        dialogBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
                alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.i(getResources().getString(R.string.app_name), "OK");
                    }
                });
                alertDialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.i(getResources().getString(R.string.app_name), "CANCEL");
                    }
                });
                alertDialog.setTitle("alert");
                alertDialog.setMessage("testMessage");
                alertDialog.show();

            }           
        });
        Button toastBtn = (Button)findViewById(R.id.toastBtn);
        toastBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "toast!", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

 

 

AlertDialog 는 생성자가 protected 로 되어있다. 그래서 해당 클래스를 쓰려면 상속받아서 만드는 수 밖에 없는데 안드로이드에서는 기본적으로 AlertDialog.Builder 라는 클래스를 제공해서 쉽게 생성 할 수 있도록 도와주고 있다.

위에서 보는것과 같이 Builder 클래스를 이용하면 ok,cancel 과 같은 기존의 alert 상자에서 볼 수 있었던 버튼들을 직접 Button 을생성해서 위치 시키지 않아도 쉽게 추가 할 수있는 setPositiveButton  이나 setNegativeButton 을 제공한다.

또한 setTitle 과 setMessage 메소드를 제공해서 다른 자잘한 셋팅에 신경쓸 필요 없이 자동으로 만들어 준다.

 

Toast 메시지는 특정 메시지를 일정 시간동안 출력하고 알아서 사라지게 된다.

위와 같은 형태로 출력이 되며 AlertDialog 처럼 사용자와 상호작용 할 수 있도록 지원하지 않는다.

또한 Toast 메시지는 뜨기는 하지만 포커스가 해당 메시지로 이동하지는 않는다.

이것은 간단한 정보를 출력 할 때 많이 쓰이고 디버그 용으로도 많이 쓰인다.

출력되는 정보가 간단한 만큼 가장 간단하게 사용할 수 있다.

Toast.makeToast 라는 static 함수로서 생성되며 위의 예제에서 처럼 .show() 함수까지 함께 써서 한줄로 사용하는것이 일반적이다.

'알짜정보 > Android' 카테고리의 다른 글

android 소스 다운로드 받기  (40) 2010.03.18
goldfish 커널 다운로드 및 컴파일 하기  (818) 2010.03.16
android 커널부팅부터 액티비티까지  (21) 2010.03.12
SharedPreferences  (1016) 2010.03.01
Activity 간의 통신  (121) 2010.02.25
by cranix 2010. 3. 1. 04:11

오늘은 위와 같은 어플을 만들 것이다.

그냥 봐서는 어플의 기능을 추측할수 없는데 이것은 껏다가 켜도 화면의 내용이 초기화 되지 않고 유지되는 기능을 가지고 있다.

 

그럼 만들기를 시작해 보도록 하자.

먼저 위와 같은 형태의 레이아웃 을 작성하자.

 

- main.xml

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

<EditText
    android:layout_height="wrap_content"
    android:id="@+id/nameEditText"
    android:layout_width="fill_parent"
    android:hint="name"></EditText>
    <EditText
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:hint="email"
        android:id="@+id/emailEditText"></EditText>
    <EditText
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:hint="phone"
        android:id="@+id/phoneEditText"></EditText>

</LinearLayout>

 

다음은  Activity 파일을 작성하자

 

- MainActivity.java

package net.cranix.android.preftest;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;

public class MainActivity extends Activity {
    private SharedPreferences pref = null;
    private EditText nameEditText = null;
    private EditText emailEditText = null;
    private EditText phoneEditText = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        pref = getSharedPreferences("net.cranix.android.preftest",Activity.MODE_PRIVATE);
        nameEditText = (EditText) findViewById(R.id.nameEditText);
        emailEditText = (EditText) findViewById(R.id.emailEditText);
        phoneEditText = (EditText) findViewById(R.id.phoneEditText);
        nameEditText.setText(pref.getString("name", ""));
        emailEditText.setText(pref.getString("email", ""));
        phoneEditText.setText(pref.getString("phone", ""));

    }
    @Override
    protected void onStop() {
        super.onStop();
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("name", nameEditText.getText().toString());
        editor.putString("email", emailEditText.getText().toString());
        editor.putString("phone", phoneEditText.getText().toString());
        editor.commit();

    }
}

이렇게 현재 화면 정보 같은 작은 정보들을 저장하기 위해서 안드로이드는 SharedPreferences 라는 클래스를 제공한다.

이 클래스는 위 소스 에서와 같이 getSharedPreferences 메소드로 객체를 생성 할 수 있다.

이렇게 생성된 SharedPreferences 객체는 getString 과 같은 getXXX 형태의 메소드로 값을 얻어 올 수 있다.

위 소스에서 Activity 가 종료되는 onStop 메소드 에서는 SharedPreferences 에다가 현재 환경을 저장하고 있다.

SharedPreferneces 는 pref.edit() 로 Editor 객체를 얻은후 putString 으로 값을 변경한다. 다 변경했으면 editor.commit() 함수로 변경된 내용을 저장한다.

 

위에서도 언급했듯이 SharedPreferences 는 임시변수나 현재 UI 정보같은 작은 크기의 정보를 저장하기 적합하다. 조금 더 큰 데이터는 직접 파일에 쓰거나 SQL 을 사용하여 DB 에 저장하도록 하여야 한다.

 

그렇다면 이 데이터는 어디에 저장되는 것일까?

DDMS 나 adb 툴을 이용하여 확인해 보면 아래와 같은 xml 파일이 어플리케이션 디렉토리에 생긴 것을 볼 수 있다.

# pwd
pwd
/data/data/net.cranix.android.preftest
# cd shared_prefs
cd shared_prefs
# ls
ls
net.cranix.android.preftest.xml
# cat net.cranix.android.preftest.xml
cat net.cranix.android.preftest.xml
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="email">2</string>
<string name="phone">3</string>
<string name="name">1</string>
</map>
#

'알짜정보 > Android' 카테고리의 다른 글

android 소스 다운로드 받기  (40) 2010.03.18
goldfish 커널 다운로드 및 컴파일 하기  (818) 2010.03.16
android 커널부팅부터 액티비티까지  (21) 2010.03.12
AlertDialog 와 Toast  (45) 2010.03.01
Activity 간의 통신  (121) 2010.02.25
by cranix 2010. 3. 1. 03:31

대부분의 안드로이드 어플리케이션은 두개 이상의 Activity로 이루어진다. 각 Activity 들은 서로 Intent 를 통해서 통신을 하게된다.

이번 포스트에서는 Activity 간에 통신하는 방법을 예제와 함께 알아보자.

 

먼저 가장 메인 화면 레이아웃은 아래와 같이 구성한다.

 

main.xml 파일은 아래와 같다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:textSize="10pt" android:text="display"
        android:layout_width="wrap_content"
        android:layout_gravity="center"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:id="@+id/openBtn"
        android:text="open"/>
</LinearLayout>

 

새로운 Activity 를 위해서 아래와 같은 레이아웃을 하나 더 추가한다.

 

파일명은 form.xml 로 하고 내용은 아래와 같다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:orientation="vertical">
    <EditText
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:layout_width="fill_parent"
        android:hint="enter text"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="OK" android:id="@+id/okBtn"/>
</LinearLayout>

 

위 레이아웃을 보면 어느 정도 눈치 채겠지만 프로그램에 대해서 설명하자면 두 번째 레이아웃에 텍스트를 입력하고

OK 버튼을 누르면 첫 번째 레이아웃에 표시되는 것이다.

먼저 main.xml 과 연결되어 있는 MainActivity 를 만들도록 하자.

package net.cranix.android.activitytest;

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

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button openBtn = (Button)findViewById(R.id.openBtn);
        openBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this,FormActivity.class);
                startActivityForResult(i, 0);

            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 0) {
                TextView textView = (TextView)findViewById(R.id.textView);
                textView.setText(data.getExtras().getString("text"));

            }
        }
    }
}

위 소스에서 굵게 표시한 부분이 중요한 부분이다.

먼저 첫번째 부분은 Intent 를 이용하여 다른 Activity 를 호출하는 코드이다. 여기서 Intent는 안드로이드내 의 모든 Activity 간의 통신을 담당하는 구조체다. Intent 는 위와 같이 new Intent([호출한Activity],[호출당한Activity]) 형태로 만든다.

startActivityForResult 함수는 인텐트와 함께 resultCode 를 다른 Activity 로 보내는 역할을 한다 여기서 resultCode 가 어떤 역할을 하는지는 계속 읽다보면 이해 할 수 있을것이다.

 

 

다음으로 form.xml 과 연결될 Activity 를 만들어 보자.

 

아래와 같이 AndroidManifest.xml 파일을 열어 Application 탭의 Add 버튼을 누른다.

 

다음에 나오는 대화상자에서 Activity 를 클릭하면 아래와 같이 오른쪽에 Activity 설정 대화상자가 나온다.

거기서 아래와 같이 오른쪽에 있는 name 을 클릭하자

 

그럼 아래와 같이 클래스 추가하는 대화상자가 나오는데 Name 에다가 FormActivity 을 넣고 클래스를 생성한다.

 

 

소스는 아래와 같다.

package net.cranix.android.activitytest;

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

public class FormActivity extends Activity {
    private EditText editText;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.form);

        editText = (EditText)findViewById(R.id.editText);
        Button okBtn = (Button)findViewById(R.id.okBtn);
        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = getIntent();
                i.putExtra("text", editText.getText().toString());
                setResult(RESULT_OK, i);
                finish();

            }
        });
    }
}

 

이번 소스에도 중요한 부분은 볼드체로 되어있다.

현재 Activity 가 떠 있다는 소리는 어떤 Intent 에 의해서 호출되어진 것을 의미한다.

getIntent() 함수는 호출한 Intent 를 돌려주는 함수이다.

Intent 에다가는 데이터를 저장할 수 있는 이렇게 데이터가 저장된 intent 를 다른 Activity 로 보냄 으로서 통신이 이루어 지는 것이다.

데이터를 저장하는 방법은 위와 같이 intent 의 putExtra([key],[value]) 함수를 사용하면 된다.

setResult 함수는 호출한 Activity 에 전달해줄 intent 를 저장하는 함수로서 resultCode 와 같이 사용한다.

마지막으로 finish() 함수가 호출되면 setResult 함수에 의해 저장되어있던 resultCode 와 intent 가 이전의 Activity 에 전달되면서 현재의 Activity 는 닫히게 된다.

이러한 방식은 html 의 form 전달 방식을 보는듯 하다.

 

그럼 완성된 어플리케이션 화면을 보도록 하자.

 

 

사실 이 어플리케이션에서 Intent 를 쓰지 않고도 같은 기능을 하도록 만들 수 있다. 그럼에도 구지 Intent 를 쓰는 이유는 다른 어플들과의 통신을 쉽게 하기 위해서 이다.

안드로이드 내의 모든 어플들은 Activity 단위로 되어있으며 이 모든Activity 는 AndroidManifest 파일에서 허용만 해주면 다른 Activity 가 끌어다 쓸 수 있게 되어있다.

이러다 보니 수많은 사람들이 만든 Activity 들간의 통신방법이 존재 할 수 있기 때문에 이러한 통신 방법을 통일할 필요가 있었던 것이다.

 

 

'알짜정보 > Android' 카테고리의 다른 글

android 소스 다운로드 받기  (40) 2010.03.18
goldfish 커널 다운로드 및 컴파일 하기  (818) 2010.03.16
android 커널부팅부터 액티비티까지  (21) 2010.03.12
AlertDialog 와 Toast  (45) 2010.03.01
SharedPreferences  (1016) 2010.03.01
by cranix 2010. 2. 25. 23:47