如何在后台服务中使用oAuth获取的凭据?

时间:2015-09-25 19:21:56

标签: android oauth-2.0 google-calendar-api google-oauth2

我正在关注此(https://developers.google.com/google-apps/calendar/quickstart/android)以在我的Android应用中使用Google日历API。

它有效,但我需要能够在后台服务中做同样的事情。

com.google.api.services.calendar.Calendar mService = new com.google.api.services.calendar.Calendar.Builder(
                transport, jsonFactory, credential)
                .setApplicationName("Google Calendar API Android Quickstart")
                .build();

帮助我实例化日历对象。

我像这样实例化crendential:

credential = GoogleAccountCredential.usingOAuth2(
                getApplicationContext(), Arrays.asList(SCOPES))
                .setBackOff(new ExponentialBackOff())
                .setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));

如何在后台服务中使用它们?

我使用IntentService(WakefulIntentService)作为后台服务。

意图服务由以下警报触发:

public class Receiver extends BroadcastReceiver {
    private static final int PERIOD = 5000;
    private static final int INITIAL_DELAY = 5000;

    @Override
    public void onReceive(Context ctxt, Intent i) {
        if (i.getAction() == null) {
            WakefulIntentService.sendWakefulWork(ctxt, ScheduledService.class);
        } else {
            scheduleAlarms(ctxt);
        }
    }

    static void scheduleAlarms(Context ctxt) {
        AlarmManager mgr =
                (AlarmManager) ctxt.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(ctxt, Receiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(ctxt, 0, i, 0);
        mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + INITIAL_DELAY,
                PERIOD, pi);
    }
}

我的主要活动是Receiver.scheduleAlarms

0 个答案:

没有答案