blob: 7b25eaf8b482d11dfef283e961f79265c30cb577 [file] [log] [blame]
page.title=액티비티로부터 결과 가져오기
page.tags=intents
helpoutsWidget=true
trainingnavtop=true
@jd:body
<div id="tb-wrapper">
<div id="tb">
<h2> 과정에서 다루는 내용</h2>
<ol>
<li><a href="#StartActivity">액티비티 시작하기</a></li>
<li><a href="#ReceiveResult">결과 수신하기</a></li>
</ol>
<h2>필독 항목</h2>
<ul>
<li><a href="{@docRoot}training/sharing/index.html">간단한 데이터 공유하기</a></li>
<li><a href="{@docRoot}training/secure-file-sharing/index.html">파일 공유하기</a>
</ul>
</div>
</div>
<p>다른 액티비티를 시작하는 것이 단방향일 필요는 없습니다. 다른 액티비티를 시작하고 액티비티로부터 결과를
수신할 수도 있습니다. 결과를 수신하려면 {@link android.app.Activity#startActivityForResult
startActivityForResult()}를 호출합니다({@link android.app.Activity#startActivity
startActivity()} 대신).</p>
<p>예를 들어 자신의 앱에서 카메라 앱을 시작하고, 결과로 캡처된 사진을 수신할 있습니다. 또는,
피플 앱을 시작하여 사용자가 연락처를 선택할 있도록
있으며, 결과로 연락처 상세정보를 수신할 있습니다.</p>
<p>물론, 응답하는 액티비티는 결과를 반환하도록 설계되어 있어야 합니다. 그럴 경우, 액티비티는
다른 {@link android.content.Intent} 개체의 형태로 결과를 전송합니다. 그러면 액티비티가 {@link android.app.Activity#onActivityResult onActivityResult()} 콜백으로
결과를 수신합니다.</p>
<p class="note"><strong>참고:</strong> {@link android.app.Activity#startActivityForResult startActivityForResult()}를
호출할 명시적 또는 암묵적인 인텐트를 사용할 있습니다. 자신이 정의한 액티비티
하나를 시작하여 결과를 수신하는 경우 예상하는 결과를 수신하도록 보장하려면 명시적인 인텐트를
사용해야 합니다.</p>
<h2 id="StartActivity">액티비티 시작하기</h2>
<p>결과를 수신하기 위해 액티비티를 시작할 사용하는 {@link android.content.Intent} 개체와
관련하여 특별한 사항은 없습니다. 하지만, {@link
android.app.Activity#startActivityForResult startActivityForResult()} 메서드에 추가적인 정수 인수를 전달해야 합니다.</p>
<p>정수 인수는 요청을 식별하는 "요청 코드"입니다. 결과 {@link android.content.Intent}를
수신하는 경우, 앱이 결과를 올바르게 식별하여 이를 처리할 방법을 결정할
있도록 콜백이 이와 똑같은 요청 코드를 제공합니다.</p>
<p>다음은 사용자가 연락처를 선택할 있게 하는 액티비티를 시작하는 방법에 대한 예제입니다.</p>
<pre>
static final int PICK_CONTACT_REQUEST = 1; // The request code
...
private void pickContact() {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
</pre>
<h2 id="ReceiveResult">결과 수신하기</h2>
<p>사용자가 후속 액티비티 작업을 마치고 돌아오면, 시스템은 개발자 자신이 정의한 원래 액티비티의
{@link android.app.Activity#onActivityResult onActivityResult()} 메서드를 호출합니다. 이 메서드는 다음 세 가지
인수를 포함합니다.</p>
<ul>
<li>{@link
android.app.Activity#startActivityForResult startActivityForResult()}에 전달한 요청 코드</li>
<li> 번째 액티비티가 지정한 결과 코드. 코드는 작업이 성공한 경우 {@link
android.app.Activity#RESULT_OK}이고, 사용자가 작업을 취소했거나 작업이 어떠한
이유로 실패한 경우 {@link
android.app.Activity#RESULT_CANCELED}입니다.</li>
<li>결과 데이터를 전달하는 {@link android.content.Intent}</li>
</ul>
<p>다음은 "연락처 선택하기" 인텐트에 대한 결과를 처리하는 방법을 보여주는 예제입니다.</p>
<pre>
&#64;Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
// Do something with the contact here (bigger example below)
}
}
}
</pre>
<p> 예제에서는 Android 연락처 또는 피플 앱에서
반환되는 결과 {@link android.content.Intent}가 사용자가 선택한 연락처를 식별하는 {@link android.net.Uri} 콘텐츠를
제공합니다.</p>
<p>결과를 성공적으로 처리하기 위해서는
결과 {@link android.content.Intent}의 형식이 무엇인지 이해하고 있어야 합니다. 결과를 반환하는 액티비티가 자신이 정의한 액티비티
하나일 경우, 결과를 이해하기가 쉽습니다. Android 플랫폼에 포함된 앱은 특정한 결과 데이터를 기대할
있는 고유한 API 제공합니다. 예를 들어, 피플 앱(일부 이전 버전의 경우
연락처 앱)은 선택된 연락처를 식별하는 콘텐츠 URI 함께 항상 결과를 반환합니다. 또한
카메라 앱은 {@code "data"} 엑스트라에 {@link android.graphics.Bitmap}을 반환합니다(<a href="{@docRoot}training/camera/index.html">사진 캡처하기</a>
클래스 참조).</p>
<h4>보너스: 연락처 데이터 읽기</h4>
<p>피플 앱에서 결과를 가져오는 방법을 보여주는 상기 코드는, 결과에서
데이터를 실제로 읽는 방법에 대해 구체적으로 설명하지는 않습니다. 이유는 이를 설명하려면
<a href="{@docRoot}guide/topics/providers/content-providers.html">콘텐츠 제공자</a>에 대한 심도 있는 논의가
필요하기 때문입니다. 하지만 이러한 내용이 궁금할 경우, 결과 데이터를 쿼리하여 선택된
연락처에서 전화번호를 가져오는 방법을 보여주는 다음 코드를 참조하세요.</p>
<pre>
&#64;Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request it is that we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Get the URI that points to the selected contact
Uri contactUri = data.getData();
// We only need the NUMBER column, because there will be only one row in the result
String[] projection = {Phone.NUMBER};
// Perform the query on the contact to get the NUMBER column
// We don't need a selection or sort order (there's only one result for the given URI)
// CAUTION: The query() method should be called from a separate thread to avoid blocking
// your app's UI thread. (For simplicity of the sample, this code doesn't do that.)
// Consider using {@link android.content.CursorLoader} to perform the query.
Cursor cursor = getContentResolver()
.query(contactUri, projection, null, null, null);
cursor.moveToFirst();
// Retrieve the phone number from the NUMBER column
int column = cursor.getColumnIndex(Phone.NUMBER);
String number = cursor.getString(column);
// Do something with the phone number...
}
}
}
</pre>
<p class="note"><strong>참고:</strong> Android 2.3(API 레벨 9) 이전에서는 위에 표시된 코드와
같이 {@link android.provider.ContactsContract.Contacts Contacts Provider}에 대해 쿼리를
수행하려면 앱에서 {@link
android.Manifest.permission#READ_CONTACTS} 권한을 선언해야 합니다(<a href="{@docRoot}guide/topics/security/security.html">보안 및 권한</a> 참조). 하지만
Android 2.3부터는 연락처 제공자가 결과를 반환할 자신의 앱에서
결과를 읽어올 있도록 연락처/피플 앱이 임시 권한을 부여합니다. 임시 권한은 해당 연락처 요청에만
적용되기 때문에, 인텐트의 {@link android.net.Uri}에
지정된 연락처 외에는 쿼리할 없습니다. 다만, {@link
android.Manifest.permission#READ_CONTACTS} 권한을 명시적으로 선언한 경우는 예외입니다.</p>