├── .gitignore
├── .idea
├── .name
├── compiler.xml
├── copyright
│ └── profiles_settings.xml
├── encodings.xml
├── gradle.xml
├── misc.xml
├── modules.xml
├── runConfigurations.xml
└── vcs.xml
├── LICENSE
├── README.md
├── app
├── .gitignore
├── build.gradle
├── google-services.json
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── googleplayservicelocationsupport
│ │ ├── AppApplication.java
│ │ ├── FragmentLocationActivity.java
│ │ ├── LocationFragment.java
│ │ ├── LocationService.java
│ │ └── MainActivity.java
│ └── res
│ ├── layout
│ ├── activity_fragment_location.xml
│ └── activity_main.xml
│ ├── menu
│ └── menu.xml
│ ├── mipmap-hdpi
│ └── ic_launcher.png
│ ├── mipmap-mdpi
│ └── ic_launcher.png
│ ├── mipmap-xhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxhdpi
│ └── ic_launcher.png
│ ├── mipmap-xxxhdpi
│ └── ic_launcher.png
│ └── values
│ ├── colors.xml
│ ├── strings.xml
│ └── styles.xml
├── build.gradle
├── google-support-location
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ └── java
│ └── com
│ └── github
│ └── akashandroid90
│ └── googlesupport
│ └── location
│ ├── AppLocation.java
│ ├── AppLocationActivity.java
│ ├── AppLocationCompatActivity.java
│ ├── AppLocationFragment.java
│ ├── AppLocationIntentService.java
│ ├── AppLocationService.java
│ ├── AppLocationSupportFragment.java
│ ├── GoogleContextSupportLocation.java
│ └── GoogleSupportLocation.java
├── gradle.properties
├── gradlew
├── gradlew.bat
├── images
├── four.png
├── one.png
├── three.png
└── two.png
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 |
--------------------------------------------------------------------------------
/.idea/.name:
--------------------------------------------------------------------------------
1 | GooglePlayServiceLocationSupport
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
18 |
19 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # GooglePlayServiceLocationSupport
2 | This library is used to handle location requests and maintains the flow with permission checks in marshmallow.
3 |
4 | [](https://android-arsenal.com/details/1/2939)
5 |
6 | [  ](https://bintray.com/akashandroid90/maven/google-support-location/_latestVersion)
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 | 
15 | 
16 | 
17 | 
18 | Gradle
19 | -------------------------
20 |
21 | ```
22 |
23 | dependencies {
24 | compile 'com.github.akashandroid90.googlesupport:google-support-location:1.18@aar'
25 | }
26 |
27 | ```
28 |
29 | Usage
30 | -----
31 |
32 | for activity
33 |
34 | ```java
35 | public class MainActivity extends AppLocationActivity {}
36 | ```
37 | or
38 | ```java
39 | public class MainActivity extends AppLocationCompatActivity {}
40 | ```
41 | and for fragment
42 | ```java
43 | public class LocationFragment extends AppLocationFragment {}
44 | ```
45 |
46 | Donations
47 | ---------
48 |
49 | This project needs you! If you would like to support this project's further development, the creator of this project or the continuous maintenance of this project, feel free to donate. Your donation is highly appreciated (and I love food, coffee and beer). Thank you!
50 |
51 | **PayPal**
52 |
53 | * **[Donate $5]**: Thank's for creating this project, here's a coffee (or some beer) for you!
54 | * **[Donate $10]**: Wow, I am stunned. Let me take you to the movies!
55 | * **[Donate $15]**: I really appreciate your work, let's grab some lunch!
56 | * **[Donate $25]**: That's some awesome stuff you did right there, dinner is on me!
57 | * **[Donate $50]**: I really really want to support this project, great job!
58 | * **[Donate $100]**: You are the man! This project saved me hours (if not days) of struggle and hard work, simply awesome!
59 | * **[Donate $2799]**: Go buddy, buy Macbook Pro for yourself!
60 | Of course, you can also choose what you want to donate, all donations are awesome!
61 |
62 |
63 |
64 | Developed By
65 | --------------------
66 | Akash Jain
67 |
68 |
69 | [Donate $5]: https://www.paypal.me/akashandroid/5
70 | [Donate $10]: https://www.paypal.me/akashandroid/10
71 | [Donate $15]: https://www.paypal.me/akashandroid/15
72 | [Donate $25]: https://www.paypal.me/akashandroid/25
73 | [Donate $50]: https://www.paypal.me/akashandroid/50
74 | [Donate $100]: https://www.paypal.me/akashandroid/100
75 | [Donate $2799]: https://www.paypal.me/akashandroid/2799
76 |
77 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion compilesdk
5 | buildToolsVersion buildtool
6 | defaultConfig {
7 | applicationId "com.googleplayservicelocationsupport"
8 | minSdkVersion minsdk
9 | targetSdkVersion targetsdk
10 | versionCode 6
11 | versionName "1.4"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | signingConfig signingConfigs.config
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | // compile 'com.github.akashandroid90.googlesupport:google-support-location:1.15'
24 | compile "com.google.firebase:firebase-ads:$playservicelib"
25 | compile project(':google-support-location')
26 | }
27 | apply plugin: 'com.google.gms.google-services'
--------------------------------------------------------------------------------
/app/google-services.json:
--------------------------------------------------------------------------------
1 | {
2 | "project_info": {
3 | "project_number": "663285482468",
4 | "firebase_url": "https://admob-app-id-2039606611.firebaseio.com",
5 | "project_id": "admob-app-id-9038606611",
6 | "storage_bucket": "admob-app-id-9038606611.appspot.com"
7 | },
8 | "client": [
9 | {
10 | "client_info": {
11 | "mobilesdk_app_id": "1:663285482468:android:25tc0f66b0510b85",
12 | "android_client_info": {
13 | "package_name": "com.googleplayservicelocationsupport"
14 | }
15 | },
16 | "oauth_client": [
17 | {
18 | "client_id": "663280482468-qcueabggxpvfruo2hh04ohg9f2u6m4tq59qi.apps.googleusercontent.com",
19 | "client_type": 1,
20 | "android_info": {
21 | "package_name": "com.googleplayservicelocationsupport",
22 | "certificate_hash": "C062E17FW90E99794B6A80A1C94C07BDE3723C0A"
23 | }
24 | },
25 | {
26 | "client_id": "663285482478-hmTqg7ng0vb54far2g9li374ti55i7o3.apps.googleusercontent.com",
27 | "client_type": 3
28 | }
29 | ],
30 | "api_key": [
31 | {
32 | "current_key": "AIzaSyBtNHif8eS5VmniWQBzZ-MObqY1oAKqOjo"
33 | }
34 | ],
35 | "services": {
36 | "analytics_service": {
37 | "status": 1
38 | },
39 | "appinvite_service": {
40 | "status": 1,
41 | "other_platform_oauth_client": []
42 | },
43 | "ads_service": {
44 | "status": 2
45 | }
46 | }
47 | }
48 | ],
49 | "configuration_version": "1"
50 | }
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in D:\ide\android\AndroidSDK/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/app/src/main/java/com/googleplayservicelocationsupport/AppApplication.java:
--------------------------------------------------------------------------------
1 | package com.googleplayservicelocationsupport;
2 |
3 | import android.app.Application;
4 |
5 | import com.google.android.gms.ads.MobileAds;
6 |
7 | /**
8 | * Created by Akash Jain on 28-May-16.
9 | */
10 | public class AppApplication extends Application {
11 |
12 | @Override
13 | public void onCreate() {
14 | super.onCreate();
15 | MobileAds.initialize(getApplicationContext(), "ca-app-pub-5883105630361246~9038606611");
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/app/src/main/java/com/googleplayservicelocationsupport/FragmentLocationActivity.java:
--------------------------------------------------------------------------------
1 | package com.googleplayservicelocationsupport;
2 |
3 | import android.content.Intent;
4 | import android.net.Uri;
5 | import android.os.Bundle;
6 | import android.support.v7.app.AppCompatActivity;
7 | import android.support.v7.widget.Toolbar;
8 | import android.view.Menu;
9 | import android.view.MenuInflater;
10 | import android.view.MenuItem;
11 |
12 | import com.google.android.gms.ads.AdListener;
13 | import com.google.android.gms.ads.AdRequest;
14 | import com.google.android.gms.ads.InterstitialAd;
15 |
16 | public class FragmentLocationActivity extends AppCompatActivity {
17 |
18 | private InterstitialAd mInterstitialAd;
19 |
20 | @Override
21 | protected void onCreate(Bundle savedInstanceState) {
22 | super.onCreate(savedInstanceState);
23 | setContentView(R.layout.activity_fragment_location);
24 | mInterstitialAd = new InterstitialAd(this);
25 | mInterstitialAd.setAdUnitId(getResources().getString(R.string.interstitial_ad));
26 | mInterstitialAd.setAdListener(new AdListener() {
27 | @Override
28 | public void onAdClosed() {
29 | finish();
30 | }
31 | });
32 | AdRequest adRequest = new AdRequest.Builder().build();
33 | mInterstitialAd.loadAd(adRequest);
34 |
35 | Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
36 | setSupportActionBar(toolbar);
37 | }
38 |
39 | @Override
40 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
41 | getSupportFragmentManager().getFragments().get(0).onActivityResult(requestCode, resultCode, data);
42 | super.onActivityResult(requestCode, resultCode, data);
43 | }
44 |
45 | @Override
46 | public boolean onCreateOptionsMenu(Menu menu) {
47 | final MenuInflater inflater = getMenuInflater();
48 | inflater.inflate(R.menu.menu, menu);
49 | return super.onCreateOptionsMenu(menu);
50 | }
51 |
52 | @Override
53 | public boolean onOptionsItemSelected(MenuItem item) {
54 | Intent intent;
55 | switch (item.getItemId()) {
56 | case R.id.play_store:
57 | intent = new Intent(Intent.ACTION_VIEW);
58 | intent.setData(Uri.parse("market://details?id=com.googleplayservicelocationsupport"));
59 | startActivity(intent);
60 | return true;
61 | case R.id.other_apps:
62 | intent = new Intent(Intent.ACTION_VIEW);
63 | intent.setData(Uri.parse("market://search?q=pub:AkashJain"));
64 | startActivity(intent);
65 | return true;
66 | case R.id.github:
67 | intent = new Intent(Intent.ACTION_VIEW);
68 | intent.setData(Uri.parse("https://github.com/akashandroid90/GooglePlayServiceLocationSupport"));
69 | startActivity(intent);
70 | return true;
71 | case R.id.share:
72 | Intent sendIntent = new Intent();
73 | sendIntent.setAction(Intent.ACTION_SEND);
74 | sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Material Icon");
75 | sendIntent.putExtra(Intent.EXTRA_TEXT, "http://play.google.com/store/apps/details?id=com.googleplayservicelocationsupport");
76 | sendIntent.setType("text/plain");
77 | startActivity(sendIntent);
78 | return true;
79 | }
80 | return super.onOptionsItemSelected(item);
81 | }
82 |
83 | @Override
84 | public void onBackPressed() {
85 | if (mInterstitialAd != null && mInterstitialAd.isLoaded())
86 | mInterstitialAd.show();
87 | else finish();
88 | }
89 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/googleplayservicelocationsupport/LocationFragment.java:
--------------------------------------------------------------------------------
1 | package com.googleplayservicelocationsupport;
2 |
3 | import android.content.ComponentName;
4 | import android.content.Context;
5 | import android.content.DialogInterface;
6 | import android.content.Intent;
7 | import android.content.ServiceConnection;
8 | import android.location.Location;
9 | import android.os.Bundle;
10 | import android.os.Handler;
11 | import android.os.IBinder;
12 | import android.support.annotation.Nullable;
13 | import android.view.LayoutInflater;
14 | import android.view.View;
15 | import android.view.ViewGroup;
16 | import android.widget.TextView;
17 | import android.widget.Toast;
18 |
19 | import com.github.akashandroid90.googlesupport.location.AppLocationFragment;
20 | import com.google.android.gms.ads.AdRequest;
21 | import com.google.android.gms.ads.AdView;
22 | import com.google.android.gms.common.ConnectionResult;
23 | import com.google.android.gms.location.LocationRequest;
24 |
25 | /**
26 | * Created by Akash Jain on 12-Dec-15.
27 | */
28 | public class LocationFragment extends AppLocationFragment {
29 | private TextView mOldLocation, mNewLocation;
30 | public LocationService mService;
31 |
32 | @Override
33 | public void newLocation(Location location) {
34 | mNewLocation.setText(location.getLatitude() + "," + location.getLongitude());
35 | }
36 |
37 | @Override
38 | public void myCurrentLocation(Location currentLocation) {
39 | mOldLocation.setText(currentLocation.getLatitude() + "," + currentLocation.getLongitude());
40 | }
41 |
42 | @Override
43 | public void onActivityResultError(int resultCode, ServiceError serviceError, ConnectionResult connectionResult) {
44 | switch (serviceError) {
45 | case GOOGLE_PLAY_SERVICE_ERROR:
46 | break;
47 | case LOCATION_SETTING_ERROR:
48 | break;
49 | }
50 | }
51 |
52 | @Override
53 | public void onServiceDialogCancel(DialogInterface dialog, ConnectionResult connectionResult) {
54 | if (getGoogleApiAvailability().isUserResolvableError(connectionResult.getErrorCode()))
55 | showServiceErrorDialog(connectionResult);
56 | else
57 | Toast.makeText(mContext, connectionResult.getErrorMessage(), Toast.LENGTH_SHORT).show();
58 | }
59 |
60 | @Nullable
61 | @Override
62 | public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
63 | return inflater.inflate(R.layout.activity_main, container, false);
64 | }
65 |
66 | @Override
67 | public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
68 | view.findViewById(R.id.btn_fragment).setVisibility(View.GONE);
69 | view.findViewById(R.id.btn_location).setVisibility(View.VISIBLE);
70 | view.findViewById(R.id.btn_location).setOnClickListener(new View.OnClickListener() {
71 | @Override
72 | public void onClick(View v) {
73 | if(mService!=null)
74 | mService.requestForCurrentLocation();
75 | else {
76 | mContext.bindService(new Intent(mContext, LocationService.class), new ServiceConnection() {
77 | @Override
78 | public void onServiceConnected(ComponentName name, IBinder service) {
79 | mService= ((LocationService.LocalBinder)service).getService() ;
80 | }
81 |
82 | @Override
83 | public void onServiceDisconnected(ComponentName name) {
84 | mService=null;
85 | }
86 | }, Context.BIND_AUTO_CREATE);
87 | }
88 | }
89 | });
90 | view.findViewById(R.id.toolbar).setVisibility(View.GONE);
91 | mOldLocation = (TextView) view.findViewById(R.id.oldlocation);
92 | mNewLocation = (TextView) view.findViewById(R.id.newlocation);
93 | AdView mAdView = (AdView) view.findViewById(R.id.adView);
94 | AdRequest adRequest = new AdRequest.Builder().build();
95 | mAdView.loadAd(adRequest);
96 | super.onViewCreated(view, savedInstanceState);
97 | }
98 |
99 | @Override
100 | public void onActivityResult(int requestCode, int resultCode, Intent data) {
101 | new Handler().postDelayed(new Runnable() {
102 | @Override
103 | public void run() {
104 | setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
105 | }
106 | }, 100);
107 | super.onActivityResult(requestCode, resultCode, data);
108 | }
109 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/googleplayservicelocationsupport/LocationService.java:
--------------------------------------------------------------------------------
1 | package com.googleplayservicelocationsupport;
2 |
3 | import android.content.Intent;
4 | import android.location.Location;
5 | import android.os.Binder;
6 | import android.os.IBinder;
7 | import android.support.annotation.Nullable;
8 | import android.widget.Toast;
9 |
10 | import com.github.akashandroid90.googlesupport.location.AppLocationService;
11 |
12 | import java.lang.ref.WeakReference;
13 |
14 | /**
15 | * Created by Akash Jain on 22-Jan-17.
16 | */
17 |
18 | public class LocationService extends AppLocationService {
19 | @Nullable
20 | @Override
21 | public IBinder onBind(Intent intent) {
22 | return new LocalBinder<>(this);
23 | }
24 |
25 | @Override
26 | public void myCurrentLocation(Location currentLocation) {
27 | super.myCurrentLocation(currentLocation);
28 | Toast.makeText(this,"lat:"+currentLocation.getLatitude()+" lng"+currentLocation.getLongitude(),Toast.LENGTH_SHORT).show();
29 | }
30 |
31 | @Override
32 | public void newLocation(Location location) {
33 | super.newLocation(location);
34 | Toast.makeText(this,"lat:"+location.getLatitude()+" lng"+location.getLongitude(),Toast.LENGTH_SHORT).show();
35 | }
36 |
37 | public class LocalBinder extends Binder {
38 | private final WeakReference mService;
39 |
40 | public LocalBinder(final S service) {
41 | mService = new WeakReference(service);
42 | }
43 |
44 | public S getService() {
45 | return mService.get();
46 | }
47 |
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/app/src/main/java/com/googleplayservicelocationsupport/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.googleplayservicelocationsupport;
2 |
3 | import android.content.DialogInterface;
4 | import android.content.Intent;
5 | import android.location.Location;
6 | import android.net.Uri;
7 | import android.os.Bundle;
8 | import android.support.v7.app.AlertDialog;
9 | import android.support.v7.widget.Toolbar;
10 | import android.view.Menu;
11 | import android.view.MenuInflater;
12 | import android.view.MenuItem;
13 | import android.view.View;
14 | import android.widget.TextView;
15 | import android.widget.Toast;
16 |
17 | import com.github.akashandroid90.googlesupport.location.AppLocationCompatActivity;
18 | import com.google.android.gms.ads.AdListener;
19 | import com.google.android.gms.ads.AdRequest;
20 | import com.google.android.gms.ads.AdView;
21 | import com.google.android.gms.ads.InterstitialAd;
22 | import com.google.android.gms.common.ConnectionResult;
23 |
24 |
25 | public class MainActivity extends AppLocationCompatActivity {
26 |
27 | private TextView mOldLocation, mNewLocation;
28 | private InterstitialAd mInterstitialAd;
29 |
30 | @Override
31 | protected void onCreate(Bundle savedInstanceState) {
32 | super.onCreate(savedInstanceState);
33 | setContentView(R.layout.activity_main);
34 | mOldLocation = (TextView) findViewById(R.id.oldlocation);
35 | mNewLocation = (TextView) findViewById(R.id.newlocation);
36 | AdView mAdView = (AdView) findViewById(R.id.adView);
37 |
38 | mInterstitialAd = new InterstitialAd(this);
39 | mInterstitialAd.setAdUnitId(getResources().getString(R.string.interstitial_ad));
40 | mInterstitialAd.setAdListener(new AdListener() {
41 | @Override
42 | public void onAdClosed() {
43 | startActivity(new Intent(MainActivity.this, FragmentLocationActivity.class));
44 | }
45 | });
46 | AdRequest adRequest = new AdRequest.Builder().build();
47 | mInterstitialAd.loadAd(adRequest);
48 |
49 | adRequest = new AdRequest.Builder().build();
50 | mAdView.loadAd(adRequest);
51 | findViewById(R.id.btn_fragment).setOnClickListener(new View.OnClickListener() {
52 | @Override
53 | public void onClick(View v) {
54 | if (mInterstitialAd != null && mInterstitialAd.isLoaded())
55 | mInterstitialAd.show();
56 | else startActivity(new Intent(MainActivity.this, FragmentLocationActivity.class));
57 | }
58 | });
59 | Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
60 | setSupportActionBar(toolbar);
61 | }
62 |
63 | @Override
64 | public void newLocation(Location location) {
65 | mNewLocation.setText(location.getLatitude() + "," + location.getLongitude());
66 | }
67 |
68 | @Override
69 | public void myCurrentLocation(Location currentLocation) {
70 | mOldLocation.setText(currentLocation.getLatitude() + "," + currentLocation.getLongitude());
71 | }
72 |
73 | @Override
74 | public void onActivityResultError(int resultCode, ServiceError serviceError, ConnectionResult connectionResult) {
75 | switch (serviceError) {
76 | case GOOGLE_PLAY_SERVICE_ERROR:
77 | break;
78 | case LOCATION_SETTING_ERROR:
79 | break;
80 | }
81 | }
82 |
83 | @Override
84 | public void onServiceDialogCancel(DialogInterface dialog, ConnectionResult connectionResult) {
85 | if (connectionResult != null) {
86 | if (getGoogleApiAvailability().isUserResolvableError(connectionResult.getErrorCode()))
87 | showServiceErrorDialog(connectionResult);
88 | else
89 | Toast.makeText(this, connectionResult.getErrorMessage(), Toast.LENGTH_SHORT).show();
90 | }
91 | }
92 |
93 | @Override
94 | public boolean onCreateOptionsMenu(Menu menu) {
95 | final MenuInflater inflater = getMenuInflater();
96 | inflater.inflate(R.menu.menu, menu);
97 | return super.onCreateOptionsMenu(menu);
98 | }
99 |
100 | @Override
101 | public boolean onOptionsItemSelected(MenuItem item) {
102 | Intent intent;
103 | switch (item.getItemId()) {
104 | case R.id.play_store:
105 | intent = new Intent(Intent.ACTION_VIEW);
106 | intent.setData(Uri.parse("market://details?id=com.googleplayservicelocationsupport"));
107 | startActivity(intent);
108 | return true;
109 | case R.id.other_apps:
110 | intent = new Intent(Intent.ACTION_VIEW);
111 | intent.setData(Uri.parse("market://search?q=pub:AkashJain"));
112 | startActivity(intent);
113 | return true;
114 | case R.id.github:
115 | intent = new Intent(Intent.ACTION_VIEW);
116 | intent.setData(Uri.parse("https://github.com/akashandroid90/GooglePlayServiceLocationSupport"));
117 | startActivity(intent);
118 | return true;
119 | case R.id.share:
120 | Intent sendIntent = new Intent();
121 | sendIntent.setAction(Intent.ACTION_SEND);
122 | sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Material Icon");
123 | sendIntent.putExtra(Intent.EXTRA_TEXT, "http://play.google.com/store/apps/details?id=com.googleplayservicelocationsupport");
124 | sendIntent.setType("text/plain");
125 | startActivity(sendIntent);
126 | return true;
127 | }
128 | return super.onOptionsItemSelected(item);
129 | }
130 |
131 | @Override
132 | public void onBackPressed() {
133 | new AlertDialog.Builder(this).setMessage("Are you sure want to exit from app?").setPositiveButton("Yes", new DialogInterface.OnClickListener() {
134 | @Override
135 | public void onClick(DialogInterface dialogInterface, int i) {
136 | dialogInterface.dismiss();
137 | finish();
138 | }
139 | }).setNegativeButton("No", new DialogInterface.OnClickListener() {
140 | @Override
141 | public void onClick(DialogInterface dialogInterface, int i) {
142 | dialogInterface.dismiss();
143 | }
144 | }).setNeutralButton("Rate us", new DialogInterface.OnClickListener() {
145 | @Override
146 | public void onClick(DialogInterface dialogInterface, int i) {
147 | dialogInterface.dismiss();
148 | Intent intent = new Intent(Intent.ACTION_VIEW);
149 | intent.setData(Uri.parse("market://details?id=com.googleplayservicelocationsupport"));
150 | startActivity(intent);
151 | }
152 | }).create().show();
153 | }
154 | }
155 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_fragment_location.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
16 |
22 |
23 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
15 |
22 |
25 |
30 |
31 |
40 |
41 |
42 |
45 |
46 |
52 |
53 |
62 |
63 |
64 |
72 |
78 |
83 |
89 |
90 |
91 |
--------------------------------------------------------------------------------
/app/src/main/res/menu/menu.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akashjaindev/GooglePlayServiceLocationSupport/23582afb84183d9fc16187f44b8cb866d81c0fc1/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akashjaindev/GooglePlayServiceLocationSupport/23582afb84183d9fc16187f44b8cb866d81c0fc1/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akashjaindev/GooglePlayServiceLocationSupport/23582afb84183d9fc16187f44b8cb866d81c0fc1/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akashjaindev/GooglePlayServiceLocationSupport/23582afb84183d9fc16187f44b8cb866d81c0fc1/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akashjaindev/GooglePlayServiceLocationSupport/23582afb84183d9fc16187f44b8cb866d81c0fc1/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Location Support
3 | App Crash
4 | ca-app-pub-5883105630361246/1515339811
5 | ca-app-pub-5883105630361246/9664373019
6 | Other Apps
7 | Github
8 | Rate us
9 | Share
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.2.3'
9 |
10 | // NOTE: Do not place your application dependencies here; they belong
11 | // in the individual module build.gradle files
12 | }
13 | }
14 |
15 | allprojects {
16 | repositories {
17 | jcenter()
18 | }
19 | }
20 |
21 | task clean(type: Delete) {
22 | delete rootProject.buildDir
23 | }
24 |
--------------------------------------------------------------------------------
/google-support-location/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/google-support-location/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 | android {
3 | compileSdkVersion compilesdk
4 | buildToolsVersion buildtool
5 | defaultConfig {
6 | minSdkVersion minsdk
7 | targetSdkVersion targetsdk
8 | versionCode 1
9 | versionName '1.0'
10 | }
11 | buildTypes {
12 | release {
13 | minifyEnabled false
14 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
15 | }
16 | }
17 | }
18 | dependencies {
19 | compile "com.android.support:appcompat-v7:$androidlib"
20 | compile "com.google.android.gms:play-services-location:$playservicelib"
21 | }
--------------------------------------------------------------------------------
/google-support-location/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in D:\ide\android\AndroidSDK/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 |
20 | #-optimizationpasses 5
21 | #-renamesourcefileattribute SourceFile
22 | #-optimizations !code/simplification/advanced,code/simplification/*
23 | #
24 | #
25 | #-keepclassmembers enum * { public static **[] values(); public static ** valueOf(java.lang.String); }
26 | #
27 | #-keep class com.github.akashandroid90.googlesupport.location.** { *; }
28 | #
29 | #-keep class com.google.android.gms.**
30 | #-keep class com.google.android.gms.location.**
31 | #-keep class com.google.api.services.*.model.*
32 | #-keep class com.google.api.client.**
33 | #
34 | #-keep public class * extends android.view.View {
35 | #void set*(***);
36 | # *** get*();
37 | # }
38 |
--------------------------------------------------------------------------------
/google-support-location/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
6 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/google-support-location/src/main/java/com/github/akashandroid90/googlesupport/location/AppLocation.java:
--------------------------------------------------------------------------------
1 | package com.github.akashandroid90.googlesupport.location;
2 |
3 | /**
4 | * Created by Akash Jain on 08-Dec-15.
5 | */
6 | public class AppLocation {
7 | public static final String REQUEST_UPDATES = "request_updates";
8 | }
9 |
--------------------------------------------------------------------------------
/google-support-location/src/main/java/com/github/akashandroid90/googlesupport/location/AppLocationActivity.java:
--------------------------------------------------------------------------------
1 | package com.github.akashandroid90.googlesupport.location;
2 |
3 |
4 | import android.Manifest;
5 | import android.content.Context;
6 | import android.content.DialogInterface;
7 | import android.content.Intent;
8 | import android.content.IntentSender;
9 | import android.content.pm.PackageManager;
10 | import android.location.Location;
11 | import android.location.LocationManager;
12 | import android.os.Bundle;
13 | import android.support.annotation.NonNull;
14 | import android.support.v4.app.ActivityCompat;
15 | import android.support.v4.app.FragmentActivity;
16 | import android.widget.Toast;
17 |
18 | import com.google.android.gms.common.ConnectionResult;
19 | import com.google.android.gms.common.GoogleApiAvailability;
20 | import com.google.android.gms.common.api.Api;
21 | import com.google.android.gms.common.api.GoogleApiClient;
22 | import com.google.android.gms.common.api.PendingResult;
23 | import com.google.android.gms.common.api.ResultCallback;
24 | import com.google.android.gms.common.api.Status;
25 | import com.google.android.gms.location.LocationRequest;
26 | import com.google.android.gms.location.LocationServices;
27 | import com.google.android.gms.location.LocationSettingsRequest;
28 | import com.google.android.gms.location.LocationSettingsResult;
29 | import com.google.android.gms.location.LocationSettingsStatusCodes;
30 |
31 | import java.util.Random;
32 |
33 | /**
34 | * Created by akash on 8/12/15.
35 | */
36 | public abstract class AppLocationActivity extends FragmentActivity
37 | implements GoogleContextSupportLocation {
38 | private final int ACCESS_FINE_LOCATION = 101;
39 | private final int ACCESS_COARSE_LOCATION = 102;
40 | private final int ACCESS_LOCATION = 103;
41 | private final int REQUEST_CHECK_SETTINGS = 104;
42 | private final int ACCESS_FUSED_LOCATION = 105;
43 |
44 | private final int REQUEST_CODE_PLAY_SERVICES = 106;
45 |
46 | private GoogleApiClient mGoogleApiClient;
47 | private LocationRequest mLocationRequest;
48 | private LocationManager mLocationService;
49 |
50 | private boolean enableUpdates;
51 | private GoogleApiAvailability mGoogleApiAvailability;
52 | private ConnectionResult mConnectionResult;
53 |
54 | /**
55 | * this method gives GoogleApiAvailability object created
56 | *
57 | * @return GoogleApiAvailability
58 | */
59 | @Override
60 | public GoogleApiAvailability getGoogleApiAvailability() {
61 | return mGoogleApiAvailability;
62 | }
63 |
64 | /**
65 | * this method gives GoogleApiClient object created
66 | *
67 | * @return GoogleApiClient
68 | */
69 | @Override
70 | public GoogleApiClient getGoogleApiClient() {
71 | return mGoogleApiClient;
72 | }
73 |
74 | /**
75 | * this method gives LocationRequest object created
76 | *
77 | * @return LocationRequest
78 | */
79 | @Override
80 | public LocationRequest getLocationRequest() {
81 | return mLocationRequest;
82 | }
83 |
84 | /**
85 | * this method gives LocationManager object created
86 | *
87 | * @return LocationManager
88 | */
89 | @Override
90 | public LocationManager getLocationService() {
91 | return mLocationService;
92 | }
93 |
94 | @Override
95 | public void onConnected(Bundle bundle) {
96 | mConnectionResult = null;
97 | checkLocationEnable();
98 | }
99 |
100 | @Override
101 | public void onConnectionSuspended(int i) {
102 | if (!mGoogleApiClient.isConnected())
103 | mGoogleApiClient.reconnect();
104 | }
105 |
106 | @Override
107 | public void newLocation(Location location) {
108 | }
109 |
110 | @Override
111 | public void myCurrentLocation(Location currentLocation) {
112 | }
113 |
114 | @Override
115 | public void onServiceDialogCancel(DialogInterface dialog, ConnectionResult connectionResult) {
116 | }
117 |
118 | @Override
119 | public void onConnectionFailed(ConnectionResult connectionResult) {
120 | mConnectionResult = connectionResult;
121 | if (mGoogleApiAvailability.isUserResolvableError(connectionResult.getErrorCode()))
122 | mGoogleApiAvailability.getErrorDialog(this, connectionResult.getErrorCode(), REQUEST_CODE_PLAY_SERVICES, this).show();
123 | else if (enableUpdates)
124 | Toast.makeText(this, connectionResult.getErrorMessage(), Toast.LENGTH_SHORT).show();
125 | if (!mGoogleApiClient.isConnected())
126 | mGoogleApiClient.reconnect();
127 | }
128 |
129 | @Override
130 | public void onLocationChanged(Location location) {
131 | newLocation(location);
132 | }
133 |
134 |
135 | protected final void checkLocationEnable() {
136 |
137 | if (enableUpdates && mGoogleApiClient != null && mGoogleApiClient.isConnected())
138 | LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
139 |
140 | LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
141 | .addLocationRequest(mLocationRequest).setAlwaysShow(true);
142 |
143 | PendingResult result =
144 | LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
145 |
146 | result.setResultCallback(new ResultCallback() {
147 | @Override
148 | public void onResult(LocationSettingsResult result) {
149 | final Status status = result.getStatus();
150 | // mLocationSettingsStates = result.getLocationSettingsStates();
151 | switch (status.getStatusCode()) {
152 | case LocationSettingsStatusCodes.SUCCESS:
153 | // All location settings are satisfied. The client can initialize location
154 | // requests here.
155 |
156 | requestLocationUpdates();
157 | break;
158 | case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
159 | // Location settings are not satisfied. But could be fixed by showing the user
160 | // a dialog.
161 | try {
162 | // Show the dialog by calling startResolutionForResult(),
163 | // and check the result in onActivityResult().
164 | status.startResolutionForResult(AppLocationActivity.this, REQUEST_CHECK_SETTINGS);
165 | } catch (IntentSender.SendIntentException e) {
166 | // Ignore the error.
167 | }
168 | break;
169 | case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
170 | // Location settings are not satisfied. However, we have no way to fix the
171 | // settings so we won't show the dialog.
172 |
173 | break;
174 | }
175 | }
176 | });
177 |
178 | }
179 |
180 | @Override
181 | public void onCancel(DialogInterface dialog) {
182 | onServiceDialogCancel(dialog, mConnectionResult);
183 | }
184 |
185 | @Override
186 | public void addApi(@NonNull Api extends Api.ApiOptions.NotRequiredOptions> value) {
187 | if (mGoogleApiClient != null)
188 | mGoogleApiClient.disconnect();
189 | GoogleApiClient.Builder builder = new GoogleApiClient.Builder(this).addApi(LocationServices.API).enableAutoManage(this, new Random().nextInt(Integer.MAX_VALUE), this).
190 | addConnectionCallbacks(this).addOnConnectionFailedListener(this);
191 | if (!value.getName().equalsIgnoreCase(LocationServices.API.getName())) {
192 | addApi(value);
193 | }
194 | mGoogleApiClient = builder.build();
195 | if (!servicesConnected())
196 | mGoogleApiClient.connect();
197 | }
198 |
199 | @Override
200 | public void addApi(@NonNull Api extends Api.ApiOptions.NotRequiredOptions>[] value) {
201 | if (mGoogleApiClient != null)
202 | mGoogleApiClient.disconnect();
203 | GoogleApiClient.Builder builder = new GoogleApiClient.Builder(this).addApi(LocationServices.API).enableAutoManage(this, new Random().nextInt(Integer.MAX_VALUE), this).
204 | addConnectionCallbacks(this).addOnConnectionFailedListener(this);
205 | for (Api extends Api.ApiOptions.NotRequiredOptions> options : value) {
206 | if (!options.getName().equalsIgnoreCase(LocationServices.API.getName())) {
207 | builder.addApi(options);
208 | }
209 | }
210 | mGoogleApiClient = builder.build();
211 | if (!servicesConnected())
212 | mGoogleApiClient.connect();
213 | }
214 |
215 | @Override
216 | public boolean servicesConnected() {
217 | // Check that Google Play services is available
218 | int resultCode = mGoogleApiAvailability.isGooglePlayServicesAvailable(this);
219 |
220 | // If Google Play services is available
221 | if (ConnectionResult.SUCCESS == resultCode) {
222 | if (mGoogleApiClient.isConnected())
223 | return true;
224 | else
225 | return false;
226 | }
227 | return false;
228 | }
229 |
230 | @Override
231 | protected void onCreate(Bundle savedInstanceState) {
232 | super.onCreate(savedInstanceState);
233 | mGoogleApiAvailability = GoogleApiAvailability.getInstance();
234 | mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API).enableAutoManage(this, new Random().nextInt(Integer.MAX_VALUE), this).
235 | addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
236 |
237 | mLocationService = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
238 |
239 | mLocationRequest = LocationRequest.create();
240 |
241 | Intent intent = getIntent();
242 | enableUpdates = intent.getBooleanExtra(AppLocation.REQUEST_UPDATES, true);
243 | }
244 |
245 | /**
246 | * @param fastInterval time to request update frequently
247 | */
248 | @Override
249 | public void setFastestInterval(long fastInterval) {
250 | mLocationRequest.setFastestInterval(fastInterval);
251 | checkLocationEnable();
252 | }
253 |
254 | /**
255 | * @param distance used to set displacement for request make
256 | */
257 | @Override
258 | public void setSmallestDisplacement(long distance) {
259 | mLocationRequest.setSmallestDisplacement(distance);
260 | checkLocationEnable();
261 | }
262 |
263 | /**
264 | * @param interval time in millis for location request
265 | */
266 | @Override
267 | public void setInterval(long interval) {
268 | mLocationRequest.setInterval(interval);
269 | checkLocationEnable();
270 | }
271 |
272 | /**
273 | * @param priority int value to set location request priority
274 | */
275 | @Override
276 | public void setPriority(int priority) {
277 | mLocationRequest.setPriority(priority);
278 | checkLocationEnable();
279 | }
280 |
281 | @Override
282 | protected void onStart() {
283 | // if (mLocationSettingsStates != null && mLocationSettingsStates.isLocationUsable()) {
284 | if (!servicesConnected())
285 | mGoogleApiClient.connect();
286 | // }
287 | super.onStart();
288 | }
289 |
290 | @Override
291 | protected void onStop() {
292 | if (mGoogleApiClient.isConnected())
293 | mGoogleApiClient.disconnect();
294 | super.onStop();
295 | }
296 |
297 | public void stopUpdates() {
298 | if (enableUpdates) {
299 | enableUpdates = false;
300 | LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
301 | }
302 | }
303 |
304 | @Override
305 | public void startUpdates() {
306 | if (!enableUpdates) {
307 | enableUpdates = true;
308 | requestLocationUpdates();
309 | }
310 | }
311 |
312 | private void requestLocationUpdates() {
313 | if (enableUpdates) {
314 | if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
315 | || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
316 | ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, ACCESS_FUSED_LOCATION);
317 | else {
318 | LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
319 | requestForCurrentLocation();
320 | }
321 | } else {
322 | if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
323 | || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
324 | ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, ACCESS_FUSED_LOCATION);
325 | else {
326 | requestForCurrentLocation();
327 | }
328 | }
329 | }
330 |
331 | @Override
332 | public Location requestForCurrentLocation() {
333 | // If Google Play Services is available
334 | Location currentLocation = null;
335 | if (servicesConnected()) {
336 | // Get the current location
337 | currentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
338 | }
339 | if (currentLocation == null) {
340 |
341 | if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
342 | && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
343 | ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, ACCESS_LOCATION);
344 | else {
345 | Location locationGPS = mLocationService.getLastKnownLocation(LocationManager.GPS_PROVIDER);
346 | Location locationNet = mLocationService.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
347 |
348 | long GPSLocationTime = 0;
349 | if (null != locationGPS) {
350 | GPSLocationTime = locationGPS.getTime();
351 | }
352 |
353 | long NetLocationTime = 0;
354 |
355 | if (null != locationNet) {
356 | NetLocationTime = locationNet.getTime();
357 | }
358 |
359 | if (0 < GPSLocationTime - NetLocationTime) {
360 | currentLocation = locationGPS;
361 | } else {
362 | currentLocation = locationNet;
363 | }
364 | }
365 |
366 | if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
367 | && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
368 | ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_FINE_LOCATION);
369 | else
370 | currentLocation = mLocationService.getLastKnownLocation(LocationManager.GPS_PROVIDER);
371 |
372 | if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
373 | && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
374 | ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, ACCESS_COARSE_LOCATION);
375 | else
376 | currentLocation = mLocationService.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
377 | }
378 | if (currentLocation != null)
379 | myCurrentLocation(currentLocation);
380 | return currentLocation;
381 | }
382 |
383 | @Override
384 | public void showServiceErrorDialog(ConnectionResult connectionResult) {
385 | mConnectionResult = connectionResult;
386 | if (mGoogleApiAvailability.isUserResolvableError(connectionResult.getErrorCode()))
387 | mGoogleApiAvailability.getErrorDialog(this, connectionResult.getErrorCode(), REQUEST_CODE_PLAY_SERVICES, this).show();
388 | }
389 |
390 | @Override
391 | public void showServiceErrorDialog(ConnectionResult connectionResult, int requestCode) {
392 | mConnectionResult = connectionResult;
393 | if (mGoogleApiAvailability.isUserResolvableError(connectionResult.getErrorCode()))
394 | mGoogleApiAvailability.getErrorDialog(this, connectionResult.getErrorCode(), requestCode, this).show();
395 | }
396 |
397 | @Override
398 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
399 | super.onRequestPermissionsResult(requestCode, permissions, grantResults);
400 | switch (requestCode) {
401 | case ACCESS_COARSE_LOCATION:
402 | if ((permissions.length > 0 && permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_COARSE_LOCATION)) && (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED))
403 | requestForCurrentLocation();
404 | else onRequestPermissionsResultError(requestCode, permissions, grantResults);
405 | break;
406 | case ACCESS_FINE_LOCATION:
407 | if ((permissions.length > 0 && permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION)) && (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED))
408 | requestForCurrentLocation();
409 | else onRequestPermissionsResultError(requestCode, permissions, grantResults);
410 | break;
411 | case ACCESS_LOCATION:
412 | if (permissions.length > 0 && ((permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION)
413 | || permissions[1].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION)) ||
414 | ((permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_COARSE_LOCATION)
415 | || permissions[1].equalsIgnoreCase(Manifest.permission.ACCESS_COARSE_LOCATION))))) {
416 | if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED &&
417 | grantResults[1] == PackageManager.PERMISSION_GRANTED)
418 | requestForCurrentLocation();
419 | else onRequestPermissionsResultError(requestCode, permissions, grantResults);
420 | }
421 | case ACCESS_FUSED_LOCATION:
422 | if (permissions.length > 0 && ((permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION)
423 | || permissions[1].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION)) ||
424 | ((permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_COARSE_LOCATION)
425 | || permissions[1].equalsIgnoreCase(Manifest.permission.ACCESS_COARSE_LOCATION))))) {
426 | if (grantResults.length > 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED ||
427 | grantResults[1] == PackageManager.PERMISSION_GRANTED) {
428 | LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
429 | requestForCurrentLocation();
430 | } else if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
431 | requestForCurrentLocation();
432 | LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
433 | } else onRequestPermissionsResultError(requestCode, permissions, grantResults);
434 | }
435 | break;
436 | }
437 | }
438 |
439 | @Override
440 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
441 | // final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
442 | switch (requestCode) {
443 | case REQUEST_CHECK_SETTINGS:
444 | switch (resultCode) {
445 | case RESULT_OK:
446 | // All required changes were successfully made
447 | if (!mGoogleApiClient.isConnected())
448 | mGoogleApiClient.connect();
449 | else {
450 | try {
451 | Thread.sleep(500);
452 | requestLocationUpdates();
453 | } catch (InterruptedException e) {
454 | e.printStackTrace();
455 | }
456 | }
457 |
458 | break;
459 | case RESULT_CANCELED:
460 | // The user was asked to change settings, but chose not to
461 | onActivityResultError(resultCode, ServiceError.LOCATION_SETTING_ERROR, null);
462 | break;
463 | default:
464 | onActivityResultError(resultCode, ServiceError.LOCATION_SETTING_ERROR, null);
465 | break;
466 | }
467 | break;
468 | case REQUEST_CODE_PLAY_SERVICES:
469 | switch (resultCode) {
470 | case RESULT_OK:
471 | // All required changes were successfully made
472 | if (!mGoogleApiClient.isConnected())
473 | mGoogleApiClient.connect();
474 | else
475 | requestLocationUpdates();
476 | break;
477 | default:
478 | if (mConnectionResult != null)
479 | onActivityResultError(resultCode, ServiceError.GOOGLE_PLAY_SERVICE_ERROR, mConnectionResult);
480 | }
481 | break;
482 | }
483 | super.onActivityResult(requestCode, resultCode, data);
484 | }
485 |
486 | @Override
487 | public void onActivityResultError(int resultCode, ServiceError serviceError, ConnectionResult connectionResult) {
488 | }
489 |
490 | @Override
491 | public void onRequestPermissionsResultError(int requestCode, String[] permissions, int[] grantResults) {
492 | }
493 | }
--------------------------------------------------------------------------------
/google-support-location/src/main/java/com/github/akashandroid90/googlesupport/location/AppLocationCompatActivity.java:
--------------------------------------------------------------------------------
1 | package com.github.akashandroid90.googlesupport.location;
2 |
3 |
4 | import android.Manifest;
5 | import android.content.Context;
6 | import android.content.DialogInterface;
7 | import android.content.Intent;
8 | import android.content.IntentSender;
9 | import android.content.pm.PackageManager;
10 | import android.location.Location;
11 | import android.location.LocationManager;
12 | import android.os.Bundle;
13 | import android.support.annotation.NonNull;
14 | import android.support.v4.app.ActivityCompat;
15 | import android.support.v7.app.AppCompatActivity;
16 | import android.widget.Toast;
17 |
18 | import com.google.android.gms.common.ConnectionResult;
19 | import com.google.android.gms.common.GoogleApiAvailability;
20 | import com.google.android.gms.common.api.Api;
21 | import com.google.android.gms.common.api.GoogleApiClient;
22 | import com.google.android.gms.common.api.PendingResult;
23 | import com.google.android.gms.common.api.ResultCallback;
24 | import com.google.android.gms.common.api.Status;
25 | import com.google.android.gms.location.LocationRequest;
26 | import com.google.android.gms.location.LocationServices;
27 | import com.google.android.gms.location.LocationSettingsRequest;
28 | import com.google.android.gms.location.LocationSettingsResult;
29 | import com.google.android.gms.location.LocationSettingsStatusCodes;
30 |
31 | import java.util.Random;
32 |
33 | /**
34 | * Created by akash on 8/12/15.
35 | */
36 | public abstract class AppLocationCompatActivity extends AppCompatActivity
37 | implements GoogleContextSupportLocation {
38 | private final int ACCESS_FINE_LOCATION = 101;
39 | private final int ACCESS_COARSE_LOCATION = 102;
40 | private final int ACCESS_LOCATION = 103;
41 | private final int REQUEST_CHECK_SETTINGS = 104;
42 | private final int ACCESS_FUSED_LOCATION = 105;
43 |
44 | private final int REQUEST_CODE_PLAY_SERVICES = 106;
45 |
46 | private GoogleApiClient mGoogleApiClient;
47 | private LocationRequest mLocationRequest;
48 | private LocationManager mLocationService;
49 |
50 | private boolean enableUpdates;
51 | private GoogleApiAvailability mGoogleApiAvailability;
52 | private ConnectionResult mConnectionResult;
53 |
54 | /**
55 | * this method gives GoogleApiAvailability object created
56 | *
57 | * @return GoogleApiAvailability
58 | */
59 | @Override
60 | public GoogleApiAvailability getGoogleApiAvailability() {
61 | return mGoogleApiAvailability;
62 | }
63 |
64 | /**
65 | * this method gives GoogleApiClient object created
66 | *
67 | * @return GoogleApiClient
68 | */
69 | @Override
70 | public GoogleApiClient getGoogleApiClient() {
71 | return mGoogleApiClient;
72 | }
73 |
74 | /**
75 | * this method gives LocationRequest object created
76 | *
77 | * @return LocationRequest
78 | */
79 | @Override
80 | public LocationRequest getLocationRequest() {
81 | return mLocationRequest;
82 | }
83 |
84 | /**
85 | * this method gives LocationManager object created
86 | *
87 | * @return LocationManager
88 | */
89 | @Override
90 | public LocationManager getLocationService() {
91 | return mLocationService;
92 | }
93 |
94 | @Override
95 | public void onConnected(Bundle bundle) {
96 | mConnectionResult = null;
97 | checkLocationEnable();
98 | }
99 |
100 | @Override
101 | public void onConnectionSuspended(int i) {
102 | if (!mGoogleApiClient.isConnected())
103 | mGoogleApiClient.reconnect();
104 | }
105 |
106 | @Override
107 | public void newLocation(Location location) {
108 | }
109 |
110 | @Override
111 | public void myCurrentLocation(Location currentLocation) {
112 | }
113 |
114 | @Override
115 | public void onServiceDialogCancel(DialogInterface dialog, ConnectionResult connectionResult) {
116 | }
117 |
118 | @Override
119 | public void onConnectionFailed(ConnectionResult connectionResult) {
120 | mConnectionResult = connectionResult;
121 | if (mGoogleApiAvailability.isUserResolvableError(connectionResult.getErrorCode()))
122 | mGoogleApiAvailability.getErrorDialog(this, connectionResult.getErrorCode(), REQUEST_CODE_PLAY_SERVICES, this).show();
123 | else if (enableUpdates)
124 | Toast.makeText(this, connectionResult.getErrorMessage(), Toast.LENGTH_SHORT).show();
125 | if (!mGoogleApiClient.isConnected())
126 | mGoogleApiClient.reconnect();
127 | }
128 |
129 | @Override
130 | public void onLocationChanged(Location location) {
131 | newLocation(location);
132 | }
133 |
134 |
135 | protected final void checkLocationEnable() {
136 |
137 | if (enableUpdates && mGoogleApiClient != null && mGoogleApiClient.isConnected())
138 | LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
139 |
140 | LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
141 | .addLocationRequest(mLocationRequest).setAlwaysShow(true);
142 |
143 | PendingResult result =
144 | LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
145 |
146 | result.setResultCallback(new ResultCallback() {
147 | @Override
148 | public void onResult(LocationSettingsResult result) {
149 | final Status status = result.getStatus();
150 | // mLocationSettingsStates = result.getLocationSettingsStates();
151 | switch (status.getStatusCode()) {
152 | case LocationSettingsStatusCodes.SUCCESS:
153 | // All location settings are satisfied. The client can initialize location
154 | // requests here.
155 |
156 | requestLocationUpdates();
157 | break;
158 | case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
159 | // Location settings are not satisfied. But could be fixed by showing the user
160 | // a dialog.
161 | try {
162 | // Show the dialog by calling startResolutionForResult(),
163 | // and check the result in onActivityResult().
164 | status.startResolutionForResult(AppLocationCompatActivity.this, REQUEST_CHECK_SETTINGS);
165 | } catch (IntentSender.SendIntentException e) {
166 | // Ignore the error.
167 | }
168 | break;
169 | case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
170 | // Location settings are not satisfied. However, we have no way to fix the
171 | // settings so we won't show the dialog.
172 |
173 | break;
174 | }
175 | }
176 | });
177 |
178 | }
179 |
180 | @Override
181 | public void onCancel(DialogInterface dialog) {
182 | onServiceDialogCancel(dialog, mConnectionResult);
183 | }
184 |
185 | @Override
186 | protected void onCreate(Bundle savedInstanceState) {
187 | super.onCreate(savedInstanceState);
188 | mGoogleApiAvailability = GoogleApiAvailability.getInstance();
189 | mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API).enableAutoManage(this, this).
190 | addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
191 |
192 | mLocationService = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
193 |
194 | mLocationRequest = LocationRequest.create();
195 |
196 | Intent intent = getIntent();
197 | enableUpdates = intent.getBooleanExtra(AppLocation.REQUEST_UPDATES, true);
198 | }
199 |
200 | @Override
201 | public void addApi(@NonNull Api extends Api.ApiOptions.NotRequiredOptions> value) {
202 | if (mGoogleApiClient != null)
203 | mGoogleApiClient.disconnect();
204 | GoogleApiClient.Builder builder = new GoogleApiClient.Builder(this).addApi(LocationServices.API).enableAutoManage(this, new Random().nextInt(Integer.MAX_VALUE), this).
205 | addConnectionCallbacks(this).addOnConnectionFailedListener(this);
206 | if (!value.getName().equalsIgnoreCase(LocationServices.API.getName())) {
207 | addApi(value);
208 | }
209 | mGoogleApiClient = builder.build();
210 | if (!servicesConnected())
211 | mGoogleApiClient.connect();
212 | }
213 |
214 | @Override
215 | public void addApi(@NonNull Api extends Api.ApiOptions.NotRequiredOptions>[] value) {
216 | if (mGoogleApiClient != null)
217 | mGoogleApiClient.disconnect();
218 | GoogleApiClient.Builder builder = new GoogleApiClient.Builder(this).addApi(LocationServices.API).enableAutoManage(this, new Random().nextInt(Integer.MAX_VALUE), this).
219 | addConnectionCallbacks(this).addOnConnectionFailedListener(this);
220 | for (Api extends Api.ApiOptions.NotRequiredOptions> options : value) {
221 | if (!options.getName().equalsIgnoreCase(LocationServices.API.getName())) {
222 | builder.addApi(options);
223 | }
224 | }
225 | mGoogleApiClient = builder.build();
226 | if (!servicesConnected())
227 | mGoogleApiClient.connect();
228 | }
229 |
230 | @Override
231 | public boolean servicesConnected() {
232 | // Check that Google Play services is available
233 | int resultCode = mGoogleApiAvailability.isGooglePlayServicesAvailable(this);
234 |
235 | // If Google Play services is available
236 | if (ConnectionResult.SUCCESS == resultCode) {
237 | if (mGoogleApiClient.isConnected())
238 | return true;
239 | else
240 | return false;
241 | }
242 | return false;
243 | }
244 |
245 |
246 | /**
247 | * @param fastInterval time to request update frequently
248 | */
249 | @Override
250 | public void setFastestInterval(long fastInterval) {
251 | mLocationRequest.setFastestInterval(fastInterval);
252 | checkLocationEnable();
253 | }
254 |
255 | /**
256 | * @param distance used to set displacement for request make
257 | */
258 | @Override
259 | public void setSmallestDisplacement(long distance) {
260 | mLocationRequest.setSmallestDisplacement(distance);
261 | checkLocationEnable();
262 | }
263 |
264 | /**
265 | * @param interval time in millis for location request
266 | */
267 | @Override
268 | public void setInterval(long interval) {
269 | mLocationRequest.setInterval(interval);
270 | checkLocationEnable();
271 | }
272 |
273 | /**
274 | * @param priority int value to set location request priority
275 | */
276 | @Override
277 | public void setPriority(int priority) {
278 | mLocationRequest.setPriority(priority);
279 | checkLocationEnable();
280 | }
281 |
282 | @Override
283 | protected void onStart() {
284 | // if (mLocationSettingsStates != null && mLocationSettingsStates.isLocationUsable()) {
285 | if (!servicesConnected())
286 | mGoogleApiClient.connect();
287 | // }
288 | super.onStart();
289 | }
290 |
291 | @Override
292 | protected void onStop() {
293 | if (mGoogleApiClient.isConnected())
294 | mGoogleApiClient.disconnect();
295 | super.onStop();
296 | }
297 |
298 | public void stopUpdates() {
299 | if (enableUpdates) {
300 | enableUpdates = false;
301 | LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
302 | }
303 | }
304 |
305 | @Override
306 | public void startUpdates() {
307 | if (!enableUpdates) {
308 | enableUpdates = true;
309 | requestLocationUpdates();
310 | }
311 | }
312 |
313 | private void requestLocationUpdates() {
314 | if (enableUpdates) {
315 | if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
316 | || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
317 | ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, ACCESS_FUSED_LOCATION);
318 | else {
319 | LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
320 | requestForCurrentLocation();
321 | }
322 | } else {
323 | if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
324 | || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
325 | ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, ACCESS_FUSED_LOCATION);
326 | else {
327 | requestForCurrentLocation();
328 | }
329 | }
330 | }
331 |
332 | @Override
333 | public Location requestForCurrentLocation() {
334 | // If Google Play Services is available
335 | Location currentLocation = null;
336 | if (servicesConnected()) {
337 | // Get the current location
338 |
339 | currentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
340 | }
341 | if (currentLocation == null) {
342 |
343 | if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
344 | && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
345 | ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, ACCESS_LOCATION);
346 |
347 | else {
348 | Location locationGPS = mLocationService.getLastKnownLocation(LocationManager.GPS_PROVIDER);
349 | Location locationNet = mLocationService.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
350 |
351 | long GPSLocationTime = 0;
352 | if (null != locationGPS) {
353 | GPSLocationTime = locationGPS.getTime();
354 | }
355 |
356 | long NetLocationTime = 0;
357 |
358 | if (null != locationNet) {
359 | NetLocationTime = locationNet.getTime();
360 | }
361 |
362 | if (0 < GPSLocationTime - NetLocationTime) {
363 | currentLocation = locationGPS;
364 | } else {
365 | currentLocation = locationNet;
366 | }
367 | }
368 |
369 | if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
370 | && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
371 | ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_FINE_LOCATION);
372 | else
373 | currentLocation = mLocationService.getLastKnownLocation(LocationManager.GPS_PROVIDER);
374 |
375 | if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
376 | && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
377 | ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, ACCESS_COARSE_LOCATION);
378 | else
379 | currentLocation = mLocationService.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
380 | }
381 | if (currentLocation != null)
382 | myCurrentLocation(currentLocation);
383 | return currentLocation;
384 | }
385 |
386 | @Override
387 | public void showServiceErrorDialog(ConnectionResult connectionResult) {
388 | mConnectionResult = connectionResult;
389 | if (mGoogleApiAvailability.isUserResolvableError(connectionResult.getErrorCode()))
390 | mGoogleApiAvailability.getErrorDialog(this, connectionResult.getErrorCode(), REQUEST_CODE_PLAY_SERVICES, this).show();
391 | }
392 |
393 | @Override
394 | public void showServiceErrorDialog(ConnectionResult connectionResult, int requestCode) {
395 | mConnectionResult = connectionResult;
396 | if (mGoogleApiAvailability.isUserResolvableError(connectionResult.getErrorCode()))
397 | mGoogleApiAvailability.getErrorDialog(this, connectionResult.getErrorCode(), requestCode, this).show();
398 | }
399 |
400 | @Override
401 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
402 | super.onRequestPermissionsResult(requestCode, permissions, grantResults);
403 | switch (requestCode) {
404 | case ACCESS_COARSE_LOCATION:
405 | if ((permissions.length > 0 && permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_COARSE_LOCATION)) && (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED))
406 | requestForCurrentLocation();
407 | else onRequestPermissionsResultError(requestCode, permissions, grantResults);
408 | break;
409 | case ACCESS_FINE_LOCATION:
410 | if ((permissions.length > 0 && permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION)) && (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED))
411 | requestForCurrentLocation();
412 | else onRequestPermissionsResultError(requestCode, permissions, grantResults);
413 | break;
414 | case ACCESS_LOCATION:
415 | if (permissions.length > 0 && ((permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION)
416 | || permissions[1].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION)) ||
417 | ((permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_COARSE_LOCATION)
418 | || permissions[1].equalsIgnoreCase(Manifest.permission.ACCESS_COARSE_LOCATION))))) {
419 | if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED &&
420 | grantResults[1] == PackageManager.PERMISSION_GRANTED)
421 | requestForCurrentLocation();
422 | else onRequestPermissionsResultError(requestCode, permissions, grantResults);
423 | }
424 | case ACCESS_FUSED_LOCATION:
425 | if (permissions.length > 0 && ((permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION)
426 | || permissions[1].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION)) ||
427 | ((permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_COARSE_LOCATION)
428 | || permissions[1].equalsIgnoreCase(Manifest.permission.ACCESS_COARSE_LOCATION))))) {
429 | if (grantResults.length > 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED ||
430 | grantResults[1] == PackageManager.PERMISSION_GRANTED) {
431 | LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
432 | requestForCurrentLocation();
433 | } else if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
434 | requestForCurrentLocation();
435 | LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
436 | } else onRequestPermissionsResultError(requestCode, permissions, grantResults);
437 | }
438 | break;
439 | }
440 | }
441 |
442 | @Override
443 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
444 | // final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
445 | switch (requestCode) {
446 | case REQUEST_CHECK_SETTINGS:
447 | switch (resultCode) {
448 | case RESULT_OK:
449 | // All required changes were successfully made
450 | if (!mGoogleApiClient.isConnected())
451 | mGoogleApiClient.connect();
452 | else {
453 | try {
454 | Thread.sleep(500);
455 | requestLocationUpdates();
456 | } catch (InterruptedException e) {
457 | e.printStackTrace();
458 | }
459 | }
460 | break;
461 | case RESULT_CANCELED:
462 | // The user was asked to change settings, but chose not to
463 | onActivityResultError(resultCode, ServiceError.LOCATION_SETTING_ERROR, null);
464 | break;
465 | default:
466 | onActivityResultError(resultCode, ServiceError.LOCATION_SETTING_ERROR, null);
467 | break;
468 | }
469 | break;
470 | case REQUEST_CODE_PLAY_SERVICES:
471 | switch (resultCode) {
472 | case RESULT_OK:
473 | // All required changes were successfully made
474 | if (!mGoogleApiClient.isConnected())
475 | mGoogleApiClient.connect();
476 | else
477 | requestLocationUpdates();
478 | break;
479 | default:
480 | if (mConnectionResult != null)
481 | onActivityResultError(resultCode, ServiceError.GOOGLE_PLAY_SERVICE_ERROR, mConnectionResult);
482 | break;
483 | }
484 | break;
485 | }
486 | super.onActivityResult(requestCode, resultCode, data);
487 | }
488 |
489 | @Override
490 | public void onActivityResultError(int resultCode, ServiceError serviceError, ConnectionResult connectionResult) {
491 | }
492 |
493 | @Override
494 | public void onRequestPermissionsResultError(int requestCode, String[] permissions, int[] grantResults) {
495 | }
496 | }
497 |
--------------------------------------------------------------------------------
/google-support-location/src/main/java/com/github/akashandroid90/googlesupport/location/AppLocationFragment.java:
--------------------------------------------------------------------------------
1 | package com.github.akashandroid90.googlesupport.location;
2 |
3 | import android.Manifest;
4 | import android.app.Activity;
5 | import android.app.Fragment;
6 | import android.content.Context;
7 | import android.content.DialogInterface;
8 | import android.content.Intent;
9 | import android.content.IntentSender;
10 | import android.content.pm.PackageManager;
11 | import android.location.Location;
12 | import android.location.LocationManager;
13 | import android.os.Bundle;
14 | import android.support.annotation.NonNull;
15 | import android.support.annotation.Nullable;
16 | import android.support.v4.app.ActivityCompat;
17 | import android.support.v4.app.FragmentActivity;
18 |
19 | import com.google.android.gms.common.ConnectionResult;
20 | import com.google.android.gms.common.GoogleApiAvailability;
21 | import com.google.android.gms.common.api.Api;
22 | import com.google.android.gms.common.api.GoogleApiClient;
23 | import com.google.android.gms.common.api.PendingResult;
24 | import com.google.android.gms.common.api.ResultCallback;
25 | import com.google.android.gms.common.api.Status;
26 | import com.google.android.gms.location.LocationRequest;
27 | import com.google.android.gms.location.LocationServices;
28 | import com.google.android.gms.location.LocationSettingsRequest;
29 | import com.google.android.gms.location.LocationSettingsResult;
30 | import com.google.android.gms.location.LocationSettingsStatusCodes;
31 |
32 | import java.util.Random;
33 |
34 | import static android.app.Activity.RESULT_CANCELED;
35 | import static android.app.Activity.RESULT_OK;
36 |
37 | /**
38 | * Created by akash on 8/12/15.
39 | */
40 | public abstract class AppLocationFragment extends Fragment
41 | implements GoogleContextSupportLocation {
42 |
43 | private final int ACCESS_FINE_LOCATION = 250;
44 | private final int ACCESS_COARSE_LOCATION = 251;
45 | private final int ACCESS_LOCATION = 252;
46 | private final int REQUEST_CHECK_SETTINGS = 253;
47 | private final int ACCESS_FUSED_LOCATION = 254;
48 | private final int REQUEST_CODE_PLAY_SERVICES = 255;
49 |
50 | protected Context mContext;
51 | private LocationManager mLocationService;
52 | private GoogleApiClient mGoogleApiClient;
53 | private LocationRequest mLocationRequest;
54 | private ConnectionResult mConnectionResult;
55 | private GoogleApiAvailability mGoogleApiAvailability;
56 |
57 | private boolean enableUpdates;
58 |
59 | /**
60 | * this method gives GoogleApiAvailability object created
61 | *
62 | * @return GoogleApiAvailability
63 | */
64 | @Override
65 | public GoogleApiAvailability getGoogleApiAvailability() {
66 | return mGoogleApiAvailability;
67 | }
68 |
69 | /**
70 | * this method gives GoogleApiClient object created
71 | *
72 | * @return GoogleApiClient
73 | */
74 | @Override
75 | public GoogleApiClient getGoogleApiClient() {
76 | return mGoogleApiClient;
77 | }
78 |
79 | /**
80 | * this method gives LocationRequest object created
81 | *
82 | * @return LocationRequest
83 | */
84 | @Override
85 | public LocationRequest getLocationRequest() {
86 | return mLocationRequest;
87 | }
88 |
89 | /**
90 | * this method gives LocationManager object created
91 | *
92 | * @return LocationManager
93 | */
94 |
95 | public LocationManager getLocationService() {
96 | return mLocationService;
97 | }
98 |
99 | @Override
100 | public void onAttach(Context context) {
101 | super.onAttach(context);
102 | mContext = context;
103 | }
104 |
105 | @Override
106 | public void onAttach(Activity activity) {
107 | super.onAttach(activity);
108 | mContext = activity;
109 | }
110 |
111 | @Override
112 | public void onConnected(Bundle bundle) {
113 | mConnectionResult = null;
114 | checkLocationEnable();
115 | }
116 |
117 | @Override
118 | public void myCurrentLocation(Location currentLocation) {
119 | }
120 |
121 | @Override
122 | public void onServiceDialogCancel(DialogInterface dialog, ConnectionResult connectionResult) {
123 | }
124 |
125 | @Override
126 | public void onConnectionSuspended(int i) {
127 | if (!mGoogleApiClient.isConnected())
128 | mGoogleApiClient.reconnect();
129 | }
130 |
131 | @Override
132 | public void onConnectionFailed(ConnectionResult connectionResult) {
133 | showServiceErrorDialog(connectionResult);
134 | }
135 |
136 | @Override
137 | public void onCancel(DialogInterface dialog) {
138 | onServiceDialogCancel(dialog, mConnectionResult);
139 | }
140 |
141 | @Override
142 | public void onLocationChanged(Location location) {
143 | newLocation(location);
144 | }
145 |
146 |
147 | protected final void checkLocationEnable() {
148 |
149 | if (enableUpdates && mGoogleApiClient != null && mGoogleApiClient.isConnected())
150 | LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
151 |
152 | LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
153 | .addLocationRequest(mLocationRequest).setAlwaysShow(true);
154 |
155 | PendingResult result =
156 | LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
157 |
158 | result.setResultCallback(new ResultCallback() {
159 | @Override
160 | public void onResult(LocationSettingsResult result) {
161 | final Status status = result.getStatus();
162 | // mLocationSettingsStates = result.getLocationSettingsStates();
163 | switch (status.getStatusCode()) {
164 | case LocationSettingsStatusCodes.SUCCESS:
165 | // All location settings are satisfied. The client can initialize location
166 | // requests here.
167 |
168 | requestLocationUpdates();
169 | break;
170 | case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
171 | // Location settings are not satisfied. But could be fixed by showing the user
172 | // a dialog.
173 | try {
174 | // Show the dialog by calling startResolutionForResult(),
175 | // and check the result in onActivityResult().
176 | status.startResolutionForResult((Activity) mContext, REQUEST_CHECK_SETTINGS);
177 | } catch (IntentSender.SendIntentException e) {
178 | // Ignore the error.
179 | }
180 | break;
181 | case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
182 | // Location settings are not satisfied. However, we have no way to fix the
183 | // settings so we won't show the dialog.
184 |
185 | break;
186 | }
187 | }
188 | });
189 |
190 | }
191 |
192 | @Override
193 | public void onCreate(@Nullable Bundle savedInstanceState) {
194 | super.onCreate(savedInstanceState);
195 | mGoogleApiAvailability = GoogleApiAvailability.getInstance();
196 | mGoogleApiClient = new GoogleApiClient.Builder(mContext).addApi(LocationServices.API).
197 | addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
198 |
199 | mLocationService = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
200 |
201 | mLocationRequest = LocationRequest.create();
202 |
203 | Bundle bundle = getArguments();
204 | if (bundle != null)
205 | enableUpdates = bundle.getBoolean(AppLocation.REQUEST_UPDATES, true);
206 | else
207 | enableUpdates = true;
208 |
209 | }
210 |
211 | /**
212 | * @param fastInterval time to request update frequently
213 | */
214 | @Override
215 | public void setFastestInterval(long fastInterval) {
216 | mLocationRequest.setFastestInterval(fastInterval);
217 | checkLocationEnable();
218 | }
219 |
220 | /**
221 | * @param distance used to set displacement for request make
222 | */
223 | @Override
224 | public void setSmallestDisplacement(long distance) {
225 | mLocationRequest.setSmallestDisplacement(distance);
226 | checkLocationEnable();
227 | }
228 |
229 | /**
230 | * @param interval time in millis for location request
231 | */
232 | @Override
233 | public void setInterval(long interval) {
234 | mLocationRequest.setInterval(interval);
235 | checkLocationEnable();
236 | }
237 |
238 | /**
239 | * @param priority int value to set location request priority
240 | */
241 | @Override
242 | public void setPriority(int priority) {
243 | mLocationRequest.setPriority(priority);
244 | checkLocationEnable();
245 | }
246 |
247 |
248 | @Override
249 | public void onStart() {
250 | // if (mLocationSettingsStates != null && mLocationSettingsStates.isLocationUsable()) {
251 | if (!servicesConnected())
252 | mGoogleApiClient.connect();
253 | // }
254 | super.onStart();
255 | }
256 |
257 | @Override
258 | public void onStop() {
259 | if (mGoogleApiClient.isConnected())
260 | mGoogleApiClient.disconnect();
261 | super.onStop();
262 | }
263 |
264 | @Override
265 | public void stopUpdates() {
266 | if (enableUpdates) {
267 | enableUpdates = false;
268 | LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
269 | }
270 | }
271 |
272 | @Override
273 | public void startUpdates() {
274 | if (!enableUpdates) {
275 | enableUpdates = true;
276 | requestLocationUpdates();
277 | }
278 | }
279 |
280 | private void requestLocationUpdates() {
281 | if (enableUpdates) {
282 | if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
283 | || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
284 | ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, ACCESS_FUSED_LOCATION);
285 | else {
286 | LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
287 | requestForCurrentLocation();
288 | }
289 | } else {
290 | if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
291 | || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
292 | ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, ACCESS_FUSED_LOCATION);
293 | else {
294 | requestForCurrentLocation();
295 | }
296 | }
297 | }
298 |
299 | @Override
300 | public void addApi(@NonNull Api extends Api.ApiOptions.NotRequiredOptions> value) {
301 | if (mGoogleApiClient != null)
302 | mGoogleApiClient.disconnect();
303 | GoogleApiClient.Builder builder = new GoogleApiClient.Builder(mContext).addApi(LocationServices.API).enableAutoManage((FragmentActivity) mContext, new Random().nextInt(Integer.MAX_VALUE), this).
304 | addConnectionCallbacks(this).addOnConnectionFailedListener(this);
305 | if (!value.getName().equalsIgnoreCase(LocationServices.API.getName())) {
306 | addApi(value);
307 | }
308 | mGoogleApiClient = builder.build();
309 | if (!servicesConnected())
310 | mGoogleApiClient.connect();
311 | }
312 |
313 | @Override
314 | public void addApi(@NonNull Api extends Api.ApiOptions.NotRequiredOptions>[] value) {
315 | if (mGoogleApiClient != null)
316 | mGoogleApiClient.disconnect();
317 | GoogleApiClient.Builder builder = new GoogleApiClient.Builder(mContext).addApi(LocationServices.API).enableAutoManage((FragmentActivity) mContext, new Random().nextInt(Integer.MAX_VALUE), this).
318 | addConnectionCallbacks(this).addOnConnectionFailedListener(this);
319 | for (Api extends Api.ApiOptions.NotRequiredOptions> options : value) {
320 | if (!options.getName().equalsIgnoreCase(LocationServices.API.getName())) {
321 | builder.addApi(options);
322 | }
323 | }
324 | mGoogleApiClient = builder.build();
325 | if (!servicesConnected())
326 | mGoogleApiClient.connect();
327 | }
328 |
329 | @Override
330 | public boolean servicesConnected() {
331 | // Check that Google Play services is available
332 | int resultCode = mGoogleApiAvailability.isGooglePlayServicesAvailable(mContext);
333 |
334 | // If Google Play services is available
335 | if (ConnectionResult.SUCCESS == resultCode) {
336 | if (mGoogleApiClient.isConnected())
337 | return true;
338 | else
339 | return false;
340 | }
341 | return false;
342 | }
343 |
344 | @Override
345 | public void newLocation(Location location) {
346 | }
347 |
348 | @Override
349 | public Location requestForCurrentLocation() {
350 | // If Google Play Services is available
351 | Location currentLocation = null;
352 | if (servicesConnected()) {
353 | // Get the current location
354 |
355 | currentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
356 | }
357 | if (currentLocation == null) {
358 |
359 | if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
360 | && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
361 | ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, ACCESS_LOCATION);
362 |
363 | else {
364 | Location locationGPS = mLocationService.getLastKnownLocation(LocationManager.GPS_PROVIDER);
365 | Location locationNet = mLocationService.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
366 |
367 | long GPSLocationTime = 0;
368 | if (null != locationGPS) {
369 | GPSLocationTime = locationGPS.getTime();
370 | }
371 |
372 | long NetLocationTime = 0;
373 |
374 | if (null != locationNet) {
375 | NetLocationTime = locationNet.getTime();
376 | }
377 |
378 | if (0 < GPSLocationTime - NetLocationTime) {
379 | currentLocation = locationGPS;
380 | } else {
381 | currentLocation = locationNet;
382 | }
383 | }
384 |
385 | if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
386 | && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
387 | ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_FINE_LOCATION);
388 | else
389 | currentLocation = mLocationService.getLastKnownLocation(LocationManager.GPS_PROVIDER);
390 |
391 | if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
392 | && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
393 | ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, ACCESS_COARSE_LOCATION);
394 | else
395 | currentLocation = mLocationService.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
396 | }
397 | if (currentLocation != null)
398 | myCurrentLocation(currentLocation);
399 | return currentLocation;
400 | }
401 |
402 | @Override
403 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
404 | super.onRequestPermissionsResult(requestCode, permissions, grantResults);
405 | switch (requestCode) {
406 | case ACCESS_COARSE_LOCATION:
407 | if ((permissions.length > 0 && permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_COARSE_LOCATION)) && (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED))
408 | requestForCurrentLocation();
409 | else onRequestPermissionsResultError(requestCode, permissions, grantResults);
410 | break;
411 | case ACCESS_FINE_LOCATION:
412 | if ((permissions.length > 0 && permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION)) && (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED))
413 | requestForCurrentLocation();
414 | else onRequestPermissionsResultError(requestCode, permissions, grantResults);
415 | break;
416 | case ACCESS_LOCATION:
417 | if (permissions.length > 0 && ((permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION)
418 | || permissions[1].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION)) ||
419 | ((permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_COARSE_LOCATION)
420 | || permissions[1].equalsIgnoreCase(Manifest.permission.ACCESS_COARSE_LOCATION))))) {
421 | if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED &&
422 | grantResults[1] == PackageManager.PERMISSION_GRANTED)
423 | requestForCurrentLocation();
424 | else onRequestPermissionsResultError(requestCode, permissions, grantResults);
425 | }
426 | case ACCESS_FUSED_LOCATION:
427 | if (permissions.length > 0 && ((permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION)
428 | || permissions[1].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION)) ||
429 | ((permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_COARSE_LOCATION)
430 | || permissions[1].equalsIgnoreCase(Manifest.permission.ACCESS_COARSE_LOCATION))))) {
431 | if (grantResults.length > 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED ||
432 | grantResults[1] == PackageManager.PERMISSION_GRANTED) {
433 | LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
434 | requestForCurrentLocation();
435 | } else if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
436 | requestForCurrentLocation();
437 | LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
438 | } else onRequestPermissionsResultError(requestCode, permissions, grantResults);
439 | }
440 | break;
441 | }
442 | }
443 |
444 | @Override
445 | public void showServiceErrorDialog(ConnectionResult connectionResult) {
446 | mConnectionResult = connectionResult;
447 | if (mGoogleApiAvailability.isUserResolvableError(connectionResult.getErrorCode()))
448 | mGoogleApiAvailability.getErrorDialog((Activity) mContext, connectionResult.getErrorCode(), REQUEST_CODE_PLAY_SERVICES, this).show();
449 | }
450 |
451 | @Override
452 | public void showServiceErrorDialog(ConnectionResult connectionResult, int requestCode) {
453 | mConnectionResult = connectionResult;
454 | if (mGoogleApiAvailability.isUserResolvableError(connectionResult.getErrorCode()))
455 | mGoogleApiAvailability.getErrorDialog((Activity) mContext, connectionResult.getErrorCode(), requestCode, this).show();
456 | }
457 |
458 | @Override
459 | public void onActivityResult(int requestCode, int resultCode, Intent data) {
460 | // final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
461 | switch (requestCode) {
462 | case REQUEST_CHECK_SETTINGS:
463 | switch (resultCode) {
464 | case RESULT_OK:
465 | // All required changes were successfully made
466 | if (!mGoogleApiClient.isConnected())
467 | mGoogleApiClient.connect();
468 | else {
469 | try {
470 | Thread.sleep(500);
471 | requestLocationUpdates();
472 | } catch (InterruptedException e) {
473 | e.printStackTrace();
474 | }
475 | }
476 | break;
477 | case RESULT_CANCELED:
478 | // The user was asked to change settings, but chose not to
479 | onActivityResultError(resultCode, ServiceError.LOCATION_SETTING_ERROR, null);
480 | break;
481 | default:
482 | onActivityResultError(resultCode, ServiceError.LOCATION_SETTING_ERROR, null);
483 | break;
484 | }
485 | break;
486 | case REQUEST_CODE_PLAY_SERVICES:
487 | switch (resultCode) {
488 | case RESULT_OK:
489 | // All required changes were successfully made
490 | if (!mGoogleApiClient.isConnected())
491 | mGoogleApiClient.connect();
492 | else
493 | requestLocationUpdates();
494 | break;
495 | default:
496 | if (mConnectionResult != null)
497 | onActivityResultError(resultCode, ServiceError.GOOGLE_PLAY_SERVICE_ERROR, mConnectionResult);
498 | break;
499 | }
500 | break;
501 | }
502 | super.onActivityResult(requestCode, resultCode, data);
503 | }
504 |
505 | @Override
506 | public void onActivityResultError(int resultCode, ServiceError serviceError, ConnectionResult connectionResult) {
507 | }
508 |
509 | @Override
510 | public void onRequestPermissionsResultError(int requestCode, String[] permissions, int[] grantResults) {
511 | }
512 | }
--------------------------------------------------------------------------------
/google-support-location/src/main/java/com/github/akashandroid90/googlesupport/location/AppLocationIntentService.java:
--------------------------------------------------------------------------------
1 | package com.github.akashandroid90.googlesupport.location;
2 |
3 | import android.Manifest;
4 | import android.app.IntentService;
5 | import android.app.Service;
6 | import android.content.Context;
7 | import android.content.pm.PackageManager;
8 | import android.location.Location;
9 | import android.location.LocationManager;
10 | import android.os.Bundle;
11 | import android.support.annotation.NonNull;
12 | import android.support.v4.app.ActivityCompat;
13 |
14 | import com.google.android.gms.common.ConnectionResult;
15 | import com.google.android.gms.common.GoogleApiAvailability;
16 | import com.google.android.gms.common.api.Api;
17 | import com.google.android.gms.common.api.GoogleApiClient;
18 | import com.google.android.gms.location.LocationRequest;
19 | import com.google.android.gms.location.LocationServices;
20 |
21 | /**
22 | * Created by Akash Jain on 23-Nov-16.
23 | */
24 |
25 | public abstract class AppLocationIntentService extends IntentService implements GoogleSupportLocation {
26 | private GoogleApiClient mGoogleApiClient;
27 | private LocationRequest mLocationRequest;
28 | private LocationManager mLocationService;
29 |
30 | private boolean enableUpdates;
31 | private GoogleApiAvailability mGoogleApiAvailability;
32 |
33 | public AppLocationIntentService(String name) {
34 | super(name);
35 | }
36 |
37 | @Override
38 | public void onCreate() {
39 | super.onCreate();
40 | mGoogleApiAvailability = GoogleApiAvailability.getInstance();
41 | mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API).
42 | addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
43 | mLocationService = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
44 | mLocationRequest = LocationRequest.create();
45 | enableUpdates = true;
46 | if (!servicesConnected()) {
47 | if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting())
48 | mGoogleApiClient.connect();
49 | }
50 | }
51 |
52 | /**
53 | * this method gives GoogleApiAvailability object created
54 | *
55 | * @return GoogleApiAvailability
56 | */
57 | @Override
58 | public GoogleApiAvailability getGoogleApiAvailability() {
59 | return mGoogleApiAvailability;
60 | }
61 |
62 | @Override
63 | public void onConnected(Bundle bundle) {
64 | requestForCurrentLocation();
65 | }
66 |
67 | @Override
68 | public void onConnectionSuspended(int i) {
69 | if (!mGoogleApiClient.isConnected())
70 | mGoogleApiClient.reconnect();
71 | }
72 |
73 | @Override
74 | public void onConnectionFailed(ConnectionResult connectionResult) {
75 | if (!mGoogleApiClient.isConnected())
76 | mGoogleApiClient.reconnect();
77 | }
78 |
79 | /**
80 | * this method gives GoogleApiClient object created
81 | *
82 | * @return GoogleApiClient
83 | */
84 | @Override
85 | public GoogleApiClient getGoogleApiClient() {
86 | return mGoogleApiClient;
87 | }
88 |
89 | /**
90 | * this method gives LocationRequest object created
91 | *
92 | * @return LocationRequest
93 | */
94 | @Override
95 | public LocationRequest getLocationRequest() {
96 | return mLocationRequest;
97 | }
98 |
99 | /**
100 | * this method gives LocationManager object created
101 | *
102 | * @return LocationManager
103 | */
104 | @Override
105 | public LocationManager getLocationService() {
106 | return mLocationService;
107 | }
108 |
109 | @Override
110 | public void onLocationChanged(Location location) {
111 | newLocation(location);
112 | }
113 |
114 | /**
115 | * @param fastInterval time to request update frequently
116 | */
117 | @Override
118 | public void setFastestInterval(long fastInterval) {
119 | mLocationRequest.setFastestInterval(fastInterval);
120 | }
121 |
122 | /**
123 | * @param distance used to set displacement for request make
124 | */
125 | @Override
126 | public void setSmallestDisplacement(long distance) {
127 | mLocationRequest.setSmallestDisplacement(distance);
128 | }
129 |
130 | /**
131 | * @param interval time in millis for location request
132 | */
133 | @Override
134 | public void setInterval(long interval) {
135 | mLocationRequest.setInterval(interval);
136 | }
137 |
138 | /**
139 | * @param priority int value to set location request priority
140 | */
141 | @Override
142 | public void setPriority(int priority) {
143 | mLocationRequest.setPriority(priority);
144 | }
145 |
146 | @Override
147 | public boolean servicesConnected() {
148 | // Check that Google Play services is available
149 | int resultCode = mGoogleApiAvailability.isGooglePlayServicesAvailable(this);
150 |
151 | // If Google Play services is available
152 | if (ConnectionResult.SUCCESS == resultCode) {
153 | if (mGoogleApiClient.isConnected())
154 | return true;
155 | else
156 | return false;
157 | }
158 | return false;
159 | }
160 |
161 | @Override
162 | public void newLocation(Location location) {
163 |
164 | }
165 |
166 | @Override
167 | public void myCurrentLocation(Location currentLocation) {
168 |
169 | }
170 |
171 | @Override
172 | public Location requestForCurrentLocation() {
173 | // If Google Play Services is available
174 | Location currentLocation = null;
175 | if (servicesConnected()) {
176 | // Get the current location
177 | currentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
178 | }
179 | if (currentLocation == null) {
180 |
181 | if (!(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
182 | && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
183 | Location locationGPS = mLocationService.getLastKnownLocation(LocationManager.GPS_PROVIDER);
184 | Location locationNet = mLocationService.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
185 |
186 | long GPSLocationTime = 0;
187 | if (null != locationGPS) {
188 | GPSLocationTime = locationGPS.getTime();
189 | }
190 |
191 | long NetLocationTime = 0;
192 |
193 | if (null != locationNet) {
194 | NetLocationTime = locationNet.getTime();
195 | }
196 |
197 | if (0 < GPSLocationTime - NetLocationTime) {
198 | currentLocation = locationGPS;
199 | } else {
200 | currentLocation = locationNet;
201 | }
202 | }else if (!(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
203 | && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED))
204 | currentLocation = mLocationService.getLastKnownLocation(LocationManager.GPS_PROVIDER);
205 | else if (!(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
206 | && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED))
207 | currentLocation = mLocationService.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
208 | }
209 | if (currentLocation != null)
210 | myCurrentLocation(currentLocation);
211 | return currentLocation;
212 | }
213 |
214 | public void stopUpdates() {
215 | if (enableUpdates) {
216 | enableUpdates = false;
217 | LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
218 | }
219 | }
220 |
221 | private void requestLocationUpdates() {
222 | if (enableUpdates) {
223 | if (!(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
224 | || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
225 | LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
226 | requestForCurrentLocation();
227 | }
228 | } else {
229 | if (!(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
230 | || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
231 | requestForCurrentLocation();
232 | }
233 | }
234 | }
235 |
236 | @Override
237 | public void startUpdates() {
238 | if (!enableUpdates) {
239 | enableUpdates = true;
240 | requestLocationUpdates();
241 | }
242 | }
243 |
244 | @Override
245 | public void addApi(@NonNull Api extends Api.ApiOptions.NotRequiredOptions>[] value) {
246 | if (mGoogleApiClient != null)
247 | mGoogleApiClient.disconnect();
248 | GoogleApiClient.Builder builder = new GoogleApiClient.Builder(this).addApi(LocationServices.API).
249 | addConnectionCallbacks(this).addOnConnectionFailedListener(this);
250 | for (Api extends Api.ApiOptions.NotRequiredOptions> options : value) {
251 | if (!options.getName().equalsIgnoreCase(LocationServices.API.getName())) {
252 | builder.addApi(options);
253 | }
254 | }
255 | mGoogleApiClient = builder.build();
256 | if (!servicesConnected())
257 | mGoogleApiClient.connect();
258 | }
259 |
260 | @Override
261 | public void addApi(@NonNull Api extends Api.ApiOptions.NotRequiredOptions> value) {
262 | if (mGoogleApiClient != null)
263 | mGoogleApiClient.disconnect();
264 | GoogleApiClient.Builder builder = new GoogleApiClient.Builder(this).addApi(LocationServices.API).
265 | addConnectionCallbacks(this).addOnConnectionFailedListener(this);
266 | if (!value.getName().equalsIgnoreCase(LocationServices.API.getName())) {
267 | addApi(value);
268 | }
269 | mGoogleApiClient = builder.build();
270 | if (!servicesConnected())
271 | mGoogleApiClient.connect();
272 | }
273 |
274 | @Override
275 | public void onDestroy() {
276 | if (mGoogleApiClient.isConnected())
277 | mGoogleApiClient.disconnect();
278 | super.onDestroy();
279 | }
280 | }
--------------------------------------------------------------------------------
/google-support-location/src/main/java/com/github/akashandroid90/googlesupport/location/AppLocationService.java:
--------------------------------------------------------------------------------
1 | package com.github.akashandroid90.googlesupport.location;
2 |
3 | import android.Manifest;
4 | import android.app.Service;
5 | import android.content.Context;
6 | import android.content.Intent;
7 | import android.content.pm.PackageManager;
8 | import android.location.Location;
9 | import android.location.LocationManager;
10 | import android.os.Bundle;
11 | import android.support.annotation.NonNull;
12 | import android.support.v4.app.ActivityCompat;
13 |
14 | import com.google.android.gms.common.ConnectionResult;
15 | import com.google.android.gms.common.GoogleApiAvailability;
16 | import com.google.android.gms.common.api.Api;
17 | import com.google.android.gms.common.api.GoogleApiClient;
18 | import com.google.android.gms.location.LocationRequest;
19 | import com.google.android.gms.location.LocationServices;
20 |
21 | /**
22 | * Created by Akash Jain on 23-Nov-16.
23 | */
24 |
25 | public abstract class AppLocationService extends Service implements GoogleSupportLocation {
26 | private GoogleApiClient mGoogleApiClient;
27 | private LocationRequest mLocationRequest;
28 | private LocationManager mLocationService;
29 |
30 | private boolean enableUpdates;
31 | private GoogleApiAvailability mGoogleApiAvailability;
32 |
33 | @Override
34 | public void onCreate() {
35 | super.onCreate();
36 | mGoogleApiAvailability = GoogleApiAvailability.getInstance();
37 | mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API).
38 | addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
39 | mLocationService = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
40 | mLocationRequest = LocationRequest.create();
41 | enableUpdates = true;
42 | if (!servicesConnected()) {
43 | if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting())
44 | mGoogleApiClient.connect();
45 | }
46 | }
47 |
48 | /**
49 | * this method gives GoogleApiAvailability object created
50 | *
51 | * @return GoogleApiAvailability
52 | */
53 | @Override
54 | public GoogleApiAvailability getGoogleApiAvailability() {
55 | return mGoogleApiAvailability;
56 | }
57 |
58 | @Override
59 | public void onConnected(Bundle bundle) {
60 | requestForCurrentLocation();
61 | }
62 |
63 | @Override
64 | public void onConnectionSuspended(int i) {
65 | if (!mGoogleApiClient.isConnected())
66 | mGoogleApiClient.reconnect();
67 | }
68 |
69 | @Override
70 | public void onConnectionFailed(ConnectionResult connectionResult) {
71 | if (!mGoogleApiClient.isConnected())
72 | mGoogleApiClient.reconnect();
73 | }
74 |
75 | /**
76 | * this method gives GoogleApiClient object created
77 | *
78 | * @return GoogleApiClient
79 | */
80 | @Override
81 | public GoogleApiClient getGoogleApiClient() {
82 | return mGoogleApiClient;
83 | }
84 |
85 | /**
86 | * this method gives LocationRequest object created
87 | *
88 | * @return LocationRequest
89 | */
90 | @Override
91 | public LocationRequest getLocationRequest() {
92 | return mLocationRequest;
93 | }
94 |
95 | /**
96 | * this method gives LocationManager object created
97 | *
98 | * @return LocationManager
99 | */
100 | @Override
101 | public LocationManager getLocationService() {
102 | return mLocationService;
103 | }
104 |
105 | @Override
106 | public void onLocationChanged(Location location) {
107 | newLocation(location);
108 | }
109 |
110 | /**
111 | * @param fastInterval time to request update frequently
112 | */
113 | @Override
114 | public void setFastestInterval(long fastInterval) {
115 | mLocationRequest.setFastestInterval(fastInterval);
116 | }
117 |
118 | /**
119 | * @param distance used to set displacement for request make
120 | */
121 | @Override
122 | public void setSmallestDisplacement(long distance) {
123 | mLocationRequest.setSmallestDisplacement(distance);
124 | }
125 |
126 | /**
127 | * @param interval time in millis for location request
128 | */
129 | @Override
130 | public void setInterval(long interval) {
131 | mLocationRequest.setInterval(interval);
132 | }
133 |
134 | /**
135 | * @param priority int value to set location request priority
136 | */
137 | @Override
138 | public void setPriority(int priority) {
139 | mLocationRequest.setPriority(priority);
140 | }
141 |
142 | @Override
143 | public boolean servicesConnected() {
144 | // Check that Google Play services is available
145 | int resultCode = mGoogleApiAvailability.isGooglePlayServicesAvailable(this);
146 |
147 | // If Google Play services is available
148 | if (ConnectionResult.SUCCESS == resultCode) {
149 | if (mGoogleApiClient.isConnected())
150 | return true;
151 | else
152 | return false;
153 | }
154 | return false;
155 | }
156 |
157 | @Override
158 | public void newLocation(Location location) {
159 |
160 | }
161 |
162 | @Override
163 | public void myCurrentLocation(Location currentLocation) {
164 |
165 | }
166 |
167 | @Override
168 | public Location requestForCurrentLocation() {
169 | // If Google Play Services is available
170 | Location currentLocation = null;
171 | if (servicesConnected()) {
172 | // Get the current location
173 | currentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
174 | }
175 | if (currentLocation == null) {
176 |
177 | if (!(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
178 | && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
179 | Location locationGPS = mLocationService.getLastKnownLocation(LocationManager.GPS_PROVIDER);
180 | Location locationNet = mLocationService.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
181 |
182 | long GPSLocationTime = 0;
183 | if (null != locationGPS) {
184 | GPSLocationTime = locationGPS.getTime();
185 | }
186 |
187 | long NetLocationTime = 0;
188 |
189 | if (null != locationNet) {
190 | NetLocationTime = locationNet.getTime();
191 | }
192 |
193 | if (0 < GPSLocationTime - NetLocationTime) {
194 | currentLocation = locationGPS;
195 | } else {
196 | currentLocation = locationNet;
197 | }
198 | }else if (!(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
199 | && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED))
200 | currentLocation = mLocationService.getLastKnownLocation(LocationManager.GPS_PROVIDER);
201 | else if (!(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
202 | && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED))
203 | currentLocation = mLocationService.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
204 | }
205 | if (currentLocation != null)
206 | myCurrentLocation(currentLocation);
207 | return currentLocation;
208 | }
209 |
210 | public void stopUpdates() {
211 | if (enableUpdates) {
212 | enableUpdates = false;
213 | LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
214 | }
215 | }
216 |
217 | private void requestLocationUpdates() {
218 | if (enableUpdates) {
219 | if (!(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
220 | || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
221 | LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
222 | requestForCurrentLocation();
223 | }
224 | } else {
225 | if (!(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
226 | || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
227 | requestForCurrentLocation();
228 | }
229 | }
230 | }
231 |
232 | @Override
233 | public void startUpdates() {
234 | if (!enableUpdates) {
235 | enableUpdates = true;
236 | requestLocationUpdates();
237 | }
238 | }
239 |
240 | @Override
241 | public void addApi(@NonNull Api extends Api.ApiOptions.NotRequiredOptions>[] value) {
242 | if (mGoogleApiClient != null)
243 | mGoogleApiClient.disconnect();
244 | GoogleApiClient.Builder builder = new GoogleApiClient.Builder(this).addApi(LocationServices.API).
245 | addConnectionCallbacks(this).addOnConnectionFailedListener(this);
246 | for (Api extends Api.ApiOptions.NotRequiredOptions> options : value) {
247 | if (!options.getName().equalsIgnoreCase(LocationServices.API.getName())) {
248 | builder.addApi(options);
249 | }
250 | }
251 | mGoogleApiClient = builder.build();
252 | if (!servicesConnected())
253 | mGoogleApiClient.connect();
254 | }
255 |
256 | @Override
257 | public void addApi(@NonNull Api extends Api.ApiOptions.NotRequiredOptions> value) {
258 | if (mGoogleApiClient != null)
259 | mGoogleApiClient.disconnect();
260 | GoogleApiClient.Builder builder = new GoogleApiClient.Builder(this).addApi(LocationServices.API).
261 | addConnectionCallbacks(this).addOnConnectionFailedListener(this);
262 | if (!value.getName().equalsIgnoreCase(LocationServices.API.getName())) {
263 | addApi(value);
264 | }
265 | mGoogleApiClient = builder.build();
266 | if (!servicesConnected())
267 | mGoogleApiClient.connect();
268 | }
269 |
270 | @Override
271 | public void onDestroy() {
272 | if (mGoogleApiClient.isConnected())
273 | mGoogleApiClient.disconnect();
274 | super.onDestroy();
275 | }
276 | }
--------------------------------------------------------------------------------
/google-support-location/src/main/java/com/github/akashandroid90/googlesupport/location/AppLocationSupportFragment.java:
--------------------------------------------------------------------------------
1 | package com.github.akashandroid90.googlesupport.location;
2 |
3 | import android.Manifest;
4 | import android.app.Activity;
5 | import android.content.Context;
6 | import android.content.DialogInterface;
7 | import android.content.Intent;
8 | import android.content.IntentSender;
9 | import android.content.pm.PackageManager;
10 | import android.location.Location;
11 | import android.location.LocationManager;
12 | import android.os.Bundle;
13 | import android.support.annotation.NonNull;
14 | import android.support.annotation.Nullable;
15 | import android.support.v4.app.ActivityCompat;
16 | import android.support.v4.app.Fragment;
17 | import android.support.v4.app.FragmentActivity;
18 |
19 | import com.google.android.gms.common.ConnectionResult;
20 | import com.google.android.gms.common.GoogleApiAvailability;
21 | import com.google.android.gms.common.api.Api;
22 | import com.google.android.gms.common.api.GoogleApiClient;
23 | import com.google.android.gms.common.api.PendingResult;
24 | import com.google.android.gms.common.api.ResultCallback;
25 | import com.google.android.gms.common.api.Status;
26 | import com.google.android.gms.location.LocationRequest;
27 | import com.google.android.gms.location.LocationServices;
28 | import com.google.android.gms.location.LocationSettingsRequest;
29 | import com.google.android.gms.location.LocationSettingsResult;
30 | import com.google.android.gms.location.LocationSettingsStatusCodes;
31 |
32 | import java.util.Random;
33 |
34 | import static android.app.Activity.RESULT_CANCELED;
35 | import static android.app.Activity.RESULT_OK;
36 |
37 | /**
38 | * Created by akash on 8/12/15.
39 | */
40 | public abstract class AppLocationSupportFragment extends Fragment
41 | implements GoogleContextSupportLocation {
42 |
43 | private final int ACCESS_FINE_LOCATION = 250;
44 | private final int ACCESS_COARSE_LOCATION = 251;
45 | private final int ACCESS_LOCATION = 252;
46 | private final int REQUEST_CHECK_SETTINGS = 253;
47 | private final int ACCESS_FUSED_LOCATION = 254;
48 | private final int REQUEST_CODE_PLAY_SERVICES = 255;
49 |
50 | protected Context mContext;
51 | private LocationManager mLocationService;
52 | private GoogleApiClient mGoogleApiClient;
53 | private LocationRequest mLocationRequest;
54 | private ConnectionResult mConnectionResult;
55 | private GoogleApiAvailability mGoogleApiAvailability;
56 |
57 | private boolean enableUpdates;
58 |
59 | /**
60 | * this method gives GoogleApiAvailability object created
61 | *
62 | * @return GoogleApiAvailability
63 | */
64 | @Override
65 | public GoogleApiAvailability getGoogleApiAvailability() {
66 | return mGoogleApiAvailability;
67 | }
68 |
69 | /**
70 | * this method gives GoogleApiClient object created
71 | *
72 | * @return GoogleApiClient
73 | */
74 | @Override
75 | public GoogleApiClient getGoogleApiClient() {
76 | return mGoogleApiClient;
77 | }
78 |
79 | /**
80 | * this method gives LocationRequest object created
81 | *
82 | * @return LocationRequest
83 | */
84 | @Override
85 | public LocationRequest getLocationRequest() {
86 | return mLocationRequest;
87 | }
88 |
89 | /**
90 | * this method gives LocationManager object created
91 | *
92 | * @return LocationManager
93 | */
94 |
95 | public LocationManager getLocationService() {
96 | return mLocationService;
97 | }
98 |
99 | @Override
100 | public void onAttach(Context context) {
101 | super.onAttach(context);
102 | mContext = context;
103 | }
104 |
105 | @Override
106 | public void onAttach(Activity activity) {
107 | super.onAttach(activity);
108 | mContext = activity;
109 | }
110 |
111 | @Override
112 | public void onConnected(Bundle bundle) {
113 | mConnectionResult = null;
114 | checkLocationEnable();
115 | }
116 |
117 | @Override
118 | public void myCurrentLocation(Location currentLocation) {
119 | }
120 |
121 | @Override
122 | public void onServiceDialogCancel(DialogInterface dialog, ConnectionResult connectionResult) {
123 | }
124 |
125 | @Override
126 | public void onConnectionSuspended(int i) {
127 | if (!mGoogleApiClient.isConnected())
128 | mGoogleApiClient.reconnect();
129 | }
130 |
131 | @Override
132 | public void onConnectionFailed(ConnectionResult connectionResult) {
133 | showServiceErrorDialog(connectionResult);
134 | }
135 |
136 | @Override
137 | public void onCancel(DialogInterface dialog) {
138 | onServiceDialogCancel(dialog, mConnectionResult);
139 | }
140 |
141 | @Override
142 | public void onLocationChanged(Location location) {
143 | newLocation(location);
144 | }
145 |
146 |
147 | protected final void checkLocationEnable() {
148 |
149 | if (enableUpdates && mGoogleApiClient != null && mGoogleApiClient.isConnected())
150 | LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
151 |
152 | LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
153 | .addLocationRequest(mLocationRequest).setAlwaysShow(true);
154 |
155 | PendingResult result =
156 | LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
157 |
158 | result.setResultCallback(new ResultCallback() {
159 | @Override
160 | public void onResult(LocationSettingsResult result) {
161 | final Status status = result.getStatus();
162 | // mLocationSettingsStates = result.getLocationSettingsStates();
163 | switch (status.getStatusCode()) {
164 | case LocationSettingsStatusCodes.SUCCESS:
165 | // All location settings are satisfied. The client can initialize location
166 | // requests here.
167 |
168 | requestLocationUpdates();
169 | break;
170 | case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
171 | // Location settings are not satisfied. But could be fixed by showing the user
172 | // a dialog.
173 | try {
174 | // Show the dialog by calling startResolutionForResult(),
175 | // and check the result in onActivityResult().
176 | status.startResolutionForResult((Activity) mContext, REQUEST_CHECK_SETTINGS);
177 | } catch (IntentSender.SendIntentException e) {
178 | // Ignore the error.
179 | }
180 | break;
181 | case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
182 | // Location settings are not satisfied. However, we have no way to fix the
183 | // settings so we won't show the dialog.
184 |
185 | break;
186 | }
187 | }
188 | });
189 |
190 | }
191 |
192 | @Override
193 | public void onCreate(@Nullable Bundle savedInstanceState) {
194 | super.onCreate(savedInstanceState);
195 | mGoogleApiAvailability = GoogleApiAvailability.getInstance();
196 | mGoogleApiClient = new GoogleApiClient.Builder(mContext).addApi(LocationServices.API).
197 | addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
198 |
199 | mLocationService = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
200 |
201 | mLocationRequest = LocationRequest.create();
202 |
203 | Bundle bundle = getArguments();
204 | if (bundle != null)
205 | enableUpdates = bundle.getBoolean(AppLocation.REQUEST_UPDATES, true);
206 | else
207 | enableUpdates = true;
208 |
209 | }
210 |
211 | /**
212 | * @param fastInterval time to request update frequently
213 | */
214 | @Override
215 | public void setFastestInterval(long fastInterval) {
216 | mLocationRequest.setFastestInterval(fastInterval);
217 | checkLocationEnable();
218 | }
219 |
220 | /**
221 | * @param distance used to set displacement for request make
222 | */
223 | @Override
224 | public void setSmallestDisplacement(long distance) {
225 | mLocationRequest.setSmallestDisplacement(distance);
226 | checkLocationEnable();
227 | }
228 |
229 | /**
230 | * @param interval time in millis for location request
231 | */
232 | @Override
233 | public void setInterval(long interval) {
234 | mLocationRequest.setInterval(interval);
235 | checkLocationEnable();
236 | }
237 |
238 | /**
239 | * @param priority int value to set location request priority
240 | */
241 | @Override
242 | public void setPriority(int priority) {
243 | mLocationRequest.setPriority(priority);
244 | checkLocationEnable();
245 | }
246 |
247 |
248 | @Override
249 | public void onStart() {
250 | // if (mLocationSettingsStates != null && mLocationSettingsStates.isLocationUsable()) {
251 | if (!servicesConnected())
252 | mGoogleApiClient.connect();
253 | // }
254 | super.onStart();
255 | }
256 |
257 | @Override
258 | public void onStop() {
259 | if (mGoogleApiClient.isConnected())
260 | mGoogleApiClient.disconnect();
261 | super.onStop();
262 | }
263 |
264 | @Override
265 | public void stopUpdates() {
266 | if (enableUpdates) {
267 | enableUpdates = false;
268 | LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
269 | }
270 | }
271 |
272 | @Override
273 | public void startUpdates() {
274 | if (!enableUpdates) {
275 | enableUpdates = true;
276 | requestLocationUpdates();
277 | }
278 | }
279 |
280 | private void requestLocationUpdates() {
281 | if (enableUpdates) {
282 | if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
283 | || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
284 | requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, ACCESS_FUSED_LOCATION);
285 | else {
286 | LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
287 | requestForCurrentLocation();
288 | }
289 | } else {
290 | if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
291 | || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
292 | ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, ACCESS_FUSED_LOCATION);
293 | else {
294 | requestForCurrentLocation();
295 | }
296 | }
297 | }
298 |
299 | @Override
300 | public void addApi(@NonNull Api extends Api.ApiOptions.NotRequiredOptions> value) {
301 | if (mGoogleApiClient != null)
302 | mGoogleApiClient.disconnect();
303 | GoogleApiClient.Builder builder = new GoogleApiClient.Builder(mContext).addApi(LocationServices.API).enableAutoManage((FragmentActivity) mContext, new Random().nextInt(Integer.MAX_VALUE), this).
304 | addConnectionCallbacks(this).addOnConnectionFailedListener(this);
305 | if (!value.getName().equalsIgnoreCase(LocationServices.API.getName())) {
306 | addApi(value);
307 | }
308 | mGoogleApiClient = builder.build();
309 | if (!servicesConnected())
310 | mGoogleApiClient.connect();
311 | }
312 |
313 | @Override
314 | public void addApi(@NonNull Api extends Api.ApiOptions.NotRequiredOptions>[] value) {
315 | if (mGoogleApiClient != null)
316 | mGoogleApiClient.disconnect();
317 | GoogleApiClient.Builder builder = new GoogleApiClient.Builder(mContext).addApi(LocationServices.API).enableAutoManage((FragmentActivity) mContext, new Random().nextInt(Integer.MAX_VALUE), this).
318 | addConnectionCallbacks(this).addOnConnectionFailedListener(this);
319 | for (Api extends Api.ApiOptions.NotRequiredOptions> options : value) {
320 | if (!options.getName().equalsIgnoreCase(LocationServices.API.getName())) {
321 | builder.addApi(options);
322 | }
323 | }
324 | mGoogleApiClient = builder.build();
325 | if (!servicesConnected())
326 | mGoogleApiClient.connect();
327 | }
328 |
329 | @Override
330 | public boolean servicesConnected() {
331 | // Check that Google Play services is available
332 | int resultCode = mGoogleApiAvailability.isGooglePlayServicesAvailable(mContext);
333 |
334 | // If Google Play services is available
335 | if (ConnectionResult.SUCCESS == resultCode) {
336 | if (mGoogleApiClient.isConnected())
337 | return true;
338 | else
339 | return false;
340 | }
341 | return false;
342 | }
343 |
344 | @Override
345 | public void newLocation(Location location) {
346 | }
347 |
348 | @Override
349 | public Location requestForCurrentLocation() {
350 | // If Google Play Services is available
351 | Location currentLocation = null;
352 | if (servicesConnected()) {
353 | // Get the current location
354 |
355 | currentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
356 | }
357 | if (currentLocation == null) {
358 |
359 | if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
360 | && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
361 | requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, ACCESS_LOCATION);
362 |
363 | else {
364 | Location locationGPS = mLocationService.getLastKnownLocation(LocationManager.GPS_PROVIDER);
365 | Location locationNet = mLocationService.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
366 |
367 | long GPSLocationTime = 0;
368 | if (null != locationGPS) {
369 | GPSLocationTime = locationGPS.getTime();
370 | }
371 |
372 | long NetLocationTime = 0;
373 |
374 | if (null != locationNet) {
375 | NetLocationTime = locationNet.getTime();
376 | }
377 |
378 | if (0 < GPSLocationTime - NetLocationTime) {
379 | currentLocation = locationGPS;
380 | } else {
381 | currentLocation = locationNet;
382 | }
383 | }
384 |
385 | if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
386 | && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
387 | requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_FINE_LOCATION);
388 | else
389 | currentLocation = mLocationService.getLastKnownLocation(LocationManager.GPS_PROVIDER);
390 |
391 | if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
392 | && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
393 | requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, ACCESS_COARSE_LOCATION);
394 | else
395 | currentLocation = mLocationService.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
396 | }
397 | if (currentLocation != null)
398 | myCurrentLocation(currentLocation);
399 | return currentLocation;
400 | }
401 |
402 | @Override
403 | public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
404 | super.onRequestPermissionsResult(requestCode, permissions, grantResults);
405 | switch (requestCode) {
406 | case ACCESS_COARSE_LOCATION:
407 | if ((permissions.length > 0 && permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_COARSE_LOCATION)) && (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED))
408 | requestForCurrentLocation();
409 | else onRequestPermissionsResultError(requestCode, permissions, grantResults);
410 | break;
411 | case ACCESS_FINE_LOCATION:
412 | if ((permissions.length > 0 && permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION)) && (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED))
413 | requestForCurrentLocation();
414 | else onRequestPermissionsResultError(requestCode, permissions, grantResults);
415 | break;
416 | case ACCESS_LOCATION:
417 | if (permissions.length > 0 && ((permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION)
418 | || permissions[1].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION)) ||
419 | ((permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_COARSE_LOCATION)
420 | || permissions[1].equalsIgnoreCase(Manifest.permission.ACCESS_COARSE_LOCATION))))) {
421 | if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED &&
422 | grantResults[1] == PackageManager.PERMISSION_GRANTED)
423 | requestForCurrentLocation();
424 | else onRequestPermissionsResultError(requestCode, permissions, grantResults);
425 | }
426 | case ACCESS_FUSED_LOCATION:
427 | if (permissions.length > 0 && ((permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION)
428 | || permissions[1].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION)) ||
429 | ((permissions[0].equalsIgnoreCase(Manifest.permission.ACCESS_COARSE_LOCATION)
430 | || permissions[1].equalsIgnoreCase(Manifest.permission.ACCESS_COARSE_LOCATION))))) {
431 | if (grantResults.length > 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED ||
432 | grantResults[1] == PackageManager.PERMISSION_GRANTED) {
433 | LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
434 | requestForCurrentLocation();
435 | } else if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
436 | requestForCurrentLocation();
437 | LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
438 | } else onRequestPermissionsResultError(requestCode, permissions, grantResults);
439 | }
440 | break;
441 | }
442 | }
443 |
444 | @Override
445 | public void showServiceErrorDialog(ConnectionResult connectionResult) {
446 | mConnectionResult = connectionResult;
447 | if (mGoogleApiAvailability.isUserResolvableError(connectionResult.getErrorCode()))
448 | mGoogleApiAvailability.getErrorDialog((Activity) mContext, connectionResult.getErrorCode(), REQUEST_CODE_PLAY_SERVICES, this).show();
449 | }
450 |
451 | @Override
452 | public void showServiceErrorDialog(ConnectionResult connectionResult, int requestCode) {
453 | mConnectionResult = connectionResult;
454 | if (mGoogleApiAvailability.isUserResolvableError(connectionResult.getErrorCode()))
455 | mGoogleApiAvailability.getErrorDialog((Activity) mContext, connectionResult.getErrorCode(), requestCode, this).show();
456 | }
457 |
458 | @Override
459 | public void onActivityResult(int requestCode, int resultCode, Intent data) {
460 | // final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
461 | switch (requestCode) {
462 | case REQUEST_CHECK_SETTINGS:
463 | switch (resultCode) {
464 | case RESULT_OK:
465 | // All required changes were successfully made
466 | if (!mGoogleApiClient.isConnected())
467 | mGoogleApiClient.connect();
468 | else {
469 | try {
470 | Thread.sleep(500);
471 | requestLocationUpdates();
472 | } catch (InterruptedException e) {
473 | e.printStackTrace();
474 | }
475 | }
476 | break;
477 | case RESULT_CANCELED:
478 | // The user was asked to change settings, but chose not to
479 | onActivityResultError(resultCode, ServiceError.LOCATION_SETTING_ERROR, null);
480 | break;
481 | default:
482 | onActivityResultError(resultCode, ServiceError.LOCATION_SETTING_ERROR, null);
483 | break;
484 | }
485 | break;
486 | case REQUEST_CODE_PLAY_SERVICES:
487 | switch (resultCode) {
488 | case RESULT_OK:
489 | // All required changes were successfully made
490 | if (!mGoogleApiClient.isConnected())
491 | mGoogleApiClient.connect();
492 | else
493 | requestLocationUpdates();
494 | break;
495 | default:
496 | if (mConnectionResult != null)
497 | onActivityResultError(resultCode, ServiceError.GOOGLE_PLAY_SERVICE_ERROR, mConnectionResult);
498 | break;
499 | }
500 | break;
501 | }
502 | super.onActivityResult(requestCode, resultCode, data);
503 | }
504 |
505 | @Override
506 | public void onActivityResultError(int resultCode, ServiceError serviceError, ConnectionResult connectionResult) {
507 | }
508 |
509 | @Override
510 | public void onRequestPermissionsResultError(int requestCode, String[] permissions, int[] grantResults) {
511 | }
512 | }
--------------------------------------------------------------------------------
/google-support-location/src/main/java/com/github/akashandroid90/googlesupport/location/GoogleContextSupportLocation.java:
--------------------------------------------------------------------------------
1 | package com.github.akashandroid90.googlesupport.location;
2 |
3 | import android.content.DialogInterface;
4 | import android.location.Location;
5 | import android.location.LocationManager;
6 | import android.support.annotation.NonNull;
7 |
8 | import com.google.android.gms.common.ConnectionResult;
9 | import com.google.android.gms.common.GoogleApiAvailability;
10 | import com.google.android.gms.common.api.Api;
11 | import com.google.android.gms.common.api.GoogleApiClient;
12 | import com.google.android.gms.location.LocationListener;
13 | import com.google.android.gms.location.LocationRequest;
14 |
15 | /**
16 | * Created by Akash Jain on 12-Dec-15.
17 | * this interface is used to provide location
18 | */
19 | public interface GoogleContextSupportLocation extends GoogleSupportLocation, DialogInterface.OnCancelListener {
20 | void onActivityResultError(int resultCode, ServiceError serviceError, ConnectionResult connectionResult);
21 | void showServiceErrorDialog(ConnectionResult connectionResult);
22 | void showServiceErrorDialog(ConnectionResult connectionResult, int requestCode);
23 | void onServiceDialogCancel(DialogInterface dialog, ConnectionResult connectionResult);
24 | void onRequestPermissionsResultError(int requestCode, String[] permissions, int[] grantResults);
25 | }
26 |
--------------------------------------------------------------------------------
/google-support-location/src/main/java/com/github/akashandroid90/googlesupport/location/GoogleSupportLocation.java:
--------------------------------------------------------------------------------
1 | package com.github.akashandroid90.googlesupport.location;
2 |
3 | import android.content.DialogInterface;
4 | import android.location.Location;
5 | import android.location.LocationManager;
6 | import android.support.annotation.NonNull;
7 |
8 | import com.google.android.gms.common.ConnectionResult;
9 | import com.google.android.gms.common.GoogleApiAvailability;
10 | import com.google.android.gms.common.api.Api;
11 | import com.google.android.gms.common.api.GoogleApiClient;
12 | import com.google.android.gms.location.LocationListener;
13 | import com.google.android.gms.location.LocationRequest;
14 |
15 | /**
16 | * Created by Akash Jain on 12-Dec-15.
17 | * this interface is used to provide location
18 | */
19 | public interface GoogleSupportLocation extends GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
20 |
21 | int PRIORITY_BALANCED_POWER_ACCURACY = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY;
22 | int PRIORITY_HIGH_ACCURACY = LocationRequest.PRIORITY_HIGH_ACCURACY;
23 | int PRIORITY_LOW_POWER = LocationRequest.PRIORITY_LOW_POWER;
24 | int PRIORITY_NO_POWER = LocationRequest.PRIORITY_NO_POWER;
25 |
26 | void newLocation(Location location);
27 | void myCurrentLocation(Location currentLocation);
28 | Location requestForCurrentLocation();
29 | GoogleApiClient getGoogleApiClient();
30 | GoogleApiAvailability getGoogleApiAvailability();
31 | LocationRequest getLocationRequest();
32 | LocationManager getLocationService();
33 | void setFastestInterval(long fastInterval);
34 | void setSmallestDisplacement(long distance);
35 | void setInterval(long interval);
36 | void setPriority(int priority);
37 | void stopUpdates();
38 | void startUpdates();
39 | void addApi(@NonNull Api extends Api.ApiOptions.NotRequiredOptions>[] value);
40 | void addApi(@NonNull Api extends Api.ApiOptions.NotRequiredOptions> value);
41 | boolean servicesConnected();
42 |
43 | enum ServiceError {
44 | GOOGLE_PLAY_SERVICE_ERROR, LOCATION_SETTING_ERROR
45 | }
46 | }
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/images/four.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akashjaindev/GooglePlayServiceLocationSupport/23582afb84183d9fc16187f44b8cb866d81c0fc1/images/four.png
--------------------------------------------------------------------------------
/images/one.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akashjaindev/GooglePlayServiceLocationSupport/23582afb84183d9fc16187f44b8cb866d81c0fc1/images/one.png
--------------------------------------------------------------------------------
/images/three.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akashjaindev/GooglePlayServiceLocationSupport/23582afb84183d9fc16187f44b8cb866d81c0fc1/images/three.png
--------------------------------------------------------------------------------
/images/two.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akashjaindev/GooglePlayServiceLocationSupport/23582afb84183d9fc16187f44b8cb866d81c0fc1/images/two.png
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/akashjaindev/GooglePlayServiceLocationSupport/23582afb84183d9fc16187f44b8cb866d81c0fc1/settings.gradle
--------------------------------------------------------------------------------