stefan-0905
stefan-0905

Reputation: 17

Make network request after user kills an application

How can I make a network request after a user swipes an app from recent? Looks like android doesn't allow network access after the application process is killed. Is there a way to still make this happen?

I would like to manage user online status where application start makes him online and when the application is completely killed he goes offline. This is done by sending requests to my API.

Upvotes: 0

Views: 1006

Answers (2)

Praveen Kumar
Praveen Kumar

Reputation: 277

It's pretty Simple. You can write an Android service component which overrides a method called onTaskRemoved() which will be triggered whenever app is removed by swiping from recants. So you can try this solution and see it fulfills your requirement. This will solve your problem defiantly.

Upvotes: 1

Ismail ackerboy
Ismail ackerboy

Reputation: 53

You could create a service that listens to the Application destroying

class MyService: Service() {


        override onBind(intent:Intent):IBinder {
            return null
        }

        override onStartCommand(intent:Intent, flags:Int, startId:Int):Int {
            return START_NOT_STICKY
        }

        override onDestroy() {
            super.onDestroy()
        }

        override onTaskRemoved(rootIntent:Intent) {
            // this will be called when Your when the application is destroyed or killed
            // launch your Network request here
        }
}

And define this service in the manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    ...>

    ...

    <application
        android:name=".MyApplication">
        ...
        <service android:name=".MyService" android:stopWithTask="false"/>

    </application>
</manifest>

then launch it in your Application

class MyApplication: Application{

        override onCreate(){
            super.onCreate()
            val intent = Intent(this, MyService::java.class)
            startService(intent)
        }
}

check this thread.

Upvotes: 0

Related Questions