0

I want to create a android app to track real time location with a android service. But when i kill the app from recent app list, Service also killed in android 6 (Huawei y3 2017). But same code works on android 8. Please help me to solve my problem. Please find below is my code.

I added START_STICKY and START_REDELIVER_INTENT flags in onStartCommand method.

I have tried to restart the service in onTaskRemoved method.

Tried to add android:process attribute to

Manifest.xml

<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="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    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>
    <activity android:name=".Login" />
    <activity android:name=".Home" />

    <service
        android:name=".TrackingService"
        android:enabled="true"
        android:exported="true" />
</application>

This is how start my service in Home activity

Intent intent = new Intent(Home.this, TrackingService.class);
startService(intent);

TrackingService.java service file

@Override
public void onCreate(){
    buildNotification();

    requestLocationUpdates();

    Toast.makeText(getBaseContext(), "Service Started", Toast.LENGTH_SHORT).show();

    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId){
   return START_STICKY;
}

private void buildNotification() {
    Random random = new Random();
    int m = random.nextInt(9999 - 1000) + 1000;

    String stop = "stop";
    registerReceiver(stopReceiver, new IntentFilter(stop));
    PendingIntent broadcastIntent = PendingIntent.getBroadcast(this, 0, new Intent(stop), PendingIntent.FLAG_UPDATE_CURRENT);

    Notification.Builder builder = new Notification.Builder(this)
            .setContentTitle(getString(R.string.app_name))
            .setContentText(getString(R.string.tracking_enabled_notif))
            .setOngoing(true)
            .setContentIntent(broadcastIntent);

    startForeground(m, builder.build());
}

protected BroadcastReceiver stopReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
          unregisterReceiver(stopReceiver);

          stopSelf();
    }
};

private void requestLocationUpdates() {
    LocationRequest request = new LocationRequest();

    request.setInterval(15000);

    request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    FusedLocationProviderClient client = LocationServices.getFusedLocationProviderClient(this);

    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

    final DatabaseReference ref = FirebaseDatabase.getInstance().getReference("connected/"+user.getUid());

    int permission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);

    if (permission == PackageManager.PERMISSION_GRANTED) {
        client.requestLocationUpdates(request, new LocationCallback() {

        @Override
            public void onLocationResult(LocationResult locationResult) {
                android.location.Location location = 
                locationResult.getLastLocation();

                String lat = Double.toString(location.getLatitude());
                String lng = Double.toString(location.getLongitude());

                Toast.makeText(getBaseContext(), "Lat "+lat, Toast.LENGTH_SHORT).show();

                if (location != null) {
                    ref.setValue(locationObj);
                }
               enter code here}
            }, null);
        }
    }
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Mobile Dev
  • 49
  • 1
  • 9
  • Relate to me https://stackoverflow.com/questions/54399485/is-there-any-way-to-run-service-continuously-in-android – Manohar Jan 31 '19 at 09:33

2 Answers2

1

The fact your service isn't getting killed on Android 8 sounds like a matter of luck. Probably your Android 8 phone has enough resources and keeps the service alive, but it will be killed sooner or later.

To achieve your goal you need to run your service in foreground. Check out official documentation:

You should only use a foreground service when your app needs to perform a task that is noticeable by the user even when they're not directly interacting with the app. For this reason, foreground services must show a status bar notification with a priority of PRIORITY_LOW or higher, which helps ensure that the user is aware of what your app is doing. If the action is of low enough importance that you want to use a minimum-priority notification, you probably shouldn't be using a service; instead, consider using a scheduled job.

Every app that runs a service places an additional load on the system, consuming system resources. If an app tries to hide its services by using a low-priority notification, this can impair the performance of the app the user is actively interacting with. For this reason, if an app tries to run a service with a minimum-priority notification, the system calls out the app's behavior in the notification drawer's bottom section.

Community
  • 1
  • 1
-1

Try to register your broadcast receiver in your main activity along with the intent actions that you want your receiver to do like this

private void RegisteringBroadcastReciever()
{
   broadcastReceiver = new XYZIntentReceiver();
   var filter = new IntentFilter();
   filter.AddAction("hearing.arc.intent.action.action1");
   filter.AddAction("hearing.arc.intent.action.action2");
   filter.AddAction("hearing.arc.intent.action.action3");
   filter.AddAction("hearing.arc.intent.action.action4");           
   AppInstance.ApplicationContext.RegisterReceiver(broadcastReceiver, filter);
} 

Even i had a similar kind of issue. But i had that issue on Oreo devices as well. But this fix has resolved my issue. And Android asks to unregister this receiver in onDestroy() method. But don't do that. It might kill the service again.

Hope this helps.