2022년 9월 4일 일요일

android 전화 번호 읽기, getNumber, getLine1Number, getPhoneNumber

 Android 전화 번호 읽기

getNumber, getLine1Number, getPhoneNumber 함수에 대해서 정리해보았습니다.

getNumber, getLine1Number 두개의 함수는 API 33 부터 deprecated 되고 getPhoneNumber 함수가 사용됩니다. 따라서 미리 코드를 정리해 보았습니다.


특히 getNumber / getPhoneNumber 함수의 경우 DualSIM에서도 번호를 읽을 수 있도록 구현 되어있습니다. 시험 환경이 없어서 시험을 해보지는 못했습니다.


권한은 아래 두 개 Runtime 권한이 필요합니다.

android.Manifest.permission.READ_PHONE_STATE,
android.Manifest.permission.READ_PHONE_NUMBERS

AndroidManifest.xml 에도 추가해줍니다.

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_NUMBERS" />


함수 사용에 기본적인 예제

단말에서도 시험을 해봤는데 33 API의 경우 현재 대상 단말을 구하기 힘들어서 가상 device를 이용하여 시험 하였습니다.



실행 화면

로그 화면


전체 소스

package com.example.javatestapp2;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;

import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;

import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;

import androidx.core.app.ActivityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.example.javatestapp2.databinding.ActivityMainBinding;

import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    public static List<SubscriptionInfo> subInfoList;
    public static ArrayList<String> Numbers;
    private SubscriptionManager mSubscriptionManager;

    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setSupportActionBar(binding.toolbar);

        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);

        binding.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        TextView textView = (TextView) findViewById(R.id.textview_first);

        // 권한이 허용되어있지않다면 권한요청
        if (!hasPermissions(this, PERMISSIONS)) {
            getPermission(PERMISSIONS);
            textView.setText("Please re run");
        }else {
            Numbers = new ArrayList<String>();
            mSubscriptionManager = SubscriptionManager.from(this);
            GetCarriorsInformation();
            textView.setText(Numbers.toString());
        }

    }

    String[] PERMISSIONS = {
            android.Manifest.permission.READ_PHONE_STATE,
            android.Manifest.permission.READ_PHONE_NUMBERS
    };

    public boolean hasPermissions(Context context, String... permissions) {
        if (context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }
    private void getPermission(String... permissions){
        ActivityCompat.requestPermissions(this,
                permissions,1000);
    }
    private void GetCarriorsInformation() {
        subInfoList = mSubscriptionManager.getActiveSubscriptionInfoList();
        Log.d("Test",subInfoList.toString());
        int subId;
        // https://developer.android.com/reference/android/telephony/SubscriptionInfo#getNumber()
        // This method was deprecated in API level 33.
        // use SubscriptionManager#getPhoneNumber(int) instead.
        for (SubscriptionInfo subscriptionInfo : subInfoList) {
            subId = subscriptionInfo.getSubscriptionId();
            Log.d("Test","SubscriptionInfo:"+subId);
            Log.d("Test","SubscriptionInfo:"+subscriptionInfo.getNumber());
            Numbers.add("SubscriptionInfo/"+subId+"/"+subscriptionInfo.getNumber()+"\n");
        }
        // https://developer.android.com/reference/android/telephony/TelephonyManager#getLine1Number()
        // This method was deprecated in API level 33.
        // use SubscriptionManager#getPhoneNumber(int) instead.
        TelephonyManager mgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String myNumber = mgr.getLine1Number();
        Log.d("Test","getLine1Number:"+myNumber);
        Numbers.add("getLine1Number/"+myNumber+"\n");

        if (android.os.Build.VERSION.SDK_INT >= 33) {
            // https://developer.android.com/reference/android/telephony/SubscriptionManager#getPhoneNumber(int)
            for (SubscriptionInfo subscriptionInfo : subInfoList) {
                subId = subscriptionInfo.getSubscriptionId();
                Log.d("Test", "SubscriptionManager:" + subId);
                Log.d("Test", "SubscriptionManager:" + mSubscriptionManager.getPhoneNumber(subId));
                Numbers.add("SubscriptionManager/" + subId + "/" + mSubscriptionManager.getPhoneNumber(subId) + "\n");
            }
        }
} @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public boolean onSupportNavigateUp() { NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main); return NavigationUI.navigateUp(navController, appBarConfiguration) || super.onSupportNavigateUp(); } }

로그

2022-09-04 12:39:22.569 7433-7433/com.example.javatestapp2 D/Test: [{id=1 iccId= simSlotIndex=0 carrierId=1 displayName=T-Mobile carrierName=T-Mobile nameSource=3 iconTint=-16746133 number=[****] dataRoaming=0 iconBitmap=null mcc=310 mnc=260 countryIso=us isEmbedded=false nativeAccessRules=null cardString= cardId=0 portIndex=0 isOpportunistic=false groupUUID=null isGroupDisabled=false profileClass=-1 ehplmns=null hplmns=null subscriptionType=0 groupOwner=null carrierConfigAccessRules=[cert: 92B5F8117FBD9BD5738FF168A4FA12CBE284BE834EDE1A7BB44DD8455BA15920 pkg: null access: 0, cert: 3D1A4BEF6EE7AF7D34D120E7B1AAC0DD245585DE6237CF100F68333AFACFF562 pkg: null access: 0, cert: 6892793FC413019D2DF609DFED7AF622D0F2D8FCF96EFA7E3FB87EEA34E10B93 pkg: null access: 0, cert: 7B68FD9D4E7610C9CB35FC0C6CC06EA04C6906E3DFA9F48F9A05460AF36BFFFC pkg: null access: 0] areUiccApplicationsEnabled=true usageSetting=0}]
2022-09-04 12:39:22.569 7433-7433/com.example.javatestapp2 D/Test: SubscriptionInfo:1
2022-09-04 12:39:22.569 7433-7433/com.example.javatestapp2 D/Test: SubscriptionInfo:+15551234567
2022-09-04 12:39:22.573 7433-7433/com.example.javatestapp2 D/Test: getLine1Number:+15551234567
2022-09-04 12:39:22.573 7433-7433/com.example.javatestapp2 D/Test: SubscriptionManager:1
2022-09-04 12:39:22.583 7433-7433/com.example.javatestapp2 D/Test: SubscriptionManager:+15551234567


빌드시 아래와 같이 설정하였습니다.

compileSdk 33
minSdk 31
targetSdk 31


댓글 없음:

댓글 쓰기