Advertisement
Guest User

Untitled

a guest
Feb 17th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.87 KB | None | 0 0
  1. package net.strongjoshua.test;
  2.  
  3. import android.Manifest;
  4. import android.accounts.AccountManager;
  5. import android.app.Dialog;
  6. import android.content.Context;
  7. import android.content.Intent;
  8. import android.content.SharedPreferences;
  9. import android.graphics.RectF;
  10. import android.net.ConnectivityManager;
  11. import android.net.NetworkInfo;
  12. import android.os.AsyncTask;
  13. import android.os.Bundle;
  14. import android.support.annotation.NonNull;
  15. import android.support.v7.app.AppCompatActivity;
  16. import android.text.TextUtils;
  17.  
  18. import com.alamkanak.weekview.MonthLoader;
  19. import com.alamkanak.weekview.WeekView;
  20. import com.alamkanak.weekview.WeekViewEvent;
  21. import com.google.android.gms.common.ConnectionResult;
  22. import com.google.android.gms.common.GoogleApiAvailability;
  23. import com.google.api.client.extensions.android.http.AndroidHttp;
  24. import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
  25. import com.google.api.client.googleapis.extensions.android.gms.auth.GooglePlayServicesAvailabilityIOException;
  26. import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
  27. import com.google.api.client.http.HttpTransport;
  28. import com.google.api.client.json.JsonFactory;
  29. import com.google.api.client.json.jackson2.JacksonFactory;
  30. import com.google.api.client.util.DateTime;
  31. import com.google.api.client.util.ExponentialBackOff;
  32. import com.google.api.services.calendar.CalendarScopes;
  33. import com.google.api.services.calendar.model.Event;
  34. import com.google.api.services.calendar.model.Events;
  35.  
  36. import java.io.IOException;
  37. import java.util.ArrayList;
  38. import java.util.Arrays;
  39. import java.util.List;
  40.  
  41. import pub.devrel.easypermissions.AfterPermissionGranted;
  42. import pub.devrel.easypermissions.EasyPermissions;
  43.  
  44. public class MainActivity extends AppCompatActivity implements
  45. WeekView.EventClickListener,
  46. MonthLoader.MonthChangeListener,
  47. WeekView.EventLongPressListener,
  48. EasyPermissions.PermissionCallbacks {
  49. private static final String[] SCOPES = {CalendarScopes.CALENDAR_READONLY};
  50. static final int REQUEST_ACCOUNT_PICKER = 1000;
  51. static final int REQUEST_AUTHORIZATION = 1001;
  52. static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002;
  53. static final int REQUEST_PERMISSION_GET_ACCOUNTS = 1003;
  54. private static final String PREF_ACCOUNT_NAME = "accountName";
  55.  
  56. GoogleAccountCredential credentials;
  57.  
  58. @Override
  59. protected void onCreate(Bundle savedInstanceState) {
  60. super.onCreate(savedInstanceState);
  61. setContentView(R.layout.activity_main);
  62.  
  63. WeekView weekView = findViewById(R.id.weekView);
  64. weekView.setOnEventClickListener(this);
  65. weekView.setMonthChangeListener(this);
  66. weekView.setEventLongPressListener(this);
  67.  
  68. credentials = GoogleAccountCredential.usingOAuth2(
  69. getApplicationContext(), Arrays.asList(SCOPES))
  70. .setBackOff(new ExponentialBackOff());
  71. getResultsFromApi();
  72. }
  73.  
  74. @Override
  75. public void onEventClick(WeekViewEvent event, RectF eventRect) {
  76.  
  77. }
  78.  
  79. @Override
  80. public List<? extends WeekViewEvent> onMonthChange(int newYear, int newMonth) {
  81. return new ArrayList<>();
  82. }
  83.  
  84. @Override
  85. public void onEventLongPress(WeekViewEvent event, RectF eventRect) {
  86.  
  87. }
  88.  
  89. /**
  90. * Attempt to call the API, after verifying that all the preconditions are
  91. * satisfied. The preconditions are: Google Play Services installed, an
  92. * account was selected and the device currently has online access. If any
  93. * of the preconditions are not satisfied, the app will prompt the user as
  94. * appropriate.
  95. */
  96. private void getResultsFromApi() {
  97. if (! isGooglePlayServicesAvailable()) {
  98. acquireGooglePlayServices();
  99. } else if (credentials.getSelectedAccountName() == null) {
  100. chooseAccount();
  101. } else if (! isDeviceOnline()) {
  102. System.out.println("No network connection available.");
  103. } else {
  104. new MakeRequestTask(credentials).execute();
  105. }
  106. }
  107.  
  108. /**
  109. * Attempts to set the account used with the API credentials. If an account
  110. * name was previously saved it will use that one; otherwise an account
  111. * picker dialog will be shown to the user. Note that the setting the
  112. * account to use with the credentials object requires the app to have the
  113. * GET_ACCOUNTS permission, which is requested here if it is not already
  114. * present. The AfterPermissionGranted annotation indicates that this
  115. * function will be rerun automatically whenever the GET_ACCOUNTS permission
  116. * is granted.
  117. */
  118. @AfterPermissionGranted(REQUEST_PERMISSION_GET_ACCOUNTS)
  119. private void chooseAccount() {
  120. if (EasyPermissions.hasPermissions(
  121. this, Manifest.permission.GET_ACCOUNTS)) {
  122. String accountName = getPreferences(Context.MODE_PRIVATE)
  123. .getString(PREF_ACCOUNT_NAME, null);
  124. if (accountName != null) {
  125. credentials.setSelectedAccountName(accountName);
  126. getResultsFromApi();
  127. } else {
  128. // Start a dialog from which the user can choose an account
  129. startActivityForResult(
  130. credentials.newChooseAccountIntent(),
  131. REQUEST_ACCOUNT_PICKER);
  132. }
  133. } else {
  134. // Request the GET_ACCOUNTS permission via a user dialog
  135. EasyPermissions.requestPermissions(
  136. this,
  137. "This app needs to access your Google account (via Contacts).",
  138. REQUEST_PERMISSION_GET_ACCOUNTS,
  139. Manifest.permission.GET_ACCOUNTS);
  140. }
  141. }
  142.  
  143. /**
  144. * Called when an activity launched here (specifically, AccountPicker
  145. * and authorization) exits, giving you the requestCode you started it with,
  146. * the resultCode it returned, and any additional data from it.
  147. * @param requestCode code indicating which activity result is incoming.
  148. * @param resultCode code indicating the result of the incoming
  149. * activity result.
  150. * @param data Intent (containing result data) returned by incoming
  151. * activity result.
  152. */
  153. @Override
  154. protected void onActivityResult(
  155. int requestCode, int resultCode, Intent data) {
  156. super.onActivityResult(requestCode, resultCode, data);
  157. switch(requestCode) {
  158. case REQUEST_GOOGLE_PLAY_SERVICES:
  159. if (resultCode != RESULT_OK) {
  160. System.out.println(
  161. "This app requires Google Play Services. Please install " +
  162. "Google Play Services on your device and relaunch this app.");
  163. } else {
  164. getResultsFromApi();
  165. }
  166. break;
  167. case REQUEST_ACCOUNT_PICKER:
  168. if (resultCode == RESULT_OK && data != null &&
  169. data.getExtras() != null) {
  170. String accountName =
  171. data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
  172. if (accountName != null) {
  173. SharedPreferences settings =
  174. getPreferences(Context.MODE_PRIVATE);
  175. SharedPreferences.Editor editor = settings.edit();
  176. editor.putString(PREF_ACCOUNT_NAME, accountName);
  177. editor.apply();
  178. credentials.setSelectedAccountName(accountName);
  179. getResultsFromApi();
  180. }
  181. }
  182. break;
  183. case REQUEST_AUTHORIZATION:
  184. if (resultCode == RESULT_OK) {
  185. getResultsFromApi();
  186. }
  187. break;
  188. }
  189. }
  190.  
  191. /**
  192. * Respond to requests for permissions at runtime for API 23 and above.
  193. * @param requestCode The request code passed in
  194. * requestPermissions(android.app.Activity, String, int, String[])
  195. * @param permissions The requested permissions. Never null.
  196. * @param grantResults The grant results for the corresponding permissions
  197. * which is either PERMISSION_GRANTED or PERMISSION_DENIED. Never null.
  198. */
  199. @Override
  200. public void onRequestPermissionsResult(int requestCode,
  201. @NonNull String[] permissions,
  202. @NonNull int[] grantResults) {
  203. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  204. EasyPermissions.onRequestPermissionsResult(
  205. requestCode, permissions, grantResults, this);
  206. }
  207.  
  208. /**
  209. * Callback for when a permission is granted using the EasyPermissions
  210. * library.
  211. * @param requestCode The request code associated with the requested
  212. * permission
  213. * @param list The requested permission list. Never null.
  214. */
  215. @Override
  216. public void onPermissionsGranted(int requestCode, List<String> list) {
  217. // Do nothing.
  218. }
  219.  
  220. /**
  221. * Callback for when a permission is denied using the EasyPermissions
  222. * library.
  223. * @param requestCode The request code associated with the requested
  224. * permission
  225. * @param list The requested permission list. Never null.
  226. */
  227. @Override
  228. public void onPermissionsDenied(int requestCode, List<String> list) {
  229. // Do nothing.
  230. }
  231.  
  232. /**
  233. * Checks whether the device currently has a network connection.
  234. * @return true if the device has a network connection, false otherwise.
  235. */
  236. private boolean isDeviceOnline() {
  237. ConnectivityManager connMgr =
  238. (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  239. NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
  240. return (networkInfo != null && networkInfo.isConnected());
  241. }
  242.  
  243. /**
  244. * Check that Google Play services APK is installed and up to date.
  245. * @return true if Google Play Services is available and up to
  246. * date on this device; false otherwise.
  247. */
  248. private boolean isGooglePlayServicesAvailable() {
  249. GoogleApiAvailability apiAvailability =
  250. GoogleApiAvailability.getInstance();
  251. final int connectionStatusCode =
  252. apiAvailability.isGooglePlayServicesAvailable(this);
  253. return connectionStatusCode == ConnectionResult.SUCCESS;
  254. }
  255.  
  256. /**
  257. * Attempt to resolve a missing, out-of-date, invalid or disabled Google
  258. * Play Services installation via a user dialog, if possible.
  259. */
  260. private void acquireGooglePlayServices() {
  261. GoogleApiAvailability apiAvailability =
  262. GoogleApiAvailability.getInstance();
  263. final int connectionStatusCode =
  264. apiAvailability.isGooglePlayServicesAvailable(this);
  265. if (apiAvailability.isUserResolvableError(connectionStatusCode)) {
  266. showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
  267. }
  268. }
  269.  
  270.  
  271. /**
  272. * Display an error dialog showing that Google Play Services is missing
  273. * or out of date.
  274. * @param connectionStatusCode code describing the presence (or lack of)
  275. * Google Play Services on this device.
  276. */
  277. void showGooglePlayServicesAvailabilityErrorDialog(
  278. final int connectionStatusCode) {
  279. GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
  280. Dialog dialog = apiAvailability.getErrorDialog(
  281. MainActivity.this,
  282. connectionStatusCode,
  283. REQUEST_GOOGLE_PLAY_SERVICES);
  284. dialog.show();
  285. }
  286.  
  287. /**
  288. * An asynchronous task that handles the Google Calendar API call.
  289. * Placing the API calls in their own task ensures the UI stays responsive.
  290. */
  291. private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
  292. private com.google.api.services.calendar.Calendar mService = null;
  293. private Exception mLastError = null;
  294.  
  295. MakeRequestTask(GoogleAccountCredential credential) {
  296. HttpTransport transport = AndroidHttp.newCompatibleTransport();
  297. JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  298. mService = new com.google.api.services.calendar.Calendar.Builder(
  299. transport, jsonFactory, credential)
  300. .setApplicationName("Google Calendar API Android Quickstart")
  301. .build();
  302. }
  303.  
  304. /**
  305. * Background task to call Google Calendar API.
  306. * @param params no parameters needed for this task.
  307. */
  308. @Override
  309. protected List<String> doInBackground(Void... params) {
  310. try {
  311. return getDataFromApi();
  312. } catch (Exception e) {
  313. mLastError = e;
  314. cancel(true);
  315. return null;
  316. }
  317. }
  318.  
  319. /**
  320. * Fetch a list of the next 10 events from the primary calendar.
  321. * @return List of Strings describing returned events.
  322. * @throws IOException
  323. */
  324. private List<String> getDataFromApi() throws IOException {
  325. // List the next 10 events from the primary calendar.
  326. DateTime now = new DateTime(System.currentTimeMillis());
  327. List<String> eventStrings = new ArrayList<String>();
  328. Events events = mService.events().list("primary")
  329. .setMaxResults(10)
  330. .setTimeMin(now)
  331. .setOrderBy("startTime")
  332. .setSingleEvents(true)
  333. .execute();
  334. List<Event> items = events.getItems();
  335.  
  336. for (Event event : items) {
  337. DateTime start = event.getStart().getDateTime();
  338. if (start == null) {
  339. // All-day events don't have start times, so just use
  340. // the start date.
  341. start = event.getStart().getDate();
  342. }
  343. eventStrings.add(
  344. String.format("%s (%s)", event.getSummary(), start));
  345. }
  346. return eventStrings;
  347. }
  348.  
  349.  
  350. @Override
  351. protected void onPreExecute() {
  352. // mOutputText.setText("");
  353. // mProgress.show();
  354. }
  355.  
  356. @Override
  357. protected void onPostExecute(List<String> output) {
  358. // mProgress.hide();
  359. if (output == null || output.size() == 0) {
  360. System.out.println("No results returned.");
  361. } else {
  362. output.add(0, "Data retrieved using the Google Calendar API:");
  363. System.out.println(TextUtils.join("\n", output));
  364. }
  365. }
  366.  
  367. @Override
  368. protected void onCancelled() {
  369. // mProgress.hide();
  370. if (mLastError != null) {
  371. if (mLastError instanceof GooglePlayServicesAvailabilityIOException) {
  372. showGooglePlayServicesAvailabilityErrorDialog(
  373. ((GooglePlayServicesAvailabilityIOException) mLastError)
  374. .getConnectionStatusCode());
  375. } else if (mLastError instanceof UserRecoverableAuthIOException) {
  376. startActivityForResult(
  377. ((UserRecoverableAuthIOException) mLastError).getIntent(),
  378. MainActivity.REQUEST_AUTHORIZATION);
  379. } else {
  380. System.out.println("The following error occurred:\n"
  381. + mLastError.getMessage());
  382. }
  383. } else {
  384. System.out.println("Request cancelled.");
  385. }
  386. }
  387. }
  388. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement