3

I'm learning Android programming by creating an android app. But whenever I kill the application service also gets killed. I'm using JobIntentService. To make that app work in the background.

JobIntentService Class

public class BackGroundDistanceCalculate extends JobIntentService {

    final public static String TAG = "BackGroundDistance";

    static void enqueueWork(Context context, Intent job) {
        enqueueWork(context, BackGroundDistanceCalculate.class, 1, job);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "Service Start");
    }

    @Override
    protected void onHandleWork(@NonNull Intent intent) {
        Log.d(TAG, "Execution Started");

        int i=0;

        for(i=0; i<1000; i++) {
            SystemClock.sleep(1000);
        }
    }

    @Override
    public boolean onStopCurrentWork() {
        Log.d(TAG,"Now It's Stopped");
        return super.onStopCurrentWork();
    }

    @Override
    public void onDestroy() {
        Log.d(TAG,"Now It's Destroyed");
        super.onDestroy();
    }
}

MainActivity

Intent backCheck = new Intent(MapsActivity.this, BackGroundDistanceCalculate.class);
BackGroundDistanceCalculate.enqueueWork(this, backCheck);

Created this intent to start Activity in onCreateMethod

Manifest

<uses-permission android:name="android.permission.WAKE_LOCK"/>
<service
    android:name=".BackGroundDistanceCalculate"
    android:permission="android.permission.BIND_JOB_SERVICE" />

What are the changes that I can make to make service run successfully even when the app is killed? Thanks in advance.

Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
Creator
  • 303
  • 4
  • 23

2 Answers2

1

well you need to migrate your service to foreground service or at-least show an ongoing notification because starting from android 8.0 onward apps cannot run background service without letting user know .Still if you want to go without notification one way is to migrate your service to Accessibility service Create accessibility service . You can refer to this link if you want to make one .

Kishan Thakkar
  • 429
  • 4
  • 11
0

Start foreground service with non dismissable notification

Ashok Kumar
  • 1,226
  • 1
  • 10
  • 14
  • Read about changes to background service android 8 & onwards https://developer.android.com/about/versions/oreo/android-8.0-changes – Ashok Kumar Jul 08 '19 at 02:17