Keep app running in background on Android all the time

前端 未结 3 1953
说谎
说谎 2020-12-21 12:06

I have to get people\'s trajectory (from home to job, for example), so my app gets latitude and longitude (I have two buttons: 1. Start to get lat and lon 2. Stop to get la

3条回答
  •  北海茫月
    2020-12-21 12:49

    Try our this

    public class ForegroundService extends Service {
        private static final String LOG_TAG = "ForegroundService";
    
        @Override
        public void onCreate() {
            super.onCreate();
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
    
            // Your logical code here
    
            return START_STICKY;
        }
    
        @Override
        public void onTaskRemoved(Intent rootIntent) {
    
            //When remove app from background then start it again
            startService(new Intent(this, ForegroundService.class));
    
            super.onTaskRemoved(rootIntent);
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            Log.i(LOG_TAG, "In onDestroy");
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            // Used only in case of bound services.
            return null;
        }
    }
    

    On Start button click:

    Intent startIntent = new Intent(MainActivity.this, ForegroundService.class);
        startService(startIntent);
    

    In Manifest

    
    

提交回复
热议问题