Skip to main content

Location Service


Gradles
compile 'com.google.android.gms:play-services-maps:10.0.1'  /*Google Maps*/
compile 'com.google.android.gms:play-services-location:10.0.1'

apply plugin: 'com.google.gms.google-services'

Dependencies
classpath 'com.google.gms:google-services:3.0.0'

 Location Service

import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener {

    public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 2000;
    /**     * 60000 1 min     */    public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
            UPDATE_INTERVAL_IN_MILLISECONDS / 2;
    /**     * 1sec     */    private static final int DISPLACEMENT_DISTANCE = 5; /* 1000=1 km*/
    private static final String TAG = "LocationService";
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    SharedPreferences pref;


    @Override    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "Service onStartCommand");
        pref = getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);
        buildGoogleApiClient();
        return START_STICKY;
    }


    protected synchronized void buildGoogleApiClient() {
        LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        boolean isGPSEnabled = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean isNetworkEnabled = manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
//        if (!isGPSEnabled && !isNetworkEnabled) {//            buildAlertMessageNoGps();//        } else {        Log.i(TAG, "Building GoogleApiClient");
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
        createLocationRequest();
//        }    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT_DISTANCE);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }


    protected void startLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling            //    ActivityCompat#requestPermissions            // here to request the missing permissions, and then overriding            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,            //                                          int[] grantResults)            // to handle the case where the user grants the permission. See the documentation            // for ActivityCompat#requestPermissions for more details.            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
    }


    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }


//    private void buildAlertMessageNoGps() {//        final AlertDialog.Builder builder = new AlertDialog.Builder(this);//        builder.setMessage(getString(R.string.msg_alert_gps))//                .setCancelable(false)//                .setPositiveButton(getString(R.string.str_yes), new DialogInterface.OnClickListener() {//                    public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {//                        dialog.cancel();//                        startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));//                    }//                })//                .setNegativeButton(getString(R.string.str_no), new DialogInterface.OnClickListener() {//                    public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {//                        dialog.cancel();//                    }//                });//        final AlertDialog alert = builder.create();//        alert.show();//    }

    @Override    public void onConnected(Bundle bundle) {
        Log.e(TAG, "Service Connect");
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling            //    ActivityCompat#requestPermissions            // here to request the missing permissions, and then overriding            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,            //                                          int[] grantResults)            // to handle the case where the user grants the permission. See the documentation            // for ActivityCompat#requestPermissions for more details.            return;
        }

        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            if (location == null) {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            } else {
//            handleNewLocation(location);            }


            /**update location frequently**/            startLocationUpdates();
        }


    }


    @Override    public void onConnectionSuspended(int i) {
        mGoogleApiClient.connect();
    }

    @Override    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());

        if (connectionResult.hasResolution()) {
            Log.e(TAG, "onConnectionFailed: " + connectionResult.getErrorMessage());
//            try {//                // Start an Activity that tries to resolve the error//                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);//            } catch (IntentSender.SendIntentException e) {//                e.printStackTrace();//            }        } else {
            Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }


    @Override    public void onLocationChanged(Location location) {
        Log.e(TAG, "onLocationChanged: location=" + location.getLongitude());
        Log.e(TAG, "onLocationChanged: location=" + location.getLatitude());
        handleNewLocation(location);


        /**send broadcast to update current location when app is open*/        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction(WebServiceParams.UPDATE_LOCATION);
        broadcastIntent.putExtra(Constants.EXTRA_CURRENT_LOCATION, location);
        sendBroadcast(broadcastIntent);
    }


    private void handleNewLocation(Location location) {
        SharedPreferences.Editor editor = pref.edit();
        editor.putLong(Constants.PREF_CURRENT_LATITUDE, Double.doubleToLongBits(location.getLatitude()));
        editor.putLong(cConstants.PREF_CURRENT_LONGITUDE, Double.doubleToLongBits(location.getLongitude()));
        editor.apply();
    }


    @Nullable    @Override    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy: service destroy");
    }

   /* @Override    public void onDestroy() {        super.onDestroy();        Log.e(TAG, "onDestroy: service destroy");        if (mGoogleApiClient.isConnected()) {            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);            mGoogleApiClient.disconnect();        }    }*/

}

Comments

Popular posts from this blog

Getview Method Wierd in Listview

Its common issue in android and most of newbee faced. To understand why its happening, you have to read about behavior of Getview method of listivew, its your home work, let continue with tutorial. Below tutorial will explain that how to maintain the position of button  which is in row file using settag and gettag. main.xml ( its contain listview which will hold row data) <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="fill_parent"     android:layout_height="fill_parent"     android:descendantFocusability="blocksDescendants">  <ListView         android:id="@+id/listView"         android:layout_width="fill_parent"         android:layout_height="fill_parent"/> </LinearLayout> ...

Amazon S3 Configuration

Gradles //amazon s3 compile 'com.amazonaws:aws-android-sdk-core:2.2.+' compile 'com.amazonaws:aws-android-sdk-s3:2.2.+' Declare in manefiest file <!--AMAZON S3--> < service android :name= "com.amazonaws.mobileconnectors.s3.transferutility.TransferService" android :enabled= "true" /> AmazonUtils.java import android.content.Context; import android.net.Uri; import com.amazonaws.auth.CognitoCachingCredentialsProvider; import com.amazonaws.mobileconnectors.s3.transferutility.TransferObserver; import com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3Client; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.UUID; /* * Handles basic helper functions used throughout the app. */ public class AmazonUtil { // We only n...
Update Progress in notification: public class NetworkService extends IntentService {     public static final String FILE_PATH = "file_path";     public static final String _FILE_PATH = "_path";     public static final String PERCENT_EXTRA = "percent";     public static final String FILE_NAME_EXTRA = "FileName";     public static final String STATE_EXTRA = "state";     public static final String IS_ALBUM_UPLAODING = "IsAlbumUplaoding";     public static final String XML = "xml";     public static final String TOKEN = "token";     public static final String MESSAGE = "mesasge";     public static final String POST_DATE = "postdate";     public static final String USERID = "userid";     public static final String GROUPID = "groupid";     public static final String PATH = "path"; ...