이 예는 Android에서 전화를 거는 방법에 대해 보여줍니다.
1단계 − Android Studio에서 새 프로젝트를 생성하고 파일 ⇒ 새 프로젝트로 이동하여 필요한 모든 세부 정보를 입력하여 새 프로젝트를 생성합니다.
2단계 − res/layout/activity_main.xml에 다음 코드를 추가합니다.
<?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android" android:layout_width = "match_parent" android:gravity = "center" android:layout_height = "match_parent"> <ListView android:id = "@+id/list" android:layout_width = "wrap_content" android:textSize = "30sp" android:layout_height = "wrap_content" android:text = "Click"/> </LinearLayout>
위의 코드에서는 목록 보기를 사용했습니다.
3단계 − src/MainActivity.java
에 다음 코드 추가package com.example.myapplication; import android.annotation.TargetApi; import android.app.Activity; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { public static final int REQUEST_READ_CONTACTS = 79; private static final int REQUEST = 112; ListView list; ArrayList mobileArray; ArrayList numberArray; String number; @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); numberArray = new ArrayList(); if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) { mobileArray = getAllContacts(); } else { requestPermission(); } list = findViewById(R.id.list); ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, mobileArray); list.setAdapter(adapter); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { number = (String) numberArray.get(position); if (Build.VERSION.SDK_INT >= 23) { String[] PERMISSIONS = {android.Manifest.permission.CALL_PHONE}; if (!hasPermissions(MainActivity.this, PERMISSIONS)) { ActivityCompat.requestPermissions((Activity) MainActivity.this, PERMISSIONS, REQUEST ); } else { makeCall(number); } } else { makeCall(number); } } }); } private static boolean hasPermissions(Context context, String... permissions) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context ! = null && permissions ! = null) { for (String permission : permissions) { if (ActivityCompat.checkSelfPermission(context, permission) ! = PackageManager.PERMISSION_GRANTED) { return false; } } } return true; } private void makeCall(String number) { Intent phoneCallIntent = new Intent(Intent.ACTION_CALL); phoneCallIntent.setData(Uri.parse("tel:"+number)); startActivity(phoneCallIntent); } private void requestPermission() { if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_CONTACTS)) { // show UI part if you want here to show some rationale !!! } else { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_CONTACTS}, REQUEST_READ_CONTACTS); } if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_CONTACTS)) { } else { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_CONTACTS}, REQUEST_READ_CONTACTS); } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case REQUEST_READ_CONTACTS: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { mobileArray = getAllContacts(); } else { // permission denied,Disable the // functionality that depends on this permission. } return; } case REQUEST: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { makeCall(number); } else { Toast.makeText(MainActivity.this, "The app was not allowed to call.", Toast.LENGTH_LONG).show(); } } } } private ArrayList getAllContacts() { ArrayList<String> nameList = new ArrayList<>(); ContentResolver cr = getContentResolver(); Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); if ((cur ! = null ? cur.getCount() : 0) > 0) { while (cur ! = null && cur.moveToNext()) { String id = cur.getString( cur.getColumnIndex(ContactsContract.Contacts._ID)); String name = cur.getString(cur.getColumnIndex( ContactsContract.Contacts.DISPLAY_NAME)); nameList.add(name); if (cur.getInt(cur.getColumnIndex( ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) { Cursor pCur = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null); while (pCur.moveToNext()) { String phoneNo = pCur.getString(pCur.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER)); numberArray.add(phoneNo); } pCur.close(); } } } if (cur ! = null) { cur.close(); } return nameList; } }
4단계 − AndroidManifest.xml에 다음 코드 추가
<?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "https://schemas.android.com/apk/res/android" package = "com.example.myapplication"> <uses-permission android:name = "android.permission.READ_CONTACTS" /> <uses-permission android:name = "android.permission.CALL_PHONE" /> <application android:allowBackup = "true" android:theme = "@style/AppTheme.NoActionBar" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true"> <activity android:name = ".MainActivity" android:configChanges = "keyboardHidden|orientation|screenSize"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <action android:name = "android.intent.action.CREATE_SHORTCUT" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
응용 프로그램을 실행해 보겠습니다. 실제 Android 모바일 장치를 컴퓨터에 연결했다고 가정합니다. Android 스튜디오에서 앱을 실행하려면 프로젝트의 활동 파일 중 하나를 열고 도구 모음에서 실행 아이콘을 클릭합니다. 모바일 장치를 옵션으로 선택한 다음 기본 화면을 표시할 모바일 장치를 확인하십시오 –
이제 아래와 같이 전화를 걸기 위해 textview를 클릭하십시오 –