Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Android 앱에서 새 연락처 추가하는 방법 – 단계별 코드 가이드

Android 앱에서 새 연락처 추가하는 방법

이 글에서는 안드로이드 앱에서 새로운 연락처를 추가하는 방법을 단계별로 살펴봅니다. 화면에 이름과 전화번호를 입력받는 필드를 만들고, 버튼을 누르면 안드로이드 시스템의 연락처 저장 화면을 호출해 실제 기기에 연락처가 등록되도록 구현합니다.

1단계 — Android Studio에서 새 프로젝트 만들기

Android Studio를 실행한 뒤 메뉴에서 File → New Project를 선택하고, 새 프로젝트 생성에 필요한 모든 항목을 입력하여 프로젝트를 만듭니다.

2단계 — activity_main.xml 레이아웃 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 이 레이아웃은 연락처 이름을 입력받는 EditText, 숫자 전용 키패드가 적용된 전화번호 입력용 EditText, 그리고 연락처를 추가하는 Button으로 구성되어 있습니다.

<? xml version= "1.0" encoding= "utf-8" ?>
<LinearLayout xmlns: android = "https://schemas.android.com/apk/res/android"
   xmlns: tools = "https://schemas.android.com/tools"
   android :layout_width= "match_parent"
   android :layout_height= "match_parent"
   android :layout_margin= "16dp"
   android :orientation= "vertical"
   tools :context= ".MainActivity" >
   <EditText
      android :id= "@+id/etContactName"
      android :layout_width= "match_parent"
      android :layout_height= "wrap_content"
      android :hint= "Contact name"
      android :inputType= "text" />
   <EditText
      android :id= "@+id/etContactNumber"
      android :layout_width= "match_parent"
      android :layout_height= "wrap_content"
      android :hint= "Contact number"
      android :inputType= "number" />
   <Button
      android :layout_width= "match_parent"
      android :layout_height= "wrap_content"
      android :onClick= "addContact"
      android :text= "ADD" />
</LinearLayout>

3단계 — MainActivity 코드 작성

src/MainActivity.java 파일에 다음 코드를 추가합니다. 핵심 로직은 addContact() 메서드에 있습니다. 이 메서드는 입력된 이름과 전화번호를 읽어온 뒤, ContactsContract.Intents.Insert.ACTION 인텐트를 생성해 안드로이드의 연락처 추가 화면으로 값을 전달합니다.

package app.tutorialspoint.com.sample ;
import android.app.Activity ;
import android.content.Intent ;
import android.os.Bundle ;
import android.provider.ContactsContract ;
import android.support.v7.app.AppCompatActivity ;
import android.view.View ;
import android.widget.EditText ;
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 addContact (View view) {
      EditText etContactName = findViewById(R.id. etContactName ) ;
      EditText etContactNumber = findViewById(R.id. etContactNumber ) ;
      String name = etContactName.getText().toString() ;
      String phone = etContactNumber.getText().toString() ;
      Intent contactIntent = new Intent(ContactsContract.Intents.Insert. ACTION ) ;
      contactIntent.setType(ContactsContract.RawContacts. CONTENT_TYPE ) ;
      contactIntent
      .putExtra(ContactsContract.Intents.Insert. NAME , name)
      .putExtra(ContactsContract.Intents.Insert. PHONE , phone) ;
      startActivityForResult(contactIntent , 1 ) ;
   }
   @Override
   protected void onActivityResult ( int requestCode , int resultCode , Intent intent) {
      super .onActivityResult(requestCode , resultCode , intent) ;
      if (requestCode == 1 ) {
         if (resultCode == Activity. RESULT_OK ) {
            Toast. makeText ( this, "Added Contact" , Toast. LENGTH_SHORT ).show() ;
         }
         if (resultCode == Activity. RESULT_CANCELED ) {
            Toast. makeText ( this, "Cancelled Added Contact" ,
            Toast. LENGTH_SHORT ).show() ;
         }
      }
   }
}

연락처 저장 결과는 onActivityResult() 콜백에서 처리됩니다. 요청 코드가 1이고 결과가 성공(RESULT_OK)이면 "Added Contact"라는 토스트 메시지를, 사용자가 취소(RESULT_CANCELED)하면 취소 메시지를 화면에 표시합니다.

참고: 위 예제는 구버전 지원 라이브러리인 android.support.v7.app.AppCompatActivity를 사용합니다. 최신 프로젝트라면 AndroidX의 androidx.appcompat.app.AppCompatActivity로 임포트를 교체하면 됩니다.

4단계 — AndroidManifest.xml 설정

androidManifest.xml 파일에 아래 코드를 추가합니다. 원문 예제에는 CALL_PHONE 권한과 디바이스 관리자(DeviceAdmin) 리시버 선언도 함께 포함되어 있지만, 인텐트를 통해 연락처 추가 화면만 호출하는 경우에는 application 태그와 MainActivity 선언만 있어도 기능이 정상 동작합니다.

<? xml version= "1.0" encoding= "utf-8" ?>
<manifest xmlns: android = "https://schemas.android.com/apk/res/android"
   package= "app.tutorialspoint.com.sample" >
   <uses-permission android :name= "android.permission.CALL_PHONE" />
   <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>
      <receiver
         android :name= ".DeviceAdmin"
         android :description= "@string/app_description"
         android :label= "@string/app_name"
         android :permission= "android.permission.BIND_DEVICE_ADMIN" >
         <meta-data
            android :name= "android.app.device_admin"
            android :resource= "@xml/policies" />
         <intent-filter>
            <action android :name= "android.app.action.DEVICE_ADMIN_ENABLED" />
         </intent-filter>
      </receiver>
   </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 스마트폰이 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하세요. 실행 기기 목록에서 본인의 모바일 기기를 선택하면 앱이 설치되고 기본 화면이 표시됩니다.

이름과 전화번호를 입력한 후 ADD 버튼을 누르면 시스템의 연락처 저장 화면으로 전환됩니다. 여기서 저장을 완료하면 토스트 메시지가 표시되고, 기기의 연락처 앱에서 새로 등록된 연락처를 확인할 수 있습니다.

Android 앱에서 새 연락처 추가하는 방법 – 단계별 코드 가이드