我有以下代码,可以在日历中插入事件。它被扩展为活动类,因此在调用它时,会打开一个空白活动。我想通过Async Task执行此操作。
活动类:
private static final Level LOGGING_LEVEL = Level.OFF;
private static final String PREF_ACCOUNT_NAME = "accountName";
static final String TAG = "CalendarAuth";
static final int REQUEST_GOOGLE_PLAY_SERVICES = 0;
static final int REQUEST_AUTHORIZATION = 1;
static final int REQUEST_ACCOUNT_PICKER = 2;
private final static int ADD_OR_EDIT_CALENDAR_REQUEST = 3;
com.google.api.services.calendar.Calendar service;
final HttpTransport transport = AndroidHttp.newCompatibleTransport();
final JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
GoogleAccountCredential credential;
Event event;
CalendarModel model = new CalendarModel();
String title, description;
com.google.api.services.calendar.Calendar client;
int numAsyncTasks;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.smspayremin);
reset = (Button) findViewById(R.id.rest);
final SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit();
final SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Logger.getLogger("com.google.api.client").setLevel(LOGGING_LEVEL);
// Initialize credentials and service object.
credential = GoogleAccountCredential.usingOAuth2(this, Collections.singleton(CalendarScopes.CALENDAR));
credential.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));
// Calendar client
client = new com.google.api.services.calendar.Calendar.Builder(
transport, jsonFactory, credential).setApplicationName("Google-CalendarAndroidSample/1.0")
.build();
reset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
editor.putBoolean(getString(R.string.smartrem), true).apply();
}
});
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
if (bundle.containsKey("remtitle")) {
title = bundle.getString("remtitle");
description = bundle.getString("remdesc");
button.setVisibility(View.GONE);
textView.setVisibility(View.GONE);
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_GOOGLE_PLAY_SERVICES:
if (resultCode == Activity.RESULT_OK) {
haveGooglePlayServices();
} else {
checkGooglePlayServicesAvailable();
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == Activity.RESULT_OK) {
// AsyncLoadCalendars.run(this);
} else {
chooseAccount();
}
break;
case REQUEST_ACCOUNT_PICKER:
if (resultCode == Activity.RESULT_OK && data != null && data.getExtras() != null) {
String accountName = data.getExtras().getString(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
credential.setSelectedAccountName(accountName);
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREF_ACCOUNT_NAME, accountName);
editor.commit();
// AsyncLoadCalendars.run(this);
}
}
break;
}
}
public void createEvent(GoogleAccountCredential mCredential) {
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
service = new com.google.api.services.calendar.Calendar.Builder(
transport, jsonFactory, mCredential)
.setApplicationName("Created By Mini4Me")
.build();
event = new Event()
.setSummary(title)
/*.setLocation("Dhaka")*/
.setDescription(description);
TimeZone timeZone = TimeZone.getDefault();
DateTime startDateTime = new DateTime(new Date());
EventDateTime start = new EventDateTime()
.setDateTime(startDateTime)
.setTimeZone(timeZone.getID());
event.setStart(start);
DateTime endDateTime = new DateTime(addDays(new Date(), 10));
Log.e("start D ", startDateTime + "End Date " + endDateTime + timeZone.getID());
EventDateTime end = new EventDateTime()
.setDateTime(endDateTime).setTimeZone(timeZone.getID());
event.setEnd(end);
String[] recurrence = new String[]{"RRULE:FREQ=DAILY;COUNT=2"};
event.setRecurrence(Arrays.asList(recurrence));
/* EventAttendee[] attendees = new EventAttendee[]{
new EventAttendee().setEmail("abir@aksdj.com"),
new EventAttendee().setEmail("asdasd@andlk.com"),
};
event.setAttendees(Arrays.asList(attendees));*/
EventReminder[] reminderOverrides = new EventReminder[]{
//new EventReminder().setMethod("email").setMinutes(24 * 60),
new EventReminder().setMethod("popup").setMinutes(10),
};
Event.Reminders reminders = new Event.Reminders()
.setUseDefault(false)
.setOverrides(Arrays.asList(reminderOverrides));
event.setReminders(reminders);
final String calendarId = "primary";
new Thread(new Runnable() {
@Override
public void run() {
try {
event = service.events().insert(calendarId, event).execute();
System.out.printf("Event created: %s\n", event.getHtmlLink());
if (title != null) {
title = null;
finish();
finish();
//System.exit(0);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public static Date addDays(Date date, int days) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
cal.add(java.util.Calendar.DATE, days);
return cal.getTime();
}
public boolean checkGooglePlayServicesAvailable() {
final int connectionStatusCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (GooglePlayServicesUtil.isUserRecoverableError(connectionStatusCode)) {
showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
return false;
}
return true;
}
void showGooglePlayServicesAvailabilityErrorDialog(final int connectionStatusCode) {
runOnUiThread(new Runnable() {
public void run() {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
connectionStatusCode, SMSDataFetch.this, REQUEST_GOOGLE_PLAY_SERVICES);
dialog.show();
}
});
}
public void haveGooglePlayServices() {
// check if there is already an account selected
if (credential.getSelectedAccountName() == null) {
// ask user to choose account
chooseAccount();
} else {
if (title != null && description != null) {
createEvent(credential);
}
}
}
private void chooseAccount() {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit();
editor.putBoolean(getString(R.string.smartrem), true).apply();
button.setText("Disable Smart Reminder");
startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
@Override
protected void onResume() {
super.onResume();
if (checkGooglePlayServicesAvailable()) {
haveGooglePlayServices();
}
}
}
要插入我在AsyncTask类下面创建的事件,但它不起作用,并在诸如凭证,事件等各个点给我NPE。
public class BGTask extends AsyncTask<Void, Void, Void> {
private static final String TAG = "BGTask";
Event event;
final HttpTransport transport = AndroidHttp.newCompatibleTransport();
final JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
private com.google.api.services.calendar.Calendar mService = null;
private String title, message;
private Context context;
GoogleAccountCredential credential;
com.google.api.services.calendar.Calendar client;
public BGTask(Context context, String title, String message) {
this.title = title;
this.message = message;
this.context = context;
}
@Override
protected void onPreExecute() {
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
credential = GoogleAccountCredential.usingOAuth2(context, Collections.singleton(CalendarScopes.CALENDAR));
credential.setSelectedAccountName(settings.getString("accountName", null));
credential.setSelectedAccountName("ankurjain30@gmail.com");
// Calendar client
client = new com.google.api.services.calendar.Calendar.Builder(
transport, jsonFactory, credential).setApplicationName("Google-CalendarAndroidSample/1.0")
.build();
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... voids) {
if (checkGooglePlayServicesAvailable()) {
haveGooglePlayServices();
}
return null;
}
public boolean checkGooglePlayServicesAvailable() {
final int connectionStatusCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
if (GooglePlayServicesUtil.isUserRecoverableError(connectionStatusCode)) {
return false;
}
return true;
}
private void haveGooglePlayServices() {
// check if there is already an account selected
if (credential.getSelectedAccountName() == null) {
// ask user to choose account
} else {
cre();
}
}
public void cre() {
event = new Event()
.setSummary(title)
/*.setLocation("Dhaka")*/
.setDescription(message);
TimeZone timeZone = TimeZone.getDefault();
DateTime startDateTime = new DateTime(new Date());
EventDateTime start = new EventDateTime()
.setDateTime(startDateTime)
.setTimeZone(timeZone.getID());
event.setStart(start);
DateTime endDateTime = new DateTime(new Date());
Log.e("start D ", startDateTime + "End Date " + endDateTime + timeZone.getID());
EventDateTime end = new EventDateTime()
.setDateTime(endDateTime).setTimeZone(timeZone.getID());
event.setEnd(end);
String[] recurrence = new String[]{"RRULE:FREQ=DAILY;COUNT=2"};
event.setRecurrence(Arrays.asList(recurrence));
/* EventAttendee[] attendees = new EventAttendee[]{
new EventAttendee().setEmail("abir@aksdj.com"),
new EventAttendee().setEmail("asdasd@andlk.com"),
};
event.setAttendees(Arrays.asList(attendees));*/
EventReminder[] reminderOverrides = new EventReminder[]{
//new EventReminder().setMethod("email").setMinutes(24 * 60),
new EventReminder().setMethod("popup").setMinutes(10),
};
Event.Reminders reminders = new Event.Reminders()
.setUseDefault(false)
.setOverrides(Arrays.asList(reminderOverrides));
event.setReminders(reminders);
final String calendarId = "primary";
try {
event = mService.events().insert(calendarId, event).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
有人可以帮我修理它。