Advertisement
Guest User

Untitled

a guest
May 26th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 27.07 KB | None | 0 0
  1. package com.google.android.gms.location.sample.locationupdates;
  2.  
  3. import android.Manifest;
  4. import android.app.Activity;
  5. import android.content.Intent;
  6. import android.content.IntentSender;
  7. import android.content.pm.PackageManager;
  8. import android.location.Location;
  9. import android.net.Uri;
  10. import android.os.Bundle;
  11. import android.os.Environment;
  12. import android.os.Looper;
  13. import android.provider.Settings;
  14. import android.support.annotation.NonNull;
  15. import android.support.design.widget.Snackbar;
  16. import android.support.v4.app.ActivityCompat;
  17. import android.support.v7.app.AppCompatActivity;
  18. import android.support.v7.widget.Toolbar;
  19. import android.util.Log;
  20. import android.view.View;
  21. import android.widget.Button;
  22. import android.widget.EditText;
  23. import android.widget.TextView;
  24. import android.widget.Toast;
  25.  
  26. import java.io.BufferedReader;
  27. import java.io.File;
  28. import java.io.FileInputStream;
  29. import java.io.FileNotFoundException;
  30. import java.io.FileOutputStream;
  31. import java.io.IOException;
  32. import java.io.InputStreamReader;
  33.  
  34. import com.google.android.gms.common.api.ApiException;
  35. import com.google.android.gms.common.api.ResolvableApiException;
  36. import com.google.android.gms.location.FusedLocationProviderClient;
  37. import com.google.android.gms.location.LocationCallback;
  38. import com.google.android.gms.location.LocationRequest;
  39. import com.google.android.gms.location.LocationResult;
  40. import com.google.android.gms.location.LocationServices;
  41. import com.google.android.gms.location.LocationSettingsRequest;
  42. import com.google.android.gms.location.LocationSettingsResponse;
  43. import com.google.android.gms.location.LocationSettingsStatusCodes;
  44. import com.google.android.gms.location.SettingsClient;
  45. import com.google.android.gms.tasks.OnCompleteListener;
  46. import com.google.android.gms.tasks.OnFailureListener;
  47. import com.google.android.gms.tasks.OnSuccessListener;
  48. import com.google.android.gms.tasks.Task;
  49.  
  50. import java.text.DateFormat;
  51. import java.util.Date;
  52. import java.util.Locale;
  53. import java.util.ArrayList;
  54. import java.util.List;
  55. /**
  56. * Using location settings.
  57. * Uses the {@link com.google.android.gms.location.SettingsApi} to ensure that the device's system
  58. * settings are properly configured for the app's location needs. When making a request to
  59. * Location services, the device's system settings may be in a state that prevents the app from
  60. * obtaining the location data that it needs. For example, GPS or Wi-Fi scanning may be switched
  61. * off. The {@code SettingsApi} makes it possible to determine if a device's system settings are
  62. * adequate for the location request, and to optionally invoke a dialog that allows the user to
  63. * enable the necessary settings.
  64. * This sample allows the user to request location updates using the ACCESS_FINE_LOCATION setting
  65. * (as specified in AndroidManifest.xml).
  66. */
  67. public class MainActivity extends AppCompatActivity {
  68. private static final String TAG = MainActivity.class.getSimpleName();
  69. /**
  70. * Code used in requesting runtime permissions.
  71. */
  72. private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
  73. /**
  74. * Constant used in the location settings dialog.
  75. */
  76. private static final int REQUEST_CHECK_SETTINGS = 0x1;
  77. /**
  78. * The desired interval for location updates. Inexact. Updates may be more or less frequent. 10000 bylo
  79. */
  80. private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 1000;
  81. /**
  82. * The fastest rate for active location updates. Exact. Updates will never be more frequent
  83. * than this value. bylo przez 2
  84. */
  85. private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
  86. UPDATE_INTERVAL_IN_MILLISECONDS / 100;
  87.  
  88. // Keys for storing activity state in the Bundle.
  89. private final static String KEY_REQUESTING_LOCATION_UPDATES = "requesting-location-updates";
  90. private final static String KEY_LOCATION = "location";
  91. private final static String KEY_LAST_UPDATED_TIME_STRING = "last-updated-time-string";
  92. /**
  93. * Provides access to the Fused Location Provider API.
  94. */
  95. private FusedLocationProviderClient mFusedLocationClient;
  96. /**
  97. * Provides access to the Location Settings API.
  98. */
  99. private SettingsClient mSettingsClient;
  100. /**
  101. * Stores parameters for requests to the FusedLocationProviderApi.
  102. */
  103. private LocationRequest mLocationRequest;
  104. /**
  105. * Stores the types of location services the client is interested in using. Used for checking
  106. * settings to determine if the device has optimal location settings.
  107. */
  108. private LocationSettingsRequest mLocationSettingsRequest;
  109. /**
  110. * Callback for Location events.
  111. */
  112. private LocationCallback mLocationCallback;
  113. /**
  114. * Represents a geographical location.
  115. */
  116. private Location mCurrentLocation;
  117. // UI Widgets.
  118. private Button mStartUpdatesButton;
  119. private Button mStopUpdatesButton;
  120. private Button mbutton1;
  121. private TextView mLastUpdateTimeTextView;
  122. private TextView mLatitudeTextView;
  123.  
  124.  
  125.  
  126. private TextView mLongitudeTextView;
  127. private TextView mSpeedFromCoordinatesView;
  128.  
  129. // Labels.
  130. private String mLatitudeLabel;
  131. private String mLongitudeLabel;
  132. private String mLastUpdateTimeLabel;
  133. private String mSpeedFromCoordinatesLabel;
  134. //
  135. private String mSpeed = "cssd";
  136.  
  137. /**
  138. * Tracks the status of the location updates request. Value changes when the user presses the
  139. * Start Updates and Stop Updates buttons.
  140. */
  141. private Boolean mRequestingLocationUpdates;
  142. /**
  143. * Time when the location was updated represented as a String.
  144. */
  145. private String mLastUpdateTime;
  146.  
  147.  
  148.  
  149. public String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/GPS";
  150. public List<Double> list;
  151.  
  152. @Override
  153. public void onCreate(Bundle savedInstanceState) {
  154. super.onCreate(savedInstanceState);
  155. setContentView(R.layout.main_activity);
  156. Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
  157. setSupportActionBar(toolbar);
  158. list = new ArrayList<>();
  159. // Locate the UI widgets.
  160. mStartUpdatesButton = (Button) findViewById(R.id.start_updates_button);
  161. mStopUpdatesButton = (Button) findViewById(R.id.stop_updates_button);
  162. mbutton1 = (Button) findViewById(R.id.button1);
  163. mLatitudeTextView = (TextView) findViewById(R.id.latitude_text);
  164. mLongitudeTextView = (TextView) findViewById(R.id.longitude_text);
  165. mLastUpdateTimeTextView = (TextView) findViewById(R.id.last_update_time_text);
  166. mSpeedFromCoordinatesView = (TextView) findViewById(R.id.speed_from_coordinates);
  167.  
  168.  
  169. // Set labels.
  170. mLatitudeLabel = getResources().getString(R.string.latitude_label);
  171. mLongitudeLabel = getResources().getString(R.string.longitude_label);
  172. mLastUpdateTimeLabel = getResources().getString(R.string.last_update_time_label);
  173. mSpeedFromCoordinatesLabel = getResources().getString(R.string.speed_from_coordinates_label);
  174.  
  175. mRequestingLocationUpdates = false;
  176. mLastUpdateTime = "";
  177.  
  178. File dir = new File(path);
  179. dir.mkdirs();
  180. // Update values using data stored in the Bundle.
  181. updateValuesFromBundle(savedInstanceState);
  182.  
  183. mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
  184. mSettingsClient = LocationServices.getSettingsClient(this);
  185.  
  186. // Kick off the process of building the LocationCallback, LocationRequest, and
  187. // LocationSettingsRequest objects.
  188. createLocationCallback();
  189.  
  190. //mSpeedFromCoordinatesView.setText(String.format(Locale.ENGLISH, "%s: %f", mSpeedFromCoordinatesLabel, a));
  191. createLocationRequest();
  192. buildLocationSettingsRequest();
  193.  
  194. }
  195.  
  196. /**
  197. * Updates fields based on data stored in the bundle.
  198. *
  199. * @param savedInstanceState The activity state saved in the Bundle.
  200. */
  201. private void updateValuesFromBundle(Bundle savedInstanceState) {
  202. if (savedInstanceState != null) {
  203.  
  204.  
  205. // Update the value of mRequestingLocationUpdates from the Bundle, and make sure that
  206. // the Start Updates and Stop Updates buttons are correctly enabled or disabled.
  207. if (savedInstanceState.keySet().contains(KEY_REQUESTING_LOCATION_UPDATES)) {
  208. mRequestingLocationUpdates = savedInstanceState.getBoolean(
  209. KEY_REQUESTING_LOCATION_UPDATES);
  210. }
  211.  
  212. // Update the value of mCurrentLocation from the Bundle and update the UI to show the
  213. // correct latitude and longitude.
  214. if (savedInstanceState.keySet().contains(KEY_LOCATION)) {
  215. // Since KEY_LOCATION was found in the Bundle, we can be sure that mCurrentLocation
  216. // is not null.
  217. mCurrentLocation = savedInstanceState.getParcelable(KEY_LOCATION);
  218. }
  219.  
  220. // Update the value of mLastUpdateTime from the Bundle and update the UI.
  221. if (savedInstanceState.keySet().contains(KEY_LAST_UPDATED_TIME_STRING)) {
  222. mLastUpdateTime = savedInstanceState.getString(KEY_LAST_UPDATED_TIME_STRING);
  223.  
  224. }
  225.  
  226.  
  227. updateUI();
  228.  
  229. }
  230. }
  231.  
  232. /**
  233. * Sets up the location request. Android has two location request settings:
  234. * {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control
  235. * the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in
  236. * the AndroidManifest.xml.
  237. * <p/>
  238. * When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update
  239. * interval (5 seconds), the Fused Location Provider API returns location updates that are
  240. * accurate to within a few feet.
  241. * <p/>
  242. * These settings are appropriate for mapping applications that show real-time location
  243. * updates.
  244. */
  245. private void createLocationRequest() {
  246. mLocationRequest = new LocationRequest();
  247.  
  248. // Sets the desired interval for active location updates. This interval is
  249. // inexact. You may not receive updates at all if no location sources are available, or
  250. // you may receive them slower than requested. You may also receive updates faster than
  251. // requested if other applications are requesting location at a faster interval.
  252. mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
  253.  
  254. // Sets the fastest rate for active location updates. This interval is exact, and your
  255. // application will never receive updates faster than this value.
  256. mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
  257.  
  258. mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  259. }
  260.  
  261. /**
  262. * Creates a callback for receiving location events.
  263. */
  264. private void createLocationCallback() {
  265. mLocationCallback = new LocationCallback() {
  266. @Override
  267. public void onLocationResult(LocationResult locationResult) {
  268. super.onLocationResult(locationResult);
  269.  
  270. mCurrentLocation = locationResult.getLastLocation();
  271. mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
  272.  
  273. updateLocationUI();
  274. list.add(mCurrentLocation.getLatitude());
  275. Double a = list.get(0);
  276. mSpeedFromCoordinatesView.setText(String.format(Locale.ENGLISH, "%s: %f", mSpeedFromCoordinatesLabel, a));
  277. }
  278. };
  279. }
  280.  
  281. /**
  282. * Uses a {@link com.google.android.gms.location.LocationSettingsRequest.Builder} to build
  283. * a {@link com.google.android.gms.location.LocationSettingsRequest} that is used for checking
  284. * if a device has the needed location settings.
  285. */
  286. private void buildLocationSettingsRequest() {
  287. LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
  288. builder.addLocationRequest(mLocationRequest);
  289. mLocationSettingsRequest = builder.build();
  290. }
  291.  
  292. @Override
  293. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  294. switch (requestCode) {
  295. // Check for the integer request code originally supplied to startResolutionForResult().
  296. case REQUEST_CHECK_SETTINGS:
  297. switch (resultCode) {
  298. case Activity.RESULT_OK:
  299. Log.i(TAG, "User agreed to make required location settings changes.");
  300. // Nothing to do. startLocationupdates() gets called in onResume again.
  301. break;
  302. case Activity.RESULT_CANCELED:
  303. Log.i(TAG, "User chose not to make required location settings changes.");
  304. mRequestingLocationUpdates = false;
  305. updateUI();
  306. break;
  307. }
  308. break;
  309. }
  310. }
  311.  
  312. /**
  313. * Handles the Start Updates button and requests start of location updates. Does nothing if
  314. * updates have already been requested.
  315. */
  316. public void startUpdatesButtonHandler(View view) {
  317. if (!mRequestingLocationUpdates) {
  318. mRequestingLocationUpdates = true;
  319. setButtonsEnabledState();
  320. startLocationUpdates();
  321. }
  322. }
  323.  
  324. /**
  325. * Handles the Stop Updates button, and requests removal of location updates.
  326. */
  327. public void stopUpdatesButtonHandler(View view) {
  328. // It is a good practice to remove location requests when the activity is in a paused or
  329. // stopped state. Doing so helps battery performance and is especially
  330. // recommended in applications that request frequent location updates.
  331. stopLocationUpdates();
  332. }
  333.  
  334. /**
  335. * Requests location updates from the FusedLocationApi. Note: we don't call this unless location
  336. * runtime permission has been granted.
  337. */
  338. private void startLocationUpdates() {
  339. // Begin by checking if the device has the necessary location settings.
  340. mSettingsClient.checkLocationSettings(mLocationSettingsRequest)
  341. .addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
  342. @Override
  343. public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
  344. Log.i(TAG, "All location settings are satisfied.");
  345.  
  346. //noinspection MissingPermission
  347. mFusedLocationClient.requestLocationUpdates(mLocationRequest,
  348. mLocationCallback, Looper.myLooper());
  349.  
  350. updateUI();
  351.  
  352. }
  353. })
  354. .addOnFailureListener(this, new OnFailureListener() {
  355. @Override
  356. public void onFailure(@NonNull Exception e) {
  357. int statusCode = ((ApiException) e).getStatusCode();
  358. switch (statusCode) {
  359. case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
  360. Log.i(TAG, "Location settings are not satisfied. Attempting to upgrade " +
  361. "location settings ");
  362. try {
  363. // Show the dialog by calling startResolutionForResult(), and check the
  364. // result in onActivityResult().
  365. ResolvableApiException rae = (ResolvableApiException) e;
  366. rae.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
  367. } catch (IntentSender.SendIntentException sie) {
  368. Log.i(TAG, "PendingIntent unable to execute request.");
  369. }
  370. break;
  371. case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
  372. String errorMessage = "Location settings are inadequate, and cannot be " +
  373. "fixed here. Fix in Settings.";
  374. Log.e(TAG, errorMessage);
  375. Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_LONG).show();
  376. mRequestingLocationUpdates = false;
  377. }
  378. updateUI();
  379.  
  380. }
  381. });
  382. }
  383.  
  384. /**
  385. * Updates all UI fields.
  386. */
  387. private void updateUI() {
  388. setButtonsEnabledState();
  389. updateLocationUI();
  390. }
  391.  
  392. /**
  393. * Disables both buttons when functionality is disabled due to insuffucient location settings.
  394. * Otherwise ensures that only one button is enabled at any time. The Start Updates button is
  395. * enabled if the user is not requesting location updates. The Stop Updates button is enabled
  396. * if the user is requesting location updates.
  397. */
  398. private void setButtonsEnabledState() {
  399. if (mRequestingLocationUpdates) {
  400. mStartUpdatesButton.setEnabled(false);
  401. mStopUpdatesButton.setEnabled(true);
  402. } else {
  403. mStartUpdatesButton.setEnabled(true);
  404. mStopUpdatesButton.setEnabled(false);
  405. }
  406. }
  407.  
  408. /**
  409. * Sets the value of the UI fields for the location latitude, longitude and last update time.
  410. */
  411. private void updateLocationUI() {
  412.  
  413. if (mCurrentLocation != null) {
  414.  
  415. //list.add(mCurrentLocation.getLatitude());
  416.  
  417. mLatitudeTextView.setText(String.format(Locale.ENGLISH, "%s: %f", mLatitudeLabel,
  418. mCurrentLocation.getLatitude()));
  419. mLongitudeTextView.setText(String.format(Locale.ENGLISH, "%s: %f", mLongitudeLabel,
  420. mCurrentLocation.getLongitude()));
  421. mLastUpdateTimeTextView.setText(String.format(Locale.ENGLISH, "%s: %s",
  422. mLastUpdateTimeLabel, mLastUpdateTime));
  423.  
  424. // Double a = list.get(0);
  425.  
  426.  
  427. // Double a = list.get(0);
  428.  
  429. // String dodawanie = list.get(0) + " " + String.valueOf(list.get(1)) + " " + String.valueOf(list.get(2));
  430. // String mSpeed = String.valueOf(mCurrentLocation.getLatitude());
  431.  
  432.  
  433. // mSpeedFromCoordinatesView.setText(String.format(Locale.ENGLISH, "%s: %f", mSpeedFromCoordinatesLabel,
  434. // a));
  435.  
  436. /* String state;
  437. state = Environment.getExternalStorageState();
  438. if (Environment.MEDIA_MOUNTED.equals(state)) {
  439. File Root = Environment.getExternalStorageDirectory();
  440. File Dir = new File(Root.getAbsolutePath() + "/GPS");
  441.  
  442. Dir.mkdir();
  443.  
  444. File file = new File(Dir, "pomiar.txt");
  445.  
  446. String Message = mLatitudeTextView.getText().toString() + " " + mLongitudeTextView.getText().toString() + " " +
  447. mLastUpdateTimeTextView.getText().toString() + "\n";
  448. try {
  449. FileOutputStream fileOutputStream = new FileOutputStream(file,true);
  450. fileOutputStream.write(Message.getBytes());
  451. fileOutputStream.close();
  452. // przez to gowno znika wszystko mLastUpdateTimeTextView.setText("");
  453. Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_LONG);
  454. } catch (FileNotFoundException e) {
  455. e.printStackTrace();
  456. } catch (IOException e) {
  457. e.printStackTrace();
  458. }
  459. } else {
  460. Toast.makeText(getApplicationContext(), "SD card not found", Toast.LENGTH_LONG);
  461.  
  462. }*/
  463. }
  464.  
  465. }
  466.  
  467. /**
  468. * Removes location updates from the FusedLocationApi.
  469. */
  470. private void stopLocationUpdates() {
  471. if (!mRequestingLocationUpdates) {
  472. Log.d(TAG, "stopLocationUpdates: updates never requested, no-op.");
  473. return;
  474. }
  475.  
  476. // It is a good practice to remove location requests when the activity is in a paused or
  477. // stopped state. Doing so helps battery performance and is especially
  478. // recommended in applications that request frequent location updates.
  479. mFusedLocationClient.removeLocationUpdates(mLocationCallback)
  480. .addOnCompleteListener(this, new OnCompleteListener<Void>() {
  481. @Override
  482. public void onComplete(@NonNull Task<Void> task) {
  483. mRequestingLocationUpdates = false;
  484. setButtonsEnabledState();
  485. }
  486. });
  487. }
  488.  
  489. @Override
  490. public void onResume() {
  491. super.onResume();
  492. // Within {@code onPause()}, we remove location updates. Here, we resume receiving
  493. // location updates if the user has requested them.
  494. if (mRequestingLocationUpdates && checkPermissions()) {
  495. startLocationUpdates();
  496. } else if (!checkPermissions()) {
  497. requestPermissions();
  498. }
  499. updateUI();
  500. }
  501.  
  502. @Override
  503. protected void onPause() {
  504. super.onPause();
  505.  
  506. // Remove location updates to save battery.
  507. stopLocationUpdates();
  508. }
  509.  
  510. /**
  511. * Stores activity data in the Bundle.
  512. */
  513. public void onSaveInstanceState(Bundle savedInstanceState) {
  514. savedInstanceState.putBoolean(KEY_REQUESTING_LOCATION_UPDATES, mRequestingLocationUpdates);
  515. savedInstanceState.putParcelable(KEY_LOCATION, mCurrentLocation);
  516. savedInstanceState.putString(KEY_LAST_UPDATED_TIME_STRING, mLastUpdateTime);
  517. super.onSaveInstanceState(savedInstanceState);
  518. }
  519.  
  520. /**
  521. * Shows a {@link Snackbar}.
  522. * @param mainTextStringId The id for the string resource for the Snackbar text.
  523. * @param actionStringId The text of the action item.
  524. * @param listener The listener associated with the Snackbar action.
  525. */
  526. private void showSnackbar(final int mainTextStringId, final int actionStringId,
  527. View.OnClickListener listener) {
  528. Snackbar.make(
  529. findViewById(android.R.id.content),
  530. getString(mainTextStringId),
  531. Snackbar.LENGTH_INDEFINITE)
  532. .setAction(getString(actionStringId), listener).show();
  533. }
  534.  
  535. /**
  536. * Return the current state of the permissions needed.
  537. */
  538. private boolean checkPermissions() {
  539. int permissionState = ActivityCompat.checkSelfPermission(this,
  540. Manifest.permission.ACCESS_FINE_LOCATION);
  541. return permissionState == PackageManager.PERMISSION_GRANTED;
  542. }
  543.  
  544. private void requestPermissions() {
  545. boolean shouldProvideRationale =
  546. ActivityCompat.shouldShowRequestPermissionRationale(this,
  547. Manifest.permission.ACCESS_FINE_LOCATION);
  548.  
  549. // Provide an additional rationale to the user. This would happen if the user denied the
  550. // request previously, but didn't check the "Don't ask again" checkbox.
  551. if (shouldProvideRationale) {
  552. Log.i(TAG, "Displaying permission rationale to provide additional context.");
  553. showSnackbar(R.string.permission_rationale,
  554. android.R.string.ok, new View.OnClickListener() {
  555. @Override
  556. public void onClick(View view) {
  557. // Request permission
  558. ActivityCompat.requestPermissions(MainActivity.this,
  559. new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
  560. REQUEST_PERMISSIONS_REQUEST_CODE);
  561. }
  562. });
  563. } else {
  564. Log.i(TAG, "Requesting permission");
  565. // Request permission. It's possible this can be auto answered if device policy
  566. // sets the permission in a given state or the user denied the permission
  567. // previously and checked "Never ask again".
  568. ActivityCompat.requestPermissions(MainActivity.this,
  569. new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
  570. REQUEST_PERMISSIONS_REQUEST_CODE);
  571. }
  572. }
  573.  
  574. /**
  575. * Callback received when a permissions request has been completed.
  576. */
  577. @Override
  578. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
  579. @NonNull int[] grantResults) {
  580. Log.i(TAG, "onRequestPermissionResult");
  581. if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
  582. if (grantResults.length <= 0) {
  583. // If user interaction was interrupted, the permission request is cancelled and you
  584. // receive empty arrays.
  585. Log.i(TAG, "User interaction was cancelled.");
  586. } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  587. if (mRequestingLocationUpdates) {
  588. Log.i(TAG, "Permission granted, updates requested, starting location updates");
  589. startLocationUpdates();
  590. }
  591. } else {
  592. // Permission denied.
  593.  
  594. // Notify the user via a SnackBar that they have rejected a core permission for the
  595. // app, which makes the Activity useless. In a real app, core permissions would
  596. // typically be best requested during a welcome-screen flow.
  597.  
  598. // Additionally, it is important to remember that a permission might have been
  599. // rejected without asking the user for permission (device policy or "Never ask
  600. // again" prompts). Therefore, a user interface affordance is typically implemented
  601. // when permissions are denied. Otherwise, your app could appear unresponsive to
  602. // touches or interactions which have required permissions.
  603. showSnackbar(R.string.permission_denied_explanation,
  604. R.string.settings, new View.OnClickListener() {
  605. @Override
  606. public void onClick(View view) {
  607. // Build intent that displays the App settings screen.
  608. Intent intent = new Intent();
  609. intent.setAction(
  610. Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
  611. Uri uri = Uri.fromParts("package",
  612. BuildConfig.APPLICATION_ID, null);
  613. intent.setData(uri);
  614. intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  615. startActivity(intent);
  616. }
  617. });
  618. }
  619. }
  620. }
  621.  
  622. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement