簡體   English   中英

android GoogleAuthUtil.getTokenWithNotification Intent回調未觸發

[英]android GoogleAuthUtil.getTokenWithNotification Intent callback not triggering

我有一個后台服務,調用GoogleAuthUtl.getTokenWithNotification並且它正常工作,但我正在嘗試實現此功能的回調部分,但是無法正常工作。

我已經實現了一個廣播接收器並將其添加到清單中,我的應用程序中也有一個活動。 以下是相關的代碼段。

GoogleAuthUtil.getTokenWithNotification

GoogleAuthUtil.getTokenWithNotification(this.getContext(), account, "oauth2:" + GmailScopes.GMAIL_SEND, null, new Intent(AuthReceiver.AUTH_INTENT));

AuthReceiver

public class AuthReceiver extends BroadcastReceiver
{
    public final static String AUTH_INTENT = "com.testoauth.AUTH_INTENT";

    public AuthReceiver()
    {
    }

    @Override
    public void onReceive(Context context, Intent intent)
    {
        Log.d("RECEIVER", "Received Auth broadcast.");
        NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
    }
}

AndroidManifest

<receiver android:name=".AuthReceiver" android:enabled="true" android:exported="true">
    <intent-filter>
        <action android:name="com.testoauth.AUTH_INTENT" />
    </intent-filter>
</receiver>

我不知道為什么它沒有收到廣播。 我沒有在日志中看到任何異常,並且沒有任何跡象表明接收器完全被調用,它在調試時甚至不會在斷點處中斷。 我做錯了什么嗎?

編輯

我正在使用min sdk 16和目標sdk 25

GoogleAuthUtil.getTokenWithNotification API文檔中:

此方法專門用於后台任務。 如果出現需要用戶干預的錯誤,此方法負責推送相關通知。 在用戶解決通知之后,廣播回叫。 如果用戶取消,則不會觸發回調。

無論用戶是否取消,都不會觸發回調。 除了ActivityManager說明已顯示通知( Displayed com.google.android.gms/.auth.uiflows.gettoken.GetTokenActivity ),沒有跡象表明指定的廣播意圖(在本例中為com.testoauth.AUTH_INTENT )已在日志中發送。 “收到的Auth廣播”。 日志中也沒有消息。

此功能包含的SDK示例( <android-sdk>/extras/google/google_play_services/samples/auth/gau )甚至不起作用。

我嘗試在Android API 25上跟蹤錯誤,但從未調用回調函數:

  • 沒有互聯網
  • 用戶尚未登錄
  • 用戶未授權代表他/她發送電子郵件
  • Google Play服務已停用
  • Google Play服務已過期

如果回調方法調用對您的用例並不重要,您可以按照Android Quickstart for Gmail API在Android中代表用戶發送電子郵件。 選中發送電子郵件以創建消息。 您還可以查看使用上述教程創建的MyGoogleAuthUtilApplication

希望這可以幫助。

我已經實現了演示,我使用了最新版本的auth gradle及其工作原理。 它看起來可能與auth版本有問題

public class AuthActivity extends Activity {


    private static final int AUTHORIZATION_CODE = 1993;
    private static final int ACCOUNT_CODE = 1601;

    private AuthPreferences authPreferences;
    private AccountManager accountManager;

    /**
     * change this depending on the scope needed for the things you do in
     * doCoolAuthenticatedStuff()
     */
    private final String SCOPE = "https://www.googleapis.com/auth/googletalk";

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

        accountManager = AccountManager.get(this);

        authPreferences = new AuthPreferences(this);
        if (authPreferences.getUser() != null
                && authPreferences.getToken() != null) {
            doCoolAuthenticatedStuff();
        } else {
            chooseAccount();
        }
    }

    private void doCoolAuthenticatedStuff() {
        // TODO: insert cool stuff with authPreferences.getToken()

        Log.e("AuthApp", authPreferences.getToken());
        clickSendEmail();
    }

    private void chooseAccount() {
        // use https://github.com/frakbot/Android-AccountChooser for
        // compatibility with older devices
        Intent intent = AccountManager.newChooseAccountIntent(null, null,
                new String[] { "com.google" }, false, null, null, null, null);
        startActivityForResult(intent, ACCOUNT_CODE);
    }

    private void requestToken() {
        Account userAccount = null;
        String user = authPreferences.getUser();
        for (Account account : accountManager.getAccountsByType("com.google")) {
            if (account.name.equals(user)) {
                userAccount = account;
Preferences.setAccount(AuthActivity.this,account.name, account.type);
                break;
            }
        }

        accountManager.getAuthToken(userAccount, "oauth2:" + SCOPE, null, this,
                new OnTokenAcquired(), null);
    }

    /**
     * call this method if your token expired, or you want to request a new
     * token for whatever reason. call requestToken() again afterwards in order
     * to get a new token.
     */
    private void invalidateToken() {
        AccountManager accountManager = AccountManager.get(this);
        accountManager.invalidateAuthToken("com.google",
                authPreferences.getToken());

        authPreferences.setToken(null);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            if (requestCode == AUTHORIZATION_CODE) {
                requestToken();
            } else if (requestCode == ACCOUNT_CODE) {
                String accountName = data
                        .getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
                authPreferences.setUser(accountName);

                // invalidate old tokens which might be cached. we want a fresh
                // one, which is guaranteed to work
                invalidateToken();

                requestToken();
            }
        }
    }

    private class OnTokenAcquired implements AccountManagerCallback<Bundle> {

        @Override
        public void run(AccountManagerFuture<Bundle> result) {
            try {
                Bundle bundle = result.getResult();

                Intent launch = (Intent) bundle.get(AccountManager.KEY_INTENT);
                if (launch != null) {
                    startActivityForResult(launch, AUTHORIZATION_CODE);
                } else {
                    String token = bundle
                            .getString(AccountManager.KEY_AUTHTOKEN);

                    authPreferences.setToken(token);

                    doCoolAuthenticatedStuff();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    private void clickSendEmail()
    {
        final Account account = Preferences.getAccount(this);
        final String token = Preferences.getToken(this);

        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {

                    Session session = Session.getDefaultInstance(new Properties(), null);

                    MimeMessage email = new MimeMessage(session);

                    email.setFrom(new InternetAddress(account.name));

                    //TODO: change email address to your email address for testing
                    email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress("nasitraj2@gmail.com"));
                    email.setSubject("TEST OAUTH EMAIL");
                    email.setText("This is a test");
                    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                    email.writeTo(bytes);
                    String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray());
                    Message message = new Message();
                    message.setRaw(encodedEmail);

                    Intent intent = new Intent(AUTH_INTENT);
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(AuthActivity.this, 0, intent, 0);
                    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                    alarmManager.set(AlarmManager.RTC_WAKEUP,  System.currentTimeMillis()
                            , pendingIntent);
                    String test = GoogleAuthUtil.getTokenWithNotification(AuthActivity.this, account, "oauth2:" + GmailScopes.GMAIL_SEND, null, intent);
                    GoogleCredential credential = new GoogleCredential();
                    credential.setAccessToken(test);

                    boolean changed = false;
                    if (!test.equals(token))
                    {
                        changed = true;
                        //   Snackbar.make(AuthActivity.this.getView(), "TOKEN CHANGED", Snackbar.LENGTH_LONG).show();
                        Preferences.setToken(AuthActivity.this, test);
                    }



                    Gmail service = new Gmail.Builder(AndroidHttp.newCompatibleTransport(),
                            AndroidJsonFactory.getDefaultInstance(), credential)
                            .setApplicationName("Test OAuth").build();

                    service.users().messages().send("me", message).execute();

                    String msg = "Email sent";
                    if (changed)
                        msg = "TOKEN CHANGED: " + msg;



                }
                catch (MessagingException e)
                {
                    Log.d( "ERROR", e.getMessage());
                }
                catch (GoogleJsonResponseException e)
                {
                    if (e.getDetails().getCode() == 401)
                    {
                        try
                        {
                            Intent intent = new Intent(AUTH_INTENT);
                            GoogleAuthUtil.clearToken(AuthActivity.this, Preferences.getToken(AuthActivity.this));
                            GoogleAuthUtil.getTokenWithNotification(AuthActivity.this, account, "oauth2:" + GmailScopes.GMAIL_SEND, null, intent);
                        }
                        catch (Exception e1)
                        {
                            //ignore
                        }
                    }
                }
                catch (IOException e)
                {
                    //  Snackbar.make(AuthActivity.this.getView(), "ERROR", Snackbar.LENGTH_LONG).show();
                    Log.d( "ERROR", e.getMessage());
                }
                catch (Exception e)
                {
                    //Snackbar.make(AuthActivity.this.getView(), "ERROR", Snackbar.LENGTH_LONG).show();
                    Log.d( "ERROR", e.getMessage());
                }
            }
        }).start();
    }
}

似乎任何人都無法對這個問題給出正確的答案; 關於如何解決這個問題的大量絕對好的建議,但沒有回答實際的問題。 我得出結論,這必定是Android或Google Play服務中的錯誤。 不幸的是,我已經向Android問題跟蹤器和Google Play服務支持論壇報告了這個問題......兩者都指向對方並且甚至拒絕查看問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM