--------------------------------MainActivity----------------------------------
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener{
private TextView latitudeTextView,longitudeTextView;
private Location mylocation;
private GoogleApiClient googleApiClient;
private final static int REQUEST_CHECK_SETTINGS_GPS=0x1;
private final static int REQUEST_ID_MULTIPLE_PERMISSIONS=0x2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latitudeTextView=(TextView)findViewById(R.id.latitudeTextView);
longitudeTextView=(TextView)findViewById(R.id.longitudeTextView);
setUpGClient();
}
private synchronized void setUpGClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, 0, this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
@Override
public void onLocationChanged(Location location) {
mylocation = location;
if (mylocation != null) {
Double latitude=mylocation.getLatitude();
Double longitude=mylocation.getLongitude();
latitudeTextView.setText("Latitude : "+latitude);
longitudeTextView.setText("Longitude : "+longitude);
//Or Do whatever you want with your location
}
}
@Override
public void onConnected(Bundle bundle) {
checkPermissions();
}
@Override
public void onConnectionSuspended(int i) {
//Do whatever you need
//You can display a message here
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
//You can display a message here
}
private void getMyLocation(){
if(googleApiClient!=null) {
if (googleApiClient.isConnected()) {
int permissionLocation = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
mylocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(3000);
locationRequest.setFastestInterval(3000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
LocationServices.FusedLocationApi
.requestLocationUpdates(googleApiClient, locationRequest, this);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi
.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied.
// You can initialize location requests here.
int permissionLocation = ContextCompat
.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
mylocation = LocationServices.FusedLocationApi
.getLastLocation(googleApiClient);
}
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied.
// But could be fixed by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
// Ask to turn on GPS automatically
status.startResolutionForResult(MainActivity.this,
REQUEST_CHECK_SETTINGS_GPS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied.
// However, we have no way
// to fix the
// settings so we won't show the dialog.
// finish();
break;
}
}
});
}
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CHECK_SETTINGS_GPS:
switch (resultCode) {
case Activity.RESULT_OK:
getMyLocation();
break;
case Activity.RESULT_CANCELED:
finish();
break;
}
break;
}
}
private void checkPermissions(){
int permissionLocation = ContextCompat.checkSelfPermission(MainActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION);
List<String> listPermissionsNeeded = new ArrayList<>();
if (permissionLocation != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this,
listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
}
}else{
getMyLocation();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
int permissionLocation = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
getMyLocation();
}
}
}
---------------------activity_main.xml------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp">
<TextView
android:layout_width="match_parent"
android:textColor="#000000"
android:gravity="center"
android:textSize="20sp"
android:layout_height="wrap_content"
android:text="My Location" />
<TextView
android:layout_marginTop="10dp"
android:textSize="18sp"
android:id="@+id/latitudeTextView"
android:text="Latitude : "
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_marginTop="10dp"
android:textSize="18sp"
android:id="@+id/longitudeTextView"
android:text="Longitude :"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
---------------------androidmanifest.xml-------------------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.loggedshirsh.testapplication">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature
android:name="android.hardware.location.gps"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
---------------------build.gradle(app)------------------------------------
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.android.gms:play-services-location:10.0.1'
compile 'com.android.support:appcompat-v7:25.0.1'
}
apply plugin: 'com.google.gms.google-services'
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener{
private TextView latitudeTextView,longitudeTextView;
private Location mylocation;
private GoogleApiClient googleApiClient;
private final static int REQUEST_CHECK_SETTINGS_GPS=0x1;
private final static int REQUEST_ID_MULTIPLE_PERMISSIONS=0x2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latitudeTextView=(TextView)findViewById(R.id.latitudeTextView);
longitudeTextView=(TextView)findViewById(R.id.longitudeTextView);
setUpGClient();
}
private synchronized void setUpGClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, 0, this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
@Override
public void onLocationChanged(Location location) {
mylocation = location;
if (mylocation != null) {
Double latitude=mylocation.getLatitude();
Double longitude=mylocation.getLongitude();
latitudeTextView.setText("Latitude : "+latitude);
longitudeTextView.setText("Longitude : "+longitude);
//Or Do whatever you want with your location
}
}
@Override
public void onConnected(Bundle bundle) {
checkPermissions();
}
@Override
public void onConnectionSuspended(int i) {
//Do whatever you need
//You can display a message here
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
//You can display a message here
}
private void getMyLocation(){
if(googleApiClient!=null) {
if (googleApiClient.isConnected()) {
int permissionLocation = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
mylocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(3000);
locationRequest.setFastestInterval(3000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
LocationServices.FusedLocationApi
.requestLocationUpdates(googleApiClient, locationRequest, this);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi
.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied.
// You can initialize location requests here.
int permissionLocation = ContextCompat
.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
mylocation = LocationServices.FusedLocationApi
.getLastLocation(googleApiClient);
}
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied.
// But could be fixed by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
// Ask to turn on GPS automatically
status.startResolutionForResult(MainActivity.this,
REQUEST_CHECK_SETTINGS_GPS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied.
// However, we have no way
// to fix the
// settings so we won't show the dialog.
// finish();
break;
}
}
});
}
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CHECK_SETTINGS_GPS:
switch (resultCode) {
case Activity.RESULT_OK:
getMyLocation();
break;
case Activity.RESULT_CANCELED:
finish();
break;
}
break;
}
}
private void checkPermissions(){
int permissionLocation = ContextCompat.checkSelfPermission(MainActivity.this,
android.Manifest.permission.ACCESS_FINE_LOCATION);
List<String> listPermissionsNeeded = new ArrayList<>();
if (permissionLocation != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this,
listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
}
}else{
getMyLocation();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
int permissionLocation = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
getMyLocation();
}
}
}
---------------------activity_main.xml------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp">
<TextView
android:layout_width="match_parent"
android:textColor="#000000"
android:gravity="center"
android:textSize="20sp"
android:layout_height="wrap_content"
android:text="My Location" />
<TextView
android:layout_marginTop="10dp"
android:textSize="18sp"
android:id="@+id/latitudeTextView"
android:text="Latitude : "
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_marginTop="10dp"
android:textSize="18sp"
android:id="@+id/longitudeTextView"
android:text="Longitude :"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
---------------------androidmanifest.xml-------------------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.loggedshirsh.testapplication">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature
android:name="android.hardware.location.gps"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
---------------------build.gradle(app)------------------------------------
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.android.gms:play-services-location:10.0.1'
compile 'com.android.support:appcompat-v7:25.0.1'
}
apply plugin: 'com.google.gms.google-services'
No comments:
Post a Comment