'개발/모바일OS(안드로이드,아이폰,윈도모바일등)'에 해당되는 글 59건

  1. 2010.12.28 안드로이드 Intent에서 앱 호출하는 방법을 정리 16
  2. 2010.12.09 Android Bitmap Object Resizing Tip 1
  3. 2010.12.03 Intent에 의한 사진뷰어, 갤러리, 카메라 제어 1
  4. 2010.10.22 manifest-element 15
  5. 2010.10.13 C2DM
  6. 2010.10.13 [번역] 안드로이드 Android Cloud to Device Messaging(C2DM)
  7. 2010.07.06 웹개발자를 위한 안드로이드 강좌-설치
  8. 2010.07.06 안드로이드 http connection UTF-->euc-kr 7
  9. 2010.06.25 안드로이드 하이브리드 앱 - 1. WebView로 로컬 파일(HTML) 로드하기 2
  10. 2010.06.15 Android Fundamental 중 Activity와 Task
2010. 12. 28. 10:45

안드로이드 Intent에서 앱 호출하는 방법을 정리




안드로이드 Intent에서 앱을 호출하는 방법을 정리 합니다.

연락처 Intent

  • 연락처 조회
intent = new Intent(Intent.ACTION_VIEW, 
Uri.parse("content://contacts/people/" +
String.valueOf(contact.getId())));
startActivity(intent);
  • 연락처 등록
intent = new Intent(Intent.ACTION_INSERT, 
Uri.parse("content://contacts/people"));
startActivity(intent);
  • 연락처 수정
intent = new Intent(Intent.ACTION_EDIT, 
Uri.parse("content://contacts/people/" +
String.valueOf(contact.getId())));
startActivity(intent);
  • 연락처 삭제
intent = new Intent(Intent.ACTION_DELETE, 
Uri.parse("content://contacts/people/" +
String.valueOf(contact.getId())));
startActivity(intent);

전화 Intent

  • 권한 설정 (AndroidManifest.xml)
전화 걸기         : CALL_PHONE = "android.permission.CALL_PHONE"
긴급 통화  : CALL_PRIVILEGED =
"android.permission.CALL_PRIVILEGED"
폰 상태 읽기  : READ_PHONE_STATE =
"android.permission.READ_PHONE_STATE"
폰 상태 수정  : MODIFY_PHONE_STATE =
"android.permission.MODIFY_PHONE_STATE"
브로드케스팅 수신 : PROCESS_OUTGOING_CALLS =
"android.permission.PROCESS_OUTGOING_CALLS"
전화 걸기 이전  : ACTION_NEW_OUTGOING_CALL =
"android.intent.action.NEW_OUTGOING_CALL"
  • 전화걸기 화면
Intent intent = new Intent(Intent.ACTION_DIAL, 
Uri.parse("tel:" + TelNumber));
startActivity(intent);
  • 전화걸기
Intent intent = new Intent(Intent.ACTION_CALL, 
Uri.parse("tel:" + TelNumber));
startActivity(intent);

SMS Intent

  • 권한 설정 (AndroidManifest.xml)
수신 모니터링       : RECEIVE_SMS = "android.permission.RECEIVE_SMS"
읽기 가능  : READ_SMS = "android.permission.READ_SMS"
발송 가능  : SEND_SMS = "android.permission.SEND_SMS"
SMS Provider로 전송 : WRITE_SMS = "android.permission.WRITE_SMS"
 : BROADCAST_SMS = "android.permission.BROADCAST_SMS"
  • SMS 발송 화면
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra("sms_body", "The SMS text");
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);
  • SMS 보내기
Intent intent = new Intent(Intent.ACTION_SENDTO, 
Uri.parse("smsto://" + contact.getHandphone()));
intent.putExtra("sms_body", "The SMS text");
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);

이메일 Intent

  • 이메일 발송 화면
Intent intent = new Intent(Intent.ACTION_SENDTO, 
Uri.parse("mailto:" + contact.getEmail()));
startActivity(intent);

브라우저 Intent

  • Browser에서 URL 호출하기
new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com/"));
startActivity(intent);
  • 브라우저에서 검색
Intent intent = new Intent(Intent.ACT ION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, "검색어");
startActivity(intent);

지도 Intent

  • 지도 보기
Uri uri = Uri.parse ("geo: 38.00, -35.03");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);

안드로이드 마켓 Intent

  • 안드로이드 마켓에서 Apps 검색
Uri uri = Uri.parse("market://search?q=pname:전제_패키지_명");  
//--- 예) market://search?q=pname:com.jopenbusiness.android.smartsearch
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
  • 안드로이드 마켓의 App 상세 화면
Uri uri = Uri.parse("market://details?id=전제_패키지_명");
//--- 예) market://details?id=com.jopenbusiness.android.smartsearch
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);

갤럭시S의 Intent

  • 패키지명과 클래스명으로 App 호출
intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("패키지명", "전체_클래스명"));
startActivity(intent);
  • 전화, SMS
  • 전화번호부 : com.android.contacts, com.sec.android.app.contacts.PhoneBookTopMenuActivity
  • 전화 : com.sec.android.app.dialertab, com.sec.android.app.dialertab.DialerTabActivity
  • 최근기록 : com.sec.android.app.dialertab, com.sec.android.app.dialertab.DialerTabDialerActivity
  • 메시지 : com.sec.mms, com.sec.mms.Mms
  • 이메일 : com.android.email, com.android.email.activity.Welcome
  • 일정 : com.android.calendar, com.android.calendar.LaunchActivity
  • 인터넷 : com.android.browser, com.android.browser.BrowserActivity
  • Google의 Android용 앱
  • 검색 : com.google.android.googlequicksearchbox, com.google.android.googlequicksearchbox.SearchActivity
  • 음성 검색 : com.google.android.voicesearch, com.google.android.voicesearch.RecognitionActivity
  • Gmail : com.google.android.gm, com.google.android.gm.ConversationListActivityGmail
  • 지도 : com.google.android.apps.maps, com.google.android.maps.MapsActivity
  • 위치찾기 : com.google.android.apps.maps, com.google.android.maps.LatitudeActivity
  • YouTube : com.google.android.youtube, com.google.android.youtube.HomeActivity
  • 토크 : com.google.android.talk, com.google.android.talk.SigningInActivity
  • Goggles : com.google.android.apps.unveil, com.google.android.apps.unveil.CaptureActivity
  • Google 번역 : com.google.android.apps.translate, com.google.android.apps.translate.HomeActivity
  • Reader : com.google.android.apps.reader, com.google.android.apps.unveil.CaptureActivity
  • Voice : com.google.android.apps.googlevoice, com.google.android.apps.googlevoice.SplashActivity
  • Google 별지도 : com.google.android.stardroid, com.google.android.stardroid.activities.SplashScreenActivity
  • 카메라 : com.sec.android.app.camera, com.sec.android.app.camera.Camera
  • TV : com.sec.android.app.dmb, com.sec.android.app.dmb.activity.DMBFullScreenView
  • Android 관리
  • 환경 설정 : com.android.settings, com.android.settings.Settings
  • 작업 관리자 : com.sec.android.app.controlpanel, com.sec.android.app.controlpanel.activity.JobManagerActivity
  • 마켓 : com.android.vending, com.android.vending.AssetBrowserActivity



출처 : http://www.jopenbusiness.com/tc/oss/entry/Android-Intent-%ED%99%9C%EC%9A%A9-%EC%82%AC%EB%A1%80
2010. 12. 9. 19:44

Android Bitmap Object Resizing Tip





[Intro]

 

Android에서 사용하는 이미지는 Bitmap이라는 클래스에서 다~ 알아서 해줍니다.
그리고 이런 Bitmap Object를 쉽게 만들 수 있도록 도와주는
BitmapFactory 클래스 라는 것도 있습니다.

 

BitmapFactory는 여러가지 소스로 부터 Bitmap Object를 만들어 주는 일을 하는데,
전부 static이며 decodeXXX 라는 이름을 가진 메소드들로 이루어져 있습니다.

XXX에는 어떤 것으로 부터 decode를 하여
Bitmap Object를 만들어 낼지에 대한 말들이 들어 가겠죠.

 


[Decoding Methods]

 

BitmapFactory.decodeByteArray() 메소드는 Camera.PictureCallback 으로 부터 받은
Jpeg 사진 데이터를 가지고 Bitmap으로 만들어 줄 때 많이 사용 합니다.
Camera.PictureCallback에서 들어오는 데이터가 byte[] 형식이기 때문에
저 메소드를 사용 해야 하는 것이죠.

 

BitmapFactory.decodeFile() 메소드는 파일을 그대로 읽어 옵니다.
내부적으로는 파일 경로를 가지고 FileInputStream을 만들어서 decodeStream을 합니다.
그냥 파일 경로만 쓰면 다 해주는게 편리 한 것이죠.

 

BitmapFactory.decodeResource() 메소드는 Resource로 부터 Bitmap을 만들어 내며
BitmapFactory.decodeStream() 메소드는 InputStream으로 부터 Bitmap을 만들어 냅니다.
뭐 그냥 이름만 봐도 알 수 있는 것들이지요.

 


[OutOfMemoryError??]

 

보통 이미지 파일을 읽어서 Resizing을 해야 할 때가 있는데,
그럴때는 BitmapFactory로 읽어서 Bitmap.createScaledBitmap() 메소드를 사용하여 줄이면

간단하게 처리 할 수 있습니다.

 

그런데 BitmapFactory를 사용할 때 주의해야 할 점이 있습니다.
아래의 예를 한번 보시죠.

Bitmap src = BitmapFactory.decodeFile("/sdcard/image.jpg");
Bitmap resized = Bitmap.createScaledBitmap(src, dstWidth, dstHeight, true);

이미지 파일로부터 Bitmap을 만든 다음에

다시 dstWidth, dstHeight 만큼 줄여서 resized 라는 Bitmap을 만들어 냈습니다.
보통이라면 저렇게 하는게 맞습니다.

 

읽어서, 줄인다.

 

그런데 만약 이미지 파일의 크기가 아주 크다면 어떻게 될까요?
지금 Dev Phone에서 카메라로 촬영하면
기본적으로 2048 x 1536 크기의 Jpeg 이미지가 촬영된 데이터로 넘어옵니다.
이것을 decode 하려면 3MB 정도의 메모리가 필요 할 텐데,

과연 어떤 모바일 디바이스에서 얼마나 처리 할 수 있을까요?

 

실제로 촬영된 Jpeg 이미지를 여러번 decoding 하다보면

아래와 같은 황당한 메세지를 발견 할 수 있습니다.

java.lang.OutOfMemoryError: bitmap size exceeds VM budget

네... OutOfMemory 입니다.
더 이상 무슨 말이 필요 하겠습니까...
메모리가 딸려서 처리를 제대로 못합니다.

 

이것이 실제로 decoding 후 메모리 해제가 제대로 되지 않아서 그런 것인지,
하더라도 어디서 Leak이 발생 하는지에 대한 정확한 원인은 알 수 없습니다.
이것은 엔지니어들이 해결해야 할 문제 겠죠...

 

하지만 메모리 에러를 피할 수 있는 방법이 있습니다.

 


[BitmapFactory.Options.inSampleSize]

 

BitmapFactory.decodeXXX 시리즈는 똑같은 메소드가 두 개씩 오버로딩 되어 있습니다.
같은 이름이지만 Signature가 다른 메소드의 차이점은
BitmapFactory.Options를 파라메터로 받느냐 안받느냐의 차이죠.

BitmapFactory.Options를 사용하게 되면 decode 할 때 여러가지 옵션을 줄 수 있습니다.


여러가지 많지만 저희가 지금 사용할 것은 inSampleSize 옵션 입니다.

 

inSampleSize 옵션은,
애초에 decode를 할 때 얼마만큼 줄여서 decoding을 할 지 정하는 옵션 입니다.

 

inSampleSize 옵션은 1보다 작은 값일때는 무조건 1로 세팅이 되며,
1보다 큰 값, N일때는 1/N 만큼 이미지를 줄여서 decoding 하게 됩니다.
즉 inSampleSize가 4라면 1/4 만큼 이미지를 줄여서 decoding 해서 Bitmap으로 만들게 되는 것이죠.

 

2의 지수만큼 비례할 때 가장 빠르다고 합니다.
2, 4, 8, 16... 정도 되겠죠?

 

그래서 만약 내가 줄이고자 하는 이미지가 1/4보다는 작고 1/8보다는 클 때,
inSampleSize 옵션에 4를 주어서 decoding 한 다음에,

Bitmap.createScaledBitmap() 메소드를 사용하여 한번 더 줄이면 됩니다.

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap src = BitmapFactory.decodeFile("/sdcard/image.jpg", options);
Bitmap resized = Bitmap.createScaledBitmap(src, dstWidth, dstHeight, true);

당연한 이야기 이겠지만,
내가 원하고자 하는 사이즈가 딱 1/4 크기라면

Bitmap.createScaledBitmap() 메소드를 쓸 필요가 없지요.

 

inSampleSize 옵션을 잘 활용하면 메모리 부족 현상을 대략적으로 해소 할 수 있습니다.
참고로 제가 저 옵션을 사용한 뒤로는 메모리 에러를 본적이 한~번도 없답니다.

 


[Appendix]

 

inSampleSize 옵션을 사용하면

SkScaledBitmapSampler Object (Library Level) 를 생성 하게 되는데,
Object를 만들때 정해진 SampleSize 만큼 축소하여 width와 height를 정한 뒤에 만들게 됩니다.
그러니까 애초에 축소된 사이즈로 이미지를 decoding 하는 것이죠.

 


[Outro]

 

Android의 기본 어플리케이션 소스를 분석 하다보면
상당히 테크니컬한 기법들을 많이 얻을 수 있습니다.
어떻게 이런 방법으로 만들었나 싶을 정도로 매우 정교하고 복잡하게 만들어져 있지요.
참 대단한 것 같습니다.

 

아 그리고 왜 dstWidth와 dstHeight 변수 선언이 없냐고 따지시는 분들 설마 없겠죠?



출처 : http://blog.naver.com/visualc98/79874750

2010. 12. 3. 20:44

Intent에 의한 사진뷰어, 갤러리, 카메라 제어





Intent는 정말 보면 기존 어플들의 기능을 재사용할 수 있도록 해주는 고마운 기능인것 같습니다. 
사진보기, 갤러리, 카메라는 Intent를 활용하여서 제어를 할 수 있기 때문에 또다시 이런 기능을 또 만들지 않도록 할 수 있고 개발기간을 단축할 수 있으며, 사용자에게도 익숙한 UI 이기때문에 효율성인 측면에서 대단히 좋은 기능이 아닐 수 없습니다. 따라서 이 세가지 기능에 대해서 정리를 해보았습니다.

1. 갤러리 관련 제어
 - 내장되어 있는 갤러리를 호출하여 사진을 선택 후 내가 어떤 사진을 선택했는지 URI로 가지고 데이터를 설정한다. 
 
 - 갤러리 리스트뷰 호출 
Intent i = new Intent(Intent.ACTION_PICK);
i.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
i.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); // images on the SD card.
// 결과를 리턴하는 Activity 호출 startActivityForResult(i, REQ_CODE_PICK_PICTURE);
 - 갤러리 리스트뷰에서 사진 데이터를 가져오는 방법
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQ_CODE_PICK_PICTURE) {
if (resultCode == Activity.RESULT_OK) { 
ImageView img = (ImageView)findViewById(R.id.image);
img.setImageURI(data.getData()); // 사진 선택한 사진URI로 연결하기 
}
}


2. 사진뷰어 호출
// 개별 이미지에 대한 URI 생성
// ex>uri = content://media/external/images/media/4  --> 4 = id
Uri uri = ContentUris.withAppendedId( Images.Media.EXTERNAL_CONTENT_URI, id);  // id값은 사진고유 ID
Intent intend = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intend);


3. 카메라 호출
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
2010. 10. 22. 13:50

manifest-element




<manifest>

syntax:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
         
package="string"
         
android:sharedUserId="string"
         
android:sharedUserLabel="string resource"
         
android:versionCode="integer"
         
android:versionName="string"
         
android:installLocation=["auto" | "internalOnly" | "preferExternal"] >
    . . .
</manifest>

contained in:
none

must contain:
<application>
can contain:
<instrumentation>
<permission>
<permission-group>
<permission-tree>
<uses-configuration>
<uses-permission>

<uses-sdk>

description:
The root element of the AndroidManifest.xml file. It must contain an <application> element and specify xlmns:android and package attributes.
attributes:
xmlns:android
Defines the Android namespace. This attribute should always be set to "http://schemas.android.com/apk/res/android".
package
A full Java package name for the application. The name should be unique. The name may contain uppercase or lowercase letters ('A' through 'Z'), numbers, and underscores ('_'). However, individual package name parts may only start with letters. For example, applications published by Google could have names in the form com.google.app.application_name.

The package name serves as a unique identifier for the application. It's also the default name for the application process (see the <application> element's process process attribute) and the default task affinity of an activity (see the <activity> element's taskAffinity attribute).

android:sharedUserId
The name of a Linux user ID that will be shared with other applications. By default, Android assigns each application its own unique user ID. However, if this attribute is set to the same value for two or more applications, they will all share the same ID — provided that they are also signed by the same certificate. Application with the same user ID can access each other's data and, if desired, run in the same process.
android:sharedUserLabel
A user-readable label for the shared user ID. The label must be set as a reference to a string resource; it cannot be a raw string.

This attribute was introduced in API Level 3. It is meaningful only if the sharedUserId attribute is also set.

android:versionCode
An internal version number. This number is used only to determine whether one version is more recent than another, with higher numbers indicating more recent versions. This is not the version number shown to users; that number is set by the versionName attribute.

The value must be set as an integer, such as "100". You can define it however you want, as long as each successive version has a higher number. For example, it could be a build number. Or you could translate a version number in "x.y" format to an integer by encoding the "x" and "y" separately in the lower and upper 16 bits. Or you could simply increase the number by one each time a new version is released.

android:versionName
The version number shown to users. This attribute can be set as a raw string or as a reference to a string resource. The string has no other purpose than to be displayed to users. The versionCode attribute holds the significant version number used internally.
android:installLocation
The default install location for the application.

The following keyword strings are accepted:

Value Description
"internalOnly" The application must be installed on the internal device storage only. If this is set, the application will never be installed on the external storage. If the internal storage is full, then the system will not install the application. This is also the default behavior if you do not define android:installLocation.
"auto" The application may be installed on the external storage, but the system will install the application on the internal storage by default. If the internal storage is full, then the system will install it on the external storage. Once installed, the user can move the application to either internal or external storage through the system settings.
"preferExternal" The application prefers to be installed on the external storage (SD card). There is no guarantee that the system will honor this request. The application might be installed on internal storage if the external media is unavailable or full, or if the application uses the forward-locking mechanism (not supported on external storage). Once installed, the user can move the application to either internal or external storage through the system settings.

Note: By default, your application will be installed on the internal storage and cannot be installed on the external storage unless you define this attribute to be either "auto" or "preferExternal".

When an application is installed on the external storage:

  • The .apk file is saved to the external storage, but any application data (such as databases) is still saved on the internal device memory.
  • The container in which the .apk file is saved is encrypted with a key that allows the application to operate only on the device that installed it. (A user cannot transfer the SD card to another device and use applications installed on the card.) Though, multiple SD cards can be used with the same device.
  • At the user's request, the application can be moved to the internal storage.

The user may also request to move an application from the internal storage to the external storage. However, the system will not allow the user to move the application to external storage if this attribute is set to internalOnly, which is the default setting.

Introduced in: API Level 8.

introduced in:
API Level 1 for all attributes, unless noted otherwise in the attribute description.

see also:
App Install Location
<application>
2010. 10. 13. 16:02

C2DM





C2DM (Cloud to Device Messaging) 은 인터넷에서 안드로이드 폰에 메시지를 보낼수 있는 기술이다.

인터넷에 최신 정보가 올라와 있는 데도 휴대폰이 서버에 접속해서 알아 보기 전 까지는
최신 정보가 올라와 있는 줄 모른다. 그 이전에는 일일이 휴대폰에서 특정 시간 간격으로
서버에 접속해 알아 보아야 했다. 이럴 경우 문제가 되는 것은 배터리 소모가 많고 네트웍
트래픽이 증가 한다는 문제점이 있다.

이를 위한 해결책으로 C2DM 이 나왔다.

이 기술을 사용하기 위해서는 안드로이드 2.2 가 설치된 폰에서
마켓에 등록된 앱을 사용해야 한다. 아직은 정식 릴리즈 되지 않았기
때문에 등록 신청한 후 시험해 볼 수 있다.

먼저 전체적인 그림을 보면 다음과 같은 구성 요소들이 있다.

1. 안드로이드 폰
2. 어플리케이션 서버
3. C2DM 서버

안드로이드 폰에서 푸시 기능을 사용하고 싶다면 다음과 같은 절차가 필요하다.

1. 안드로이드 폰에서 푸시 기능 활성화 하기
2. 어플리케이션 서버에서 C2DM 서버로 메시지 보내기
3. C2DM 서버에서 해당 안드로이드 폰으로 메시지 전달하기

안드로이드 폰 사용자들이 마켓에서 앱을 다운로드 받아 설치 할 때
앱이 C2DM 기능을 가지고 있다는 정보를 받고 이 기능을 사용할지 않을지를
선택 할 수 있다.

실제로 C2DM 을 사용하는 앱을 개발하는 절차를 알아보자

1. AndroidManifest.xml
   1.1. Permission
- RECEIVE
- C2D_MESSAGE
- INTERNET
   1.2. Receiver
1.2.1. intent filters
- RECEIVE
- REGISTRATION

2. C2DM 에 등록하기
   2.1. REGISTER 인텐트 생성 with sender and app
   2.2. startService

3. 등록 결과 처리하기

   단계 2 에서 REGISTER 인텐트를 날리면 등록 ID 값을 가진 인텐트를 받게 되는데
   이 인텐트를 받아 어플리케이션 서버에 내 등록 ID 를 전달하여야 한다.

4. 메시지 처리 하기

   등록이 성공하면 어플리케이션 서버는 언제든지 메시지를 보낼수 있는데
   메시지는 크기는 1024 바이트로 제한된다. 따라서 전체 데이타를 다 보내기 보다는
   어플리케이션에게 새로운 데이타가 있으니 접속해서 업데이트 하라는 메시지만
   보내야 한다.

어플리케이션 서버가 C2DM 서버에게 메시지를 보내기 위해서는 HTTP POST 를
https://android.apis.google.com/c2dm/send 를 사용하여 보내면 된다.

원문 http://joejeon.tistory.com/310
2010. 10. 13. 15:35

[번역] 안드로이드 Android Cloud to Device Messaging(C2DM)





Android Cloud to Device Messaging
[이 포스트는 이 기능을 구현하는데 기여한 Wei Huang 에 의해 작성되었습니다. — Tim Bray]


  새롭게 발표된 안드로이드 2.2 에서, 우리는 Android Cloud to Device Messaging (C2DM) 서비스를 추가하였습니다. 이 서비스는 개발자들이 서버와 모바일 어플리케이션간에 데이타를 쉽게 싱크할 수 있도록, 서버쪽 에서에서 안드로이드 폰 상의 어플리케이션으로 데이타를 손쉽게 전달할 수 있도록 도와줍니다.

 유용한 휴대폰 어플리케이션들은 대부분 사용자가 인터넷과 연결되도록 유지합니다. 이를 위해 전통적으로 많은 어플리케이션들은 주기적으로 데이터를 가져오기 위해 폴링 방식을 사용합니다. 예를들어 POP 이메일 클라이언트의 경우 15분 마다 이메일 서버와 연결되어 새로운 이메일을 가져오도록 구현될 수 있습니다. 이러한 폴링 방식은 비교적 구현하기가 용이하고, 대부분의 경우 잘 작동합니다. 하지만, 어떤한 주기로 폴링 작업을 수행할지 결정하는 것은 조금 애매한 구석이 있습니다. 폴링을 너무 자주하게 되면, 새로운 데이타가 없는데도 불구하고 불피요한 작업이 수행되며 서버와 네트워크에 부하를 줄 수 있습니다. 너무 드물게 폴링을 수행하면 어플리케이션이 갖고 있는 데이터가 전혀 갱신되지 않는 것 처럼 느껴질지도 모릅니다. 특히나 모바일 디바이스에서 효율적으로 폴링 작업을 수행하는 것은 중요한 문제입니다. 왜냐하면 폴링 작업은 귀중한 네트워크 밴드위스와 베터리를 소모시키기 때문입니다.

 폴링 방식을 사용하는 대신, 비동기적으로 클라이언트에 메세지를 푸쉬해주는 서버를 갖추는 것은 어플리케이션이 효율적으로 새로운 데이터를 전달 받을 수 있는 훨씬 좋은 선택이 될 수 있습니다. 하지만 훌륭한 푸쉬 솔루션을 구현하는 것은 어려운 일이며, 서버측과 특정한 연결을 유지하고 있어야 하는 오버헤드가 발생합니다. 특히 안드로이드폰과 같은 모바일 디바이스에서 이를 구현하는데는 네트워크 상태(고르지 못한 네트워크 커버리지, 무선망 상황이 좋지 않아 커넥션을 시도해도 타임아웃에 걸리고 마는 좀비 커넥션등) 에관한 고려가 필요하기 때문에, 교묘한 기술이 필요합니다. 

 G-메일, 주소록, 캘린더와 같은 안드로이드용 구글 어플리케이션은 데이터를 항상 최신으로 유지하기 위해 이미 푸시 방식을 사용하고 있습니다. 안드로이드 2.2 부터 C2DM 를 사용하면 서드파티 개발자들도 구글 어플리케이션과 동일한 서비스를 사용할 수 있습니다.

C2DM 에 대해서 몇 가지 기본적으로 알아야 하는 사항이 있습니다. 
  • 안드로이드 2.2 버전이 필요합니다. 
  • C2DM 은 '구글 서비스'를 사용합니다. 이 서비스는 안드로이드 마켓을 사용하는 모든 디바이스에 존재합니다.
  • C2DM 은 '구글 서비스' 를 위해 이미 존재하는 커넥션을 사용합니다.
  • C2DM 은 안드로이드 폰 상에서 사용자가 구글 계정으로 로그인 해야 사용이 가능합니다.
  • C2DM은 서드파티 서버가 간단한 메세지를 자신들의 어플리케이션으로 전달하는 것을 허용합니다.
  • C2DM 서비스는 대량의 컨텐츠를 푸쉬하도록 설계되지 않았습니다. 대신 특정 어플리케이션에게 새로운 데이타가 있음을 '쿡' 하고 알려 주고, 어플리케이션이 해당 서버에 접속해서 데이타를 다운로드 받을 수 있도록 하는데 사용되어야 합니다. 
  • 어플리케이션은 메세지를 받기 위해 작동중일 필요가 없습니다. 시스템은 전달해야할 데이타가 도착하는 경우에, 브로드캐스트 인텐트를 이용해 해당 어플리케이션을 깨울 것 입니다. 따라서, 어플리케이션은 적절하게 브로드캐스트 리시버와 Permission 을 설정해야 합니다.
  • 데이타 메세지를 전달 받기 위해 사용자 인터페이스가 필요하지는 않습니다. 물론 어플리케이션이 원한다면 알림창에 노티피케이션을 날릴 수도 있을 것 입니다.

C2DM API 를 사용하는 것은 쉽습니다. C2DM 은 아래와 같이 작동합니다.
  • C2DM 을 사용하기 위해 디바이스 상의 어플리케이션은 우선 구글에 등록해 Registration ID 를 발급 받아야 합니다. 해당 ID 를 자신의 서버에 전달해야 합니다. 
  • 만일 자신의 서버가 푸시하고 싶은 메세지가 있을 경우, 메세지를 HTTP 를 통해 구글의 C2DM 서버에 전달합니다. 
  • C2DM 서버는 메세지를 디바이스에 라우팅 하고, 디바이스는 브로드캐스트 인텐트를 어플리케이션에 전달 할 것 입니다. 
  • 타켓 어플리케이션은 브로드 캐스트 인텐트를 통해 깨어나고 메세지를 처리합니다. 
  • 어플리케이션은 사용자가 더이상 푸시 서비스를 받고싶지 않을 경우 등록을 취소할 수 있습니다. 
 거의 다 되었습니다. 개발자에게 필요한 것은 HTTP를 전달할 수 있는 서버와 Intent API 를 어떻게 사용해야하는지 알고 있는 안드로이드용 어플리케이션 뿐입니다. 아래는 간단한 예제 코드입니다.

// Use the Intent API to get a registration ID
// Registration ID is compartmentalized per app/device
Intent regIntent = new Intent(
        "com.google.android.c2dm.intent.REGISTER");
// Identify your app
regIntent.putExtra("app",
        PendingIntent.getBroadcast(this /* your activity */, 
            0, new Intent(), 0);
// Identify role account server will use to send
regIntent.putExtra("sender", emailOfSender);
// Start the registration process
startService(regIntent);

Registration ID 는 개발자의 어플리케이션으로 com.google.android.c2dm.intent. REGISTRATION 이라는 액션값을 갖는 브로드 캐스 인텐트를 통해 전달되어 집니다. 다음은 Registration ID 를 전달 받기위한 예제 코드 입니다.

// Registration ID received via an Intent
public void onReceive(Context context, Intent intent) {
  String action = intent.getAction();
  if (“com.google.android.c2dm.intent.REGISTRATION”.equals(action)) {
    handleRegistration(context, intent);
  }
}

public void handleRegistration(Context context, Intent intent) {
  String id = intent.getExtra(“registration_id”);
  if ((intent.getExtra(“error”) != null) {
    // Registration failed.  Try again later, with backoff.
  } else if (id != null) {
    // Send the registration ID to the app’s server.
    // Be sure to do this in a separate thread.
  }
}

 서버측을 살펴보면, 개발자의 서버는 C2DM 서버와 통신하기 위해 ClientLogin Auth 토큰을 가져야합니다. 토큰을 이용해서, 서버가 디바이스에 메세지를 푸시하고 싶을 때, 다음과 같은 인증된 HTTP Post 를 통해 메세지를 전달 할 수 있습니다. 
  • Authorization: GoogleLogin auth=<auth token>
  • Registration ID 와 키/벨류 쌍으로 이루어진 데이타, Google C2DM 서버에서 동일한 키값을 갖고 있는 오래된 메세지를 가로채기 위해 사용되는 'Collapse Key' 등몇 가지 옵셔널한 파라매터들을 포함하도록 인코딩된 URL.
 개발자가 C2DM 서비스를 사용하면, 골치아픈 모바일 데이타 커넥션을 직접 처리할 필요가 없으며, 사용자가 인터넷과 연결되어있는지 신경쓸 필요도 없습니다. (Airplane 모드와 같이). C2DM 은 서버 스토어에 메세지들을 보관하고, 디바이스가 온라인 상태로 될 때 해당 메세지를 전달합니다. 기본적으로 개발자는 견고한 푸시서비스를 위해 온갖 복잡하고 어려운 일들을 모두 구글에게 맡길 수 있습니다. 어플리케이션은 구글이 이미 구축하고 검증한 푸시 서비스의 이점을 취하고, 인터넷에 연결되어진 상태로 유지될 수 있습니다. 무엇보다도 좋은 것은 여러분이  배터리 소모에대해 비난을 받지 않아도 됩니다.

어떻게 C2DM 이 가능한 어플리케이션을 만들 수 있는 가에 관한 정보는 Code Lab 에 있으며, 서비스 일반 릴리즈가 다가올 수록 보다 다양한 정보가 공개될 것 입니다. 
2010. 7. 6. 11:32

웹개발자를 위한 안드로이드 강좌-설치




안드로이드 SDK 설치 및 실행
eclipse 3.5.1 기준으로 설명함
JDK .5.0 기준
1. Java SDK 설치
http://java.sun.com/javase/downloads/index.jsp

2. 이클립스 설치
http://www.eclipse.org/downloads/

3. Android SDK 설치
http://developer.android.com/sdk
참고 디텍토리 위치에 한글 포함되면 안됨(중요)

4. 안드로이드 Eclipse 플러그인 설치(ADT)
         

 Eclipse 3.5 (Galileo)
 
  Help/Install New Software
  Add 버튼 클릭
  Name엔 적당히 Android PlugIn이라고 채우시고, Location에 https://dl-ssl.google.com/android/eclipse/ 넣음   
  OK를 누르고  리스트에 표시된 Developer Tools 라고 되어있는 체크박스를 체크한후 Next, Next, 약관 동의, Finish   
  위 URL이 안된다면 http://dl-ssl.google.com/android/eclipse/로도 시도해보세요. (https -> http)
저는 https를 실패하여 http로 접속하였음

5. 이클립스 안드로이드 SDK 설정

이클립스의 메뉴 Windows/Preference 실행
왼쪽 탭에서 Android 선택
Browse를 한후 SDK를 설치한 디렉토리 선택 (디렉토리 패스에 한글이 들어가 있으면 안됩니다.)
Apply후 OK

6. 안드로이드 버전별 다운로드

안드로이드 2.0 SDK 부터 새로 생긴 방식입니다. 각 버전별 에뮬레이터 및 SDK를 별도로 다운로드 받게 되어있습니다.
Window/Android SDK and AVD Manager 실행
Available 패키지에서 설치를 원하는 API 버전 선택
(현재 https로 시작되는 것은 에러가 나는 경우가 종종 있습니다. 이경우 http://로 시작하는 주소를 Add Site로 추가합니다.
Install Selected
설치가 모두 완료되었습니다.



 

2010. 7. 6. 10:10

안드로이드 http connection UTF-->euc-kr




 
package com.qnsolv.vanmsm.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Hashtable;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import com.qnsolv.vanmsm.common.SI;


/*
 * HttpUtil client = new HttpUtil(LOGIN_URL);  
client.AddParam("accountType", "GOOGLE");  
client.AddParam("source", "tboda-widgalytics-0.1");
client.AddParam("Email", _username);
client.AddParam("Passwd", _password);
client.AddParam("service", "analytics");
client.AddHeader("GData-Version", "2");
try {  
    client.Execute(RequestMethod.POST);
} catch (Exception e) {  
    e.printStackTrace(); 
}  
String response = client.getResponse();
 */
public class HttpUtil {
	private String defaultUrl="";//자신의 서버url
	private ArrayList params;
	private ArrayList headers;
	private String url;
	private int responseCode;
	private String message;
	private String response;
	public String METHOD_GET = "GET";
	public String METHOD_POST = "POST";
	public int networkTime=20000;
	public Hashtable getResponse() {
		return VanUtil.packetAnalyis(response);
	}
	public String getErrorMessage() {
		return message;
	}
	public int getResponseCode() {
		return responseCode;
	}

	public HttpUtil(String url)
	{
		this.url = defaultUrl+url;
		params = new ArrayList();
		headers = new ArrayList();
	}

	public void AddParam(String name, String value)
	{
		params.add(new BasicNameValuePair(name, value));
	}

	public void AddHeader(String name, String value)
	{
		headers.add(new BasicNameValuePair(name, value));
	}
	
	public void execute(String method) throws Exception
	{
		if (method.equals(METHOD_GET)) {
			String combinedParams = "";
			if (!params.isEmpty()) {
				combinedParams += "?";
				for (NameValuePair p : params)
				{
					String urlEncoderStr="";
					try {
						urlEncoderStr = URLEncoder.encode(p.getValue(),"euc-kr");
					} catch (Exception e) {
						// TODO: handle exception
					}
					String paramString = p.getName() + "=" + urlEncoderStr;
					if (combinedParams.length() > 1)
					{
						combinedParams += "&" + paramString;
					}
					else
					{
						combinedParams += paramString;
					}
				}
			}
			VanUtil.println("DEBUG",this.getClass().getName() + " :="+url + combinedParams);
			HttpGet requestGet = new HttpGet(url + combinedParams);
			// add headers
			requestGet.addHeader("Accept", "text/plain, text/html, text/*");
			requestGet.addHeader("Referer", "vw.qnsolv.com");
			requestGet.addHeader("Host", "vw.qnsolv.com:8080");
			requestGet.addHeader("Connection", "Keep-Alive");
			requestGet.addHeader("User-Agent", "");
			requestGet.addHeader("Content-Type", "text/html;charset=UTF8");
			executeRequest(requestGet, url);
		} else if (method.equals(METHOD_POST)) {
			HttpPost request = new HttpPost(url);

			request.addHeader("Accept", "text/plain, text/html, text");
			if (!params.isEmpty()) {
				request.setEntity(new UrlEncodedFormEntity(params, HTTP.ISO_8859_1));
			}
			executeRequest(request, url);
		}

	}

	private void executeRequest(HttpUriRequest request, String url)
	{

		HttpParams httpParameters = new BasicHttpParams();  
		int timeoutConnection = networkTime; 
		HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); 
		int timeoutSocket = networkTime; 
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 
		
		
		HttpClient client = new DefaultHttpClient(httpParameters);

	 

		HttpResponse httpResponse;
		try {
			
			httpResponse = client.execute(request);
			responseCode = httpResponse.getStatusLine().getStatusCode();
			message = httpResponse.getStatusLine().getReasonPhrase();
			HttpEntity entity = httpResponse.getEntity();
			if (entity != null) {

				InputStream instream = entity.getContent();
				response = convertStreamToString(instream);
				Hashtable ht = VanUtil.packetAnalyis(response);
				// Closing the input stream will trigger connection release
				instream.close();
			}

		} catch (ClientProtocolException e) {
			client.getConnectionManager().shutdown();
			e.printStackTrace();
			response=SI.gI().getVanDefaultCode()+"00000100W99네트워크 연결 지연 \n( 네트워트 연결시간 "+(networkTime/1000)+" 초)   ";
		} catch (IOException e) {
			client.getConnectionManager().shutdown();
			e.printStackTrace();
			response=SI.gI().getVanDefaultCode()+"00000100W99네트워크 연결 지연 \n( 네트워트 연결시간 "+(networkTime/1000)+" 초)    ";
		}
	}

	private static String convertStreamToString(InputStream is) {

		StringBuilder sb = new StringBuilder();
		
		try{
			BufferedReader reader= new BufferedReader(new InputStreamReader(is,"EUC-KR"));
			String line = null;
			try {
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}catch(Exception e){
			
		}
		
		
		return sb.toString();

	}

}

2010. 6. 25. 12:51

안드로이드 하이브리드 앱 - 1. WebView로 로컬 파일(HTML) 로드하기





로컬 HTML(JavaScript)과 App 영역이 통신(함수호출)을 함으로써 간단한 하이브리드 앱을 만들어볼 수 있다.

1. HTML에서 App 함수 호출
   1) 멤버로 android.os.Handler 를 생성한다. 호출 시 thread 처리를 위해서 이용된다.
        private final Handler handler = new Handler();

   2) App과 Javascript간 Bridge 클래스를 생성하고, 호출될 함수를 implement 한다.
       (이 때 파리메터는 반드시 final로 선언)
       Javascript에서 호출시 별도의 Thread로 구동될 수 있도록 아래와 같이 구현한다.

          private class AndroidBridge {
            public void setMessage(final String arg) { // must be final
                handler.post(new Runnable() {
                    public void run() {
                        Log.d("HybridApp", "setMessage("+arg+")");
                        mTextView.setText(arg);
                    }
                });
            }
          }

   3) onCreate 함수에서 WebView에서 JavaScript를 Enable 하고, JavaScriptInterface로 Bridge 인스턴스를 등록한다.
        // 웹뷰에서 자바스크립트실행가능
        mWebView.getSettings().setJavaScriptEnabled(true);
        // Bridge 인스턴스 등록
        mWebView.addJavascriptInterface(new AndroidBridge(), "HybridApp");
 
    4) HTML 내에서 JavaScript에서 선언된 함수를 다음과 같이 호출 한다.
            window.<interfaceName>.<functionName>

  window.HybridApp.setMessage(msg);


2. App에서 HTML의 Javascript 함수 호출
   이부분은 간단하다....HTML에거 링크걸 때를 생각하면 되는데....
   그냥 버튼을 눌렀을 때 다음과 같이 호출하면 된다.
    mWebView.loadUrl("javascript:<함수명>('<arg>')");

    실제 구현은 다음과 같이 된다.
       mButton.setOnClickListener( new OnClickListener(){
        public void onClick(View view) {
            mWebView.loadUrl("javascript:setMessage('"+mEditText.getText()+"')");           
        }
       });

위의 방법으로 연결된 간단한 하이브리드 어플리케이션이다...





출처 : http://devian.tistory.com/159
2010. 6. 15. 14:05

Android Fundamental 중 Activity와 Task





출처 : [KANDROID]


Activity & Task
 하나의 activity는 다른 activity를 시작할 수 있고 다른 application의 activity도 시작할 수 있다. 예를 들어 임의위치의 street map을 display한다고 가정하자, 이런 작업을 하는 activity는 이미 제공된다. 따라서 당신의 activity에서 이 activity를 시작하기 위해 해야 할 일은 필요한 정보를 포함하는 intent object를 startActivity()에 파라메터로 전달하여 호출하는것 뿐이다. 이렇게 하면 street map viewer가 표시될것이다. 이 때 BACK버튼을 누르면 viewer를 시작한 당신의 activity가 다시 보여질 것이다.
 이는 사용자로 하여금 street map viewer가 당신의 application의 일부라고 느끼게 한다. 하지만 실제로는 그 activity는 다른 app의 다른 process상의 activity이다.
 안드로이드는 이처럼 사용자가 사용한 activity들을 task로 하여 그 정보를 유지한다. 관련된 activity는 group으로 stack에 저장된다.
 root activity는 task상의 첫번째 activity이고 top activity는 현재 화면에 보여지는 activity이다. activity가 다른 activity를 시작하면 그 새로운 activity가 stack에 push되고 그 activity가 top activity가 된다. 그리고 이전 activity는 stack에 남아 있는다. 이 상태에서 사용자가 BACK버튼을 누르면 이전 activity가 stack에서 POP되어 화면에 보여지게 되어 resume된다.
stack은 activity의 object(instance)를 가지고 있다. 따라서 같은 activity의 여러개의 instance가 가능하다. 같은 activity를 여러개 시작할수 있다는 의미이다.
 stack내의 activity는 stack이므로 재정렬되지 않는다. 순서는 그대로 유지되게 된다. 단지 PUSH, POP만 된다.
Task는 activity들의 stack이다. 따라서 task내의 activity에 어떤 값을 설정하는 방법은 없다. root activity만이 affinity(친밀도) set을 이용하여 read, set이 가능하다.
Task의 모든 activity들은 하나의 집합으로 background또는 foreground로 이동한다. 현재 Task가 4개의 activity를 가진다고 가정해보자. HOME 키를 누르면 application launcher로 이동한다. 이어서 새로운 application을 실행한다. 그러면 현재 task는 background로 가고 새로운 task의 root activity가 표시된다. 이어 사용자가 다시 HOME으로 갔다가 이전 application을 다시 선택한다면 그 task가 다시 앞으로 나온다. 이 때 BACK키를 누르면 root activity가 표시되지 않고 task상의 이전 activity가 표시된다.

      A1 -> A2 -> A3 -> A4 -> HOME -> B 1-> B2 -> HOME -> A4 -> BACK -> A3

task와 activity간의 결합과 동작에 대한 제어는 intent object의 flag 파라메터와 minifest의 <activity> element의 몇가지 속성으로 제어가 가능하다.

    flag -> FLAG_ACTIVITY_NEW_TASKFLAG_ACTIVITY_CLEAR_TOP, FLAG_ACTIVITY_RESET_TASK_IF_NEEDED, FLAG_ACTIVITY_SINGLE_TOP
    <activity>'s attributes -> taskAffinity, launchMode, allowTaskReparenting, clearTaskOnLaunch, allowRetainTaskState, finishOnTaskLaunch

Affinityes and new Tasks
 기본적으로 하나의 application의 activity들은 각기 하나의 affinity를 갖는다. 그러나 각각의 affinity들은 <activity> element의 taskAffinity속성으로 affinity set을 이룰수 있다. 서로 다른 application의 activity들이 동일한 affinity를 공유할 수 있으며 한 application의 activity들이 서로 다른 affinity를 가질수 있다. affinity는 intent object에 FLAG_ACTIVITY_NEW_TASK로 activity를 적재할 때와 activity가 allowTaskReparenting속성을 true로 set하였을 때 시작된다.

FLAG_ACTIVITY_NEW_TASK 적용시
 앞서 기술한대로 기본적으로 activity는 startActivity()로 task안에 적재된다. caller와 동일한 stack에 push된다. 그러나 startActivity()가 FLAG_ACTIVITY_NEW_TASK 로 flag를 set하여 호출하면 시스템은 새로운 activity를 담기위한 task를 찾는다. 보통 새로운 task가 생성되지만 동일한 affinity를 갖는 task가 검색되면 그 태스크에 가서 달라붙는다.

allowTaskReparenting 적용시
 특정 activity가 allowTaskReparenting속성이 "true"이면, 시작된 task에서 동일한 affinity를 갖는 다른 task가 foreground로 올라올때 그 task로 activity가 이동될 수 있다. 예를 들면, 특정도시의 날씨를 보여주는 activity를 가지고 있는 travel application이 있다고 하자. travel application에 동일한 affinity를 갖는 다른 activity가 있고 reparenting이 가능하다. 이 상태에서 당신의 application의 activity가 travel application의 날씨 activity를 시작하면 날씨 activity는 당신의 task에 적재되게 된다. 그러나 이 때 travel application이 적재되게 되면 날씨 activity는 새로 시작된 travel application의 task에 재위치지정이 되고 화면에 표시되어진다.

travel application : Weather activity, ... -> allowTaskReparenting이 true이고 모두 동일 affinity를 갖는다.
your application : A, B, C, D activity

 launch travel application -> (1)start Weather activity -> HOME -> launch your application -> start A activity -> (2)start Weather activity -> HOME -> (3)travel application -> display Weather activity
  
(1) 시점에서 weather activity는 task1(travel app의 task)에 적재된다. (2)시점에서 weather activity는 task2(your app의 task)에 적재된다. (3)의 시점에서 travel app가 다시 시작될때 task2에 있던 weather activity가 task1으로 재지정되게 된다.
  
하나의 패키지(*.apk)에 여러 application이 정의되어 있다면 app단위로 각기 다른 affinity를 부여하는것이 좋다.

Launch Mode
 <activity> element에 lounchMode 속성을 조정하여 activity를 컨트롤할 수 있다. 

            standard, singleTop, singleTask, singleInstance

 위 4가지 모드는 4가지 관점에서 다르게 동작한다.
* 임의 Intent에 대해 어떤 task가 그 activity를 받을 것인가?
 standard, singleTop모드는 intent가 발생된 task에 push된다. flag를 FLAG_ACTIVITY_NEW_TASK로 설정해도 호출한 동일한 task내에 push된다. 위에 기술한 affinity & new task에 따라 다른 task가 선택될수 있다.
 singleTask및 singleInstance는 task를 정의하여 root activity로 적재되고 다른 task에 적재되지 않는다.
* 다중 instance activity가 가능한가?
standard, singleTop모드는 여러 task에 소속될수도 있고 한 task에 동일한 activity가 여러 instance가 적재될수도 있다. 
singleTask, singleInstance는 task내에서 오로지 한개의 instance만 적재된다. root activity만 가능하기 때문에 device내에서 한번에 하나의 Instance만 존재할 수 있다.
* Instance가 task내에서 다른 activity를 가질수 있는가?
 singleInstance는 task내에서 오직 하나의 instance만 가능하며, 만일 다른 activity를 시작하면 launchMode에 관계없이 새로운 task가 생성되어 적재된다.
 standard, singleTask, singleTop은 모두 multi instance가 가능하다. singleTask는 root activity로 생성되며 다른 activity를 task내에 적재가 가능하다. singleTop과 standard모드는 stack내에서 자유롭게 다른 activity를 생성가능하다.
* 특정 class의 새로운 instance가 새로운 intent를 다룰것인가?
 standard모드는 새로운 instance가 새로운 intent의 응답으로 생성된다. 각 instance는 오직 하나의 intent를 다룬다.
 singleTop : target-task의 stack에 top activity로 있다면 그 class의 instance가 intent를 재사용하여 처리한다. top activity가 아니면 재사용하지 않고 새로운 instance가 생성되어 intent를 처리하고 stack에 push된다.

예) A - B - C - D에서 D를 시작하려고 할 때  D가 singleTop이면 A - B - C - D 로된다.
     A - B - C - D에서 D를 시작하려고 할 때  D가 standard이면 A - B - C - D - D 로된다.
     B가 singleTop이나 standare이면 A - B - C - D - B 가 가능하다.
     

Clearing the stack
  기본적으로 사용자가 task를 오랫동안 사용하지 않으면 system은 task의 root activity만을 제외하고 모든 activity들을 clear한다. <activity>element의 몇가지 속성은 이를 조정할 수 있게 해준다.

alwaysRetainState 속성
  task의 root activity에 이 속성을 set하면 이 task는 오랜시가이 지나도 생존하게 된다.
clearTaskOnLaunch 속성
  task의 root activity에 이 속성을 set하면 task를 나가고 돌아올때 clear된다.
finishOnTaskLaunch
  clearTaskOnLaunch와 유사하나 이 속성은 하나의 activity에만 유효하다. root activity를 포함하여 현재 세션인 경우에만 살아있고 task를 떠나면 clear된다.

  stack에서 activity를 제거하는 다른 방법이 있다.
  intent object의 flag를 FLAG_ACTIVITY_CLEAR_TOP로 하고 이 intent를 처리할 activity가 target task에 이미 instance를 가지고 있다면 상위 activity들이 모두 clear되고 그 activity가 top activity가 된다.   launchMode가 "standard"라면 stack에서 마찬가지로 삭제되고 새로운 activity가 그 intent를 처리할 것이다.
  FLAG_ACTIVITY_NEW_TASK와 FLAG_ACTIVITY_CLEAR_TOP이 함께 사용되면 존재하는 activity가 새 task에 생성되어 intent를 처리한다.

Starting task
  activity는 intent filter중에 action filter로 android.intent.action.MAIN를 그리고 category filter로  android.intent.category.LAUNCHER로 entry point가 설정된다. 이런 설정은 icon과 label정보를 가지로 화면에 표시하고 task에 적재하고 적재후 언제든지 다시 돌아올수 있도록 해준다.
  사용자는 언제든 task를 떠날수 있고 다시 돌아올수 있다. singleTask와 singleInstance로 설정된 activity는 반드시 MAIN과 LAUNCHER를 filter로 적용해야 한다. 그러지 않으면 activity를 수행후 다른 화면으로 갔다가 다시 돌아올 수 있는 방법이 없게 된다.

  FLAG_ACTIVITY_NEW_TASK 는 activity하나가 새로운 task에 시작되고 HOME key를 눌렀을 경우 다시 복귀하기 위해 다른 방법이 있다. 
  외부 task에서 notification manager같은 entity에서 항상 activity들을 시작할 수 있다. 이런 방식으로 외부에서 activity를 invoke할 수 있다면 사용자가 다른 방법으로 그 task를 시작할 수 있음을 유의해야 한다. 이런 경우 그 activity로 복귀하기를 원하지 않는다면 finishOnTaskLaunch를 사용하면 된다.