0

---------- Esse é o meu serviço

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();
}

}

---------- esse é o meu 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>

A localização está vindo legal em primeiro plano porem em segundo plano ela para e eu gostaria que ela viece para fazer uma especie de localizador pessoal

OBS(quando estava em aplicativos separados ela trazia, porem quando juntei os app ela parou de rodar em segundo plano...

1
  • Lendo os artigos da nova versão (android 8.0) descobri que ele não ira mais atualizar a localização em tempo real pela FusedLocationApi agora que fiquei mais perdido que sego em tiroteio. Commented 23/11/2018 às 1:32

1 Resposta 1

0

Resolvi o problema! acrecentei o codigo na MainActivity para a chamada do serviço com 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));
    }

com anotação @TargetApi(26);

Desta forma o serviço não é destruido em segundo plano...

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .