Sunday, November 11, 2018

Android Google Drive API 예제

안드로이드에서 Google Drive API를 사용하는 예제이다.
구글에서 제공하는 예제넌 quick-start로서 해당 앱의 정보만 업로드하는 기능이고, 사용자의 전체 구글 드라이브의 정보를 리스팅하고 받아오지는 못한다.
우리는 사용자가 기존에 저장해 두었던 정보를 리스팅해 볼것이다.

아래의 페이지에서 사용할 package name과 keystore의 sha-1 키를 등록하자.
https://developers.google.com/drive/android/get-started

그리고 다음과 같이 소스코드를 구현한다. 단 package name은 위에서 등록한 package name이어야 한다.
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "GoogleDriveAndroidAPI";

    private final static int PERMISSION_CONTACTS = 1;
    private static final int REQUEST_AUTHORIZATION = 1;
    private static final int REQUEST_ACCOUNT_PICKER = 2;

    private final HttpTransport m_transport = AndroidHttp.newCompatibleTransport();
    private final JsonFactory m_jsonFactory = GsonFactory.getDefaultInstance();

    private GoogleAccountCredential m_credential;
    private Drive m_client;

    void startGoogleLogin() {
        // Google Accounts using OAuth2
        m_credential = GoogleAccountCredential.usingOAuth2(this, Collections.singleton(DriveScopes.DRIVE));

        m_client = new com.google.api.services.drive.Drive.Builder(
                m_transport, m_jsonFactory, m_credential).setApplicationName("AppName/1.0")
                .build();

        startActivityForResult(m_credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
    }

    boolean checkContactPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // get accounts 권한이 없으면 요청하자
            if (checkSelfPermission(Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(
                        new String[]{Manifest.permission.GET_ACCOUNTS,

                        },
                        PERMISSION_CONTACTS);
                return false;
            }
        }
        return true;
    }

    public void onRequestContactPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        Log.e("Example", "requestCode=" + requestCode);
        Log.e("Example", "permissions[0]=" + permissions[0]);
        Log.e("Example", "grantResults[0]=" + grantResults[0]);

        if (grantResults[0] == 0) {
            startGoogleLogin();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        onRequestContactPermissionsResult(requestCode, permissions, grantResults);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (checkContactPermission()) {
            startGoogleLogin();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == REQUEST_ACCOUNT_PICKER || requestCode == REQUEST_AUTHORIZATION)) {
            if (resultCode == RESULT_OK) {
                if (data != null && data.getExtras() != null) {
                    String accountName = data.getExtras().getString(AccountManager.KEY_ACCOUNT_NAME);
                    if (accountName != null) {
                        m_credential.setSelectedAccountName(accountName);
                    }

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            String pageToken = null;
                            do {
                                FileList result = null;
                                try {
                                    // GET_ACCOUNTS 권한을  수동으로 제어판 - 애플리케이션에서 설정해주어야 한다.
                                    result = m_client.files().list()
                                            .setQ("'root' in parents")
                                            .setPageSize(20)
                                            .setFields("nextPageToken, files(id, name)")
                                            .execute();
                                    List<File> files = result.getFiles();
                                    if (files == null || files.isEmpty()) {
                                        Log.e(TAG, "No files found.");
                                    } else {
                                        Log.e(TAG, "Files:");
                                        for (File file : files) {
                                            Log.e(TAG, String.format("%s (%s)\n", file.getName(), file.getId()));
                                        }
                                    }
                                    pageToken = result.getNextPageToken();
                                } catch (UserRecoverableAuthIOException e) {
                                    e.printStackTrace();
                                    startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            } while (pageToken != null);
                        }
                    }).start();
                }
                // call method to start accessing Google Drive
            } else { // CANCELLED
            }
        }
    }
}

No comments:

Post a Comment