Tuesday, 29 November 2016

Location Manager

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
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;

public class LocationManager implements LocationListener, ConnectionCallbacks, OnConnectionFailedListener, ResultCallback<LocationSettingsResult>,
        android.location.LocationListener {

    private Activity activity;
    private LocationHandlerListener listener;
    private static LocationManager instance;
    public static final int REQUEST_CHECK_SETTINGS = 1005;
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest request;
    private boolean isReqLocation;
    private LocationSettingsRequest.Builder builder;
    private PendingResult<LocationSettingsResult> result;
    private Location currentLocation;
    private android.location.LocationManager locationManager;
    private LocationSettingsRequest settingReq;

    private LocationManager(Activity activity) {
        this.activity = activity;
    }

    public static LocationManager getInstance(Activity activity) {
        if (instance == null) {
            instance = new LocationManager(activity);
        }
        return instance;
    }

    public LocationManager buildAndConnectClient() {
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(activity).addApi(LocationServices.API).addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).build();
        }
        if (!mGoogleApiClient.isConnected()) {
            mGoogleApiClient.connect();

        }
        if (locationManager == null) {
            locationManager = (android.location.LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
            int permissionCheck = ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                locationManager.requestLocationUpdates(android.location.LocationManager.GPS_PROVIDER, 0, 0, this);
            }
        }
        return this;
    }

    public LocationManager setLocationHandlerListener(LocationHandlerListener listener) {
        this.listener = listener;
        return this;
    }

    public LocationManager buildLocationRequest() {
        if (settingReq == null) {
            request = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            request.setInterval(5000);
            request.setFastestInterval(2000);
            builder = new LocationSettingsRequest.Builder().addLocationRequest(request);
            settingReq = builder.build();
        }
        return this;
    }

    public boolean requestLocation() {
        if (!mGoogleApiClient.isConnected()) {
            isReqLocation = true;
            return false;
        }
        result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, settingReq);
        result.setResultCallback(this);
        return true;
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CHECK_SETTINGS:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        int permissionCheck = ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION);
                        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, request, instance);
                        }
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(activity, "You Must enable Location Service for app functionality ", Toast.LENGTH_SHORT).show();
                        requestLocation();
                        break;
                    default:
                        break;
                }
                break;
        }
    }

    @Override
    public void onLocationChanged(Location arg0) {
        if (listener != null) {
            listener.locationChanged(arg0);
            currentLocation = arg0;
        }
    }

    public interface LocationHandlerListener {
        public void locationChanged(Location location);

        public void lastKnownLocationAfterConnection(Location location);
    }

    @Override
    public void onConnected(Bundle arg0) {
        // Toast.makeText(activity, "Conn", Toast.LENGTH_SHORT).show();
        if (isReqLocation) {
            requestLocation();
        }
        int permissionCheck = ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION);
        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
            currentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        }
        if (listener != null) {
            listener.lastKnownLocationAfterConnection(currentLocation);
        }
    }

    @Override
    public void onConnectionSuspended(int arg0) {
        // Toast.makeText(activity, "Conn Sus", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {
        // Toast.makeText(activity, "Conn Fail", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onResult(LocationSettingsResult result) {
        final Status status = result.getStatus();
        switch (status.getStatusCode()) {
            case LocationSettingsStatusCodes.SUCCESS:
                int permissionCheck = ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION);
                if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                    // Should we show an explanation?
                    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, request, instance);
                }
                break;
            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                try {
                    if (activity != null) {
                        status.startResolutionForResult(activity, REQUEST_CHECK_SETTINGS);
                    }
                } catch (SendIntentException e) {
                    e.printStackTrace();
                }
                break;
            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                break;
        }
    }

    public Location getCurrentLocation() {
        return currentLocation;
    }

    public void stopTracking() {
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, instance);
        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {
        if (result != null) {
            result.cancel();
        }

    }

    @Override
    public void onProviderDisabled(String provider) {
        if (result != null) {
            result.cancel();
            requestLocation();
        }
    }

    public void removeLocationUpdate(){
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (LocationListener) listener);
    }
}








######################################################

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.liftindia.app" >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.CALL_PHONE" />

    <!-- FOR STORAGE ACCESS -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <!-- FOR LOCATION MANAGER -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />

    <!-- FOR SMS RECEIVER -->
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <permission
        android:name="com.liftindia.app.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.liftindia.app.permission.C2D_MESSAGE" />

    <application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@mipmap/app_icon"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".activity.MainActivity"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustNothing" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />
        <activity
            android:name="com.paytm.pgsdk.PaytmPGActivity"
            android:configChanges="keyboardHidden|orientation|keyboard"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activity.LoginActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activity.OtpVerifyActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activity.ProfileActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activity.VehicleActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activity.OffererProfileActivity"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustNothing" />
        <activity
            android:name=".activity.ProfileReviewActivity"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustNothing" />
        <activity
            android:name=".activity.CropperActivity"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustNothing" />
        <activity
            android:name=".activity.HomeActivity"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustNothing" />
        <activity
            android:name=".activity.ForgotPasswordActivity"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustNothing" />
        <activity
            android:name=".firebase.ChatActivity"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="adjustPan" />

        <meta-data
            android:name="io.fabric.ApiKey"
            android:value="74bdaf80f3fcb4feb3ba98a74eec7bfa5c113cc0" />
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyDOcFIdUswKi68KacfepL-EB2Sa1DpSIs4" />
        <!-- [START gcm_receiver] -->
        <receiver
            android:name="com.google.android.gms.gcm.GcmReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />

                <category android:name="gcm.play.android.samples.com.gcmquickstart" />
            </intent-filter>
        </receiver>
        <!-- [END gcm_receiver] -->

        <receiver android:name=".ServiceStarter" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <!-- [START gcm_listener] -->
        <service
            android:name=".gcm.MyGcmListenerService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>
        <!-- [END gcm_listener] -->
        <!-- [START instanceId_listener] -->
        <service
            android:name=".gcm.MyInstanceIDListenerService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.android.gms.iid.InstanceID" />
            </intent-filter>
        </service>
        <!-- [END instanceId_listener] -->
        <service
            android:name=".gcm.RegistrationIntentService"
            android:exported="false" />
        <service
            android:name=".gcm.FirebaseNotificationService"
            android:exported="false" />

        <activity android:name=".activity.RecurringActivity" />
        <activity android:name=".activity.TrackerUserActivity" />
    </application>


</manifest>

No comments:

Post a Comment