Keep app running in background on Android all the time

前端 未结 3 1873
说谎
说谎 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:43

    I've read that some smartphones have these kind of problems, I found that Huawei, Xiaomi among others have problems with implementation Services, and guess what: My smartphone is a Huawei. The problem comes out of programs preinstalled on these devices for energy saving. Therefore, I tried to run my program on a Nexus (simulator for this one), a Sony and a Moto G, the program ran well for these 3 devices. Thanks for help.

    0 讨论(0)
  • 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

    <service
                android:name=".ForegroundService"
                android:enabled="true"
                android:stopWithTask="false" />
    
    0 讨论(0)
  • 2020-12-21 12:49

    As @Gudin says, it looks to me like you stop the service after 20 seconds. However, since you say this works sometimes, I'm guessing that's just some test code. I suspect your problem is in how you start the Service. Passing the Activity's context means your Service is tied to the lifecycle of that Activity. If that is destroyed, I think your Service goes with it. (Simply going through onStop() of the Activity & not onDestroy() leaves the Service intact). Try this

        Intent intent = new Intent(getApplicationContext(), MyService.class);
    

    I tried duplicating your problem but couldn't so I can't say for sure this is your problem. This is a good place to start though.

    0 讨论(0)
提交回复
热议问题