본문 바로가기
Project/안드로이드 프로젝트(HYPersonnalApp)

Android Studio, JAVA] 부여한 퍼미션(SMS, 전화번호부)들로 목록 가져오기

by 김마리님 2020. 11. 5.

퍼미션을 부여해서 휴대폰의 정보를 가져오는 것은, 마치 안드로이드 통신을 하는 것과 같습니다. 그러니, 먼저 데이터를 이런 형태로 가져와야 합니다~ 의 원형데이터가 필요합니다.

 

원래는 getter setter 함수가 필요하지만 저는 lombok 라이브러리를 사용했습니다. 만일 lombok을 사용하지 않으시려 한다면 getter setter 함수를 임의적으로 생성해야 합니다.

 

- PhoneBook. java

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class PhoneBook {

    private String id;
    private String name;
    private String phoneNumber;

}

 

- Message. java

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Message {
    public String messageId;
    public String threadId;
    public String address; //휴대폰번호
    public String contactId;
    public String contactId_string;
    public long timeStamp; //시간
    public String body; //문자내용


}

 

가져오는 법은 간단합니다. 

ContectResolver을 먼저 선언해줍니다. 이것은 다른 안드로이드 앱의 데이터베이스에 접근할 수 있는 권한을 부여합니다. 

이제 데이터에서 어떤 값을 가져올 지 배열로 선언하고, 쿼리에 이 배열을 넣어주면 데이터를 가져오게 됩니다. 그럼, 만들어둔 원형 데이터 타입의 ArrayList에 add 하기만 하면 됩니다.

 

- SelectBookNumberActivity . java

 

    public void readPhoneContact(){
        List<PhoneBook> phoneBookList = new ArrayList<>();

        ContentResolver resolver=SelectBookNumberActivity.this.getContentResolver();

        Uri phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

        String[] projection = {ContactsContract.CommonDataKinds.Phone.CONTACT_ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER};
        Cursor c= resolver.query(phoneUri, projection, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);

        while (c.moveToNext()){

            String id = c.getString(c.getColumnIndex(projection[0]));
            String name = c.getString(c.getColumnIndex(projection[1]));
            String number = c.getString(c.getColumnIndex(projection[2]));

            PhoneBook phoneBook = new PhoneBook();
            phoneBook.setId(id);
            phoneBook.setName(name);
            phoneBook.setPhoneNumber(number);

            DebugLogUtil.logD(TAG, phoneBook.getPhoneNumber());

            phoneBookList.add(phoneBook);

        }

        selectBookNumberAdapter.reload(phoneBookList);

    }

 

- SelectSMSActivity. java

    public void readSMSMessage() {
        Uri allMessage = Uri.parse("content://mms-sms/conversations");
        ContentResolver cr = getContentResolver();
        Cursor c = cr.query(allMessage,
                new String[]{"_id", "thread_id", "address", "person", "date", "body"},
                null, null,
                "date DESC");

        while (c.moveToNext()) {
            Message msg = new Message();

            long messageId = c.getLong(0);
            msg.setMessageId(String.valueOf(messageId));

            long threadId = c.getLong(1);
            msg.setThreadId(String.valueOf(threadId));

            String address = c.getString(2);
            msg.setAddress(address);

            long contactId = c.getLong(3);
            msg.setContactId(String.valueOf(contactId));

            String contactId_string = String.valueOf(contactId);
            msg.setContactId_string(contactId_string);

            long timestamp = c.getLong(4);
            msg.setTimeStamp(timestamp);

            String body = c.getString(5);
            msg.setBody(body);

            msgList.add(msg);
        }

        c.close();

        //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMDD");
        DebugLogUtil.logD(TAG, "msgList.size() : "+msgList.size());


        selectSMSAdapter.loadMsg(msgList);

 

이제 가져온 값들을 adapter을 이용해서 바로 ViewHolder에 끼워넣기만 하면 됩니다.

뷰홀더에 끼워넣는건.. 그냥 목록 가지고 RecyclerView에 끼워넣는 방식과 동일합니다. 그러니 접음글 처리합니다.

 

- SelectSMSAdapter. java

더보기
package com.example.hypersonnalsnsapp.selectSMSNumber.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hypersonnalsnsapp.R;
import com.example.hypersonnalsnsapp.selectSMSNumber.model.Message;

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

public class SelectSMSAdapter extends RecyclerView.Adapter {

    public List<Message> msgList=new ArrayList<>();

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_holder_sms_list,parent,false);
        return new SelectSMSViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        SelectSMSViewHolder selectSMSViewHolder = (SelectSMSViewHolder) holder;
        selectSMSViewHolder.msg=msgList.get(position);
        selectSMSViewHolder.updateView();
    }

    public void loadMsg(List<Message> msgList){
        this.msgList.clear();
        this.msgList.addAll(msgList);
        notifyDataSetChanged();
    }


    @Override
    public int getItemCount() {
        return msgList.size();
    }
}

 

- SelectSMSViewHolder. java

더보기
package com.example.hypersonnalsnsapp.selectSMSNumber.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hypersonnalsnsapp.R;
import com.example.hypersonnalsnsapp.getBankAndAddress.GetBankAndAddressActivity;
import com.example.hypersonnalsnsapp.selectProduct.SelectProductActivity;
import com.example.hypersonnalsnsapp.selectSMSNumber.model.Message;
import com.example.hypersonnalsnsapp.util.ActivityUtil;
import com.example.hypersonnalsnsapp.util.DebugLogUtil;
import com.example.hypersonnalsnsapp.util.SharedPreferenceUtil;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class SelectSMSViewHolder extends RecyclerView.ViewHolder {

    private static final String TAG = "SelectSMSViewHolder";

    private TextView textViewName;
    private TextView textViewContent;
    private TextView textViewDate;
    private TextView textViewSelect;

    public Message msg;

    public SelectSMSViewHolder(@NonNull View itemView) {
        super(itemView);
        findView();
        setListener();
    }

    private void findView() {
        textViewName = itemView.findViewById(R.id.textViewName);
        textViewContent = itemView.findViewById(R.id.textViewContent);
        textViewDate = itemView.findViewById(R.id.textViewDate);
        textViewSelect = itemView.findViewById(R.id.textViewSelect);
    }

    public void updateView() {

        String address = msg.address;

        if (msg.address.equals("#CMAS#Severe") || address.length() < 10) {
            itemView.getLayoutParams().height = 0;
        }

        if (address.length() == 10) {
            String address1 = address.substring(0, 3);
            String address2 = address.substring(3, 6);
            String address3 = address.substring(6, 10);
            textViewName.setText(address1 + "-" + address2 + "-" + address3);
        } else if (address.length() == 11) {
            String address1 = address.substring(0, 3);
            String address2 = address.substring(3, 7);
            String address3 = address.substring(7, 11);
            textViewName.setText(address1 + "-" + address2 + "-" + address3);
        }

        textViewContent.setText(msg.body);

        DateFormat dateFormat = new SimpleDateFormat("MM월 dd일");
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(msg.timeStamp);
        String finalDataString = dateFormat.format(calendar.getTime());
        textViewDate.setText(finalDataString);

    }
}

 

- SelectBookNumberAdapter. java

더보기
package com.example.hypersonnalsnsapp.selectBookNumber.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hypersonnalsnsapp.R;
import com.example.hypersonnalsnsapp.selectBookNumber.model.PhoneBook;
import com.example.hypersonnalsnsapp.selectSMSNumber.adapter.SelectSMSViewHolder;
import com.example.hypersonnalsnsapp.util.DebugLogUtil;

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

public class SelectBookNumberAdapter extends RecyclerView.Adapter {

    private static final String TAG = "SelectBookNumberAdapter";

    private List<PhoneBook> phoneBookList = new ArrayList<>();

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_holder_phone_contact_list, parent, false);
        return new SelectBookNumberViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

        SelectBookNumberViewHolder selectBookNumberViewHolder = (SelectBookNumberViewHolder) holder;
        selectBookNumberViewHolder.phoneBook=phoneBookList.get(position);
        selectBookNumberViewHolder.updateView();

    }

    public void reload(List<PhoneBook> phoneBookList){
        this.phoneBookList.clear();
        this.phoneBookList.addAll(phoneBookList);
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return phoneBookList.size();
    }
}

 

- SelectBookNumberViewHolder. java

package com.example.hypersonnalsnsapp.selectBookNumber.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hypersonnalsnsapp.R;
import com.example.hypersonnalsnsapp.getBankAndAddress.GetBankAndAddressActivity;
import com.example.hypersonnalsnsapp.selectBookNumber.model.PhoneBook;
import com.example.hypersonnalsnsapp.selectProduct.SelectProductActivity;
import com.example.hypersonnalsnsapp.util.ActivityUtil;
import com.example.hypersonnalsnsapp.util.DebugLogUtil;
import com.example.hypersonnalsnsapp.util.SharedPreferenceUtil;

public class SelectBookNumberViewHolder extends RecyclerView.ViewHolder {

    private static final String TAG = "SelectBookNumberViewHol";

    private TextView textViewName;
    private TextView textViewPhoneNumber;
    private TextView textViewSelect;

    public PhoneBook phoneBook;

    public SelectBookNumberViewHolder(@NonNull View itemView) {
        super(itemView);

        findView();
        setListener();
    }

    private void findView() {
        textViewName = itemView.findViewById(R.id.textViewName);
        textViewPhoneNumber = itemView.findViewById(R.id.textViewPhoneNumber);
        textViewSelect = itemView.findViewById(R.id.textViewSelect);
    }

    public void updateView() {
        textViewName.setText(phoneBook.getName());
        String phoneNum = phoneBook.getPhoneNumber();

        if (!phoneNum.contains("-")) {
            if (phoneNum.length() == 10) {
                String address1 = phoneNum.substring(0, 3);
                String address2 = phoneNum.substring(3, 6);
                String address3 = phoneNum.substring(6, 10);
                textViewPhoneNumber.setText(address1 + "-" + address2 + "-" + address3);
            } else if (phoneNum.length() == 11) {
                String address1 = phoneNum.substring(0, 3);
                String address2 = phoneNum.substring(3, 7);
                String address3 = phoneNum.substring(7, 11);
                textViewPhoneNumber.setText(address1 + "-" + address2 + "-" + address3);
            }
        } else {
            textViewPhoneNumber.setText(phoneNum);
        }
    }
}
반응형