Background location android studio

0

---------- This is my service

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

private static final String TAG = LocationMonitoringService.class.getSimpleName();
GoogleApiClient mLocationClient;
LocationRequest mLocationRequest = new LocationRequest();


public static final String ACTION_LOCATION_BROADCAST = LocationMonitoringService.class.getName() + "LocationBroadcast";
public static final String EXTRA_LATITUDE = "extra_latitude";
public static final String EXTRA_LONGITUDE = "extra_longitude";

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    mLocationClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    mLocationRequest.setInterval(Constants.LOCATION_INTERVAL);
    mLocationRequest.setFastestInterval(Constants.FASTEST_LOCATION_INTERVAL);


    int priority = LocationRequest.PRIORITY_HIGH_ACCURACY; //by default
    //PRIORITY_BALANCED_POWER_ACCURACY, PRIORITY_LOW_POWER, PRIORITY_NO_POWER are the other priority modes


    mLocationRequest.setPriority(priority);
    mLocationClient.connect();

    //Make it stick to the notification panel so it is less prone to get cancelled by the Operating System.
    return START_STICKY;
}

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

/*
 * LOCATION CALLBACKS
 */
@Override
public void onConnected(Bundle dataBundle) {
    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.

        Log.d(TAG, "== Error On onConnected() Permission not granted");
        //Permission not granted by user so cancel the further execution.

        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest, this);

    Log.d(TAG, "Connected to Google API");
}

/*
 * Called by Location Services if the connection to the
 * location client drops because of an error.
 */
@Override
public void onConnectionSuspended(int i) {
    Log.d(TAG, "Connection suspended");
}

//to get the location change
@Override
public void onLocationChanged(Location location) {
    Log.d(TAG, "Location changed");


    if (location != null) {
        Log.d(TAG, "== location != null");

        //Send result to activities
        sendMessageToUI(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));

    }
}

private void sendMessageToUI(String lat, String lng) {

    Log.d(TAG, "Sending info... latitude: "+ lat + " | longitude: " + lng);

    Intent intent = new Intent(ACTION_LOCATION_BROADCAST);
    intent.putExtra(EXTRA_LATITUDE, lat);
    intent.putExtra(EXTRA_LONGITUDE, lng);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.d(TAG, "Failed to connect to Google API");

}
@Override
public void onDestroy() {
    //Stop location sharing service to app server.........

    stopService(new Intent(this, LocationMonitoringService.class));
    Log.d(TAG, "OnDestroy");
    //Ends................................................
    super.onDestroy();
}

}

---------- this is my manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="sysystem.panictrackermap">

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="com.something.app.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.something.app.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.CALL_PHONE" />

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_maps"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_maps"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <receiver android:name=".services.ServiceLocationStarter">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
    <service android:name=".services.LocationMonitoringService" />

    <receiver android:name=".services.BootCompletedIntentReceiver">
        <intent-filter android:priority="2147483647">
            <action android:name="android.intent.action.MEDIA_BUTTON" />
            <action android:name="android.intent.action.CAMERA_BUTTON" />
            <action android:name="android.intent.action.CALL_BUTTON" />
        </intent-filter>
    </receiver>
    <service android:name=".firebase.CDCMessasingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    <service android:name=".firebase.CDCInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>

The location is coming cool in the foreground but in the background it stops and I would like it to come to make a kind of personal locator

    
asked by anonymous 21.11.2018 / 23:53

1 answer

0

I solved the problem! I added the code in the MainActivity for the service call with api 26 android O (OREO)

 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){

        MainActivity.this.startForegroundService(new Intent(this, LocationMonitoringService.class));
    }else{
        startService(new Intent(getBaseContext(), LocationMonitoringService.class));
    }

with annotation @TargetApi (26);

This way the service is not destroyed in the background ...

    
23.11.2018 / 03:36