2

Google+ に接続し、GoogleApiClient オブジェクトを正しく取得するアクティビティがあります。この後、Google にログインする必要があり、GMail Apis を使用してメールを送信する必要があるため、authToken 文字列が必要です。GoogleAuthUtil.getToken メソッドを呼び出すと、GoogleAuthException が発生しました。どうすればいいですか?GoogleApiClient オブジェクトを再度使用する必要がありますか?

ここにコード:

public class MainActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener
{
    GoogleApiClient mGoogleApiClient;
    private static final int REQUEST_RESOLVE_ERROR = 1001;
    // Unique tag for the error dialog fragment
    private static final String DIALOG_ERROR = "dialog_error";
    // Bool to track whether the app is already resolving an error
    private boolean mResolvingError = false;




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

        Scope scopes[] = {Plus.SCOPE_PLUS_PROFILE};

        mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Plus.API).addScope(Plus.SCOPE_PLUS_PROFILE).addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();


    }



    @Override
    public void onConnected(Bundle connectionHint)
    {

        String name = Plus.AccountApi.getAccountName(mGoogleApiClient);

        new emailTask().execute();



    }

    @Override
    public void onConnectionSuspended(int cause)
    {
        int a = 0;

        // The connection has been interrupted.
        // Disable any UI components that depend on Google APIs
        // until onConnected() is called.
    }

    @Override
    public void onConnectionFailed(ConnectionResult result)
    {
        if (mResolvingError) {
            // Already attempting to resolve an error.
            return;
        } else if (result.hasResolution()) {
            try {
                mResolvingError = true;
                result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
            } catch (SendIntentException e) {
                // There was an error with the resolution intent. Try again.
                mGoogleApiClient.connect();
            }
        } else {
            // Show dialog using GooglePlayServicesUtil.getErrorDialog()
            showErrorDialog(result.getErrorCode());
            mResolvingError = true;
        }






    }



    @Override
    protected void onStart() 
    {
        super.onStart();

        mGoogleApiClient.connect();

    }

    @Override
    protected void onStop()
    {
        mGoogleApiClient.disconnect();
        super.onStop();
    }



    private void showErrorDialog(int errorCode) {
        // Create a fragment for the error dialog
        ErrorDialogFragment dialogFragment = new ErrorDialogFragment();
        // Pass the error that should be displayed
        Bundle args = new Bundle();
        args.putInt(DIALOG_ERROR, errorCode);
        dialogFragment.setArguments(args);
        dialogFragment.show(getFragmentManager(), "errordialog");
    }

    /* Called from ErrorDialogFragment when the dialog is dismissed. */
    public void onDialogDismissed() {
        mResolvingError = false;
    }

    /* A fragment to display an error dialog */
    public static class ErrorDialogFragment extends DialogFragment {
        public ErrorDialogFragment() { }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Get the error code and retrieve the appropriate dialog
            int errorCode = this.getArguments().getInt(DIALOG_ERROR);
            return GooglePlayServicesUtil.getErrorDialog(errorCode,
                    this.getActivity(), REQUEST_RESOLVE_ERROR);
        }

        @Override
        public void onDismiss(DialogInterface dialog) {
            ((MainActivity)getActivity()).onDialogDismissed();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_RESOLVE_ERROR) {
            mResolvingError = false;
            if (resultCode == RESULT_OK) {
                // Make sure the app is not already connected or attempting to connect
                if (!mGoogleApiClient.isConnecting() &&
                        !mGoogleApiClient.isConnected()) {
                    mGoogleApiClient.connect();
                }
            }
        }
    }




    public static MimeMessage createEmail(String to, String from, String subject,
              String bodyText) throws MessagingException {
            Properties props = new Properties();
            Session session = Session.getDefaultInstance(props, null);

            MimeMessage email = new MimeMessage(session);
            InternetAddress tAddress = new InternetAddress(to);
            InternetAddress fAddress = new InternetAddress(from);

            email.setFrom(new InternetAddress(from));
            email.addRecipient(javax.mail.Message.RecipientType.TO,
                               new InternetAddress(to));
            email.setSubject(subject);
            email.setText(bodyText);
            return email;
          }



    public static Message createMessageWithEmail(MimeMessage email)
              throws MessagingException, IOException {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            email.writeTo(bytes);
            String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray());
            Message message = new Message();
            message.setRaw(encodedEmail);
            return message;
          }


    public static void sendMessage(Gmail service, String userId, MimeMessage email)
              throws MessagingException, IOException {
            Message message = createMessageWithEmail(email);
            message = service.users().messages().send(userId, message).execute();

            System.out.println("Message id: " + message.getId());
            System.out.println(message.toPrettyString());
          }



    public class emailTask extends AsyncTask
    {
        @Override
        protected Object doInBackground(Object... params) 
        {

            HttpTransport httpTransport = new NetHttpTransport();
            JsonFactory jsonFactory = new JacksonFactory();

           try {
            String token = GoogleAuthUtil.getToken(MainActivity.this, "myemail", "https://www.googleapis.com/auth/gmail.compose");
        } catch (UserRecoverableAuthException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (GoogleAuthException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

           /* try {
                clientSecrets = GoogleClientSecrets.load(jsonFactory,  new FileReader(CLIENT_SECRET_PATH));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }*/







            //GoogleCredential credential = new GoogleCredential().setAccessToken(token);
            //Gmail service = new Gmail.Builder(httpTransport, jsonFactory, credential).setApplicationName(APP_NAME).build().setFromTokenResponse(response);

            // Create a new authorized Gmail API client


            return null;
        }
    }

}

そしてここにログ:

08-11 10:37:42.197: W/System.err(4354): com.google.android.gms.auth.GoogleAuthException: Unknown
08-11 10:37:42.207: W/System.err(4354):     at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source)
08-11 10:37:42.207: W/System.err(4354):     at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source)
08-11 10:37:42.207: W/System.err(4354):     at com.fp.testauthgoogleplus.MainActivity$emailTask.doInBackground(MainActivity.java:249)
08-11 10:37:42.217: W/System.err(4354):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
08-11 10:37:42.217: W/System.err(4354):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
08-11 10:37:42.227: W/System.err(4354):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
08-11 10:37:42.227: W/System.err(4354):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
08-11 10:37:42.227: W/System.err(4354):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
08-11 10:37:42.237: W/System.err(4354):     at java.lang.Thread.run(Thread.java:841)
4

1 に答える 1