简体   繁体   中英

Android Service not staying alive after app closes

I want to have a background service, which will stay alive after the app is closed and which I can bind to again when the app is started.

For testing I made it that a counter will increase every time I bind to the service.


So theoretically the app should start, I will create the service, then bind to it -> the counter should move up.

Then I close the app and press the Bind button again and It should log a "1" and move the counter up again.

But it doesn't ... It will display a 0 every time I restart the app and bind to it ...


This is my current Test - Service - class:

package com.programm.testapp;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class TestService extends Service {

    /*
     * Service Binder
     */
    private final IBinder iBinder = new TestService.LocalConnectionService();

    public class LocalConnectionService extends Binder {
        public TestService getService(){
            return TestService.this;
        }
    }

    /*
     * Test var
     * It should increase every time the app is started.
     */
    private int test;

    @Override
    public IBinder onBind(Intent intent) {
        Log.d("mDEBUG", "Test: " + test);
        test++;

        return iBinder;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("mDEBUG", "Service: Start Command");

        return START_STICKY;
    }
}

This is my current Test - Activity:

package com.programm.testapp;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private TestService service;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button createButton = findViewById(R.id.button_create_service);
        createButton.setOnClickListener(this::createService);

        Button destroyButton = findViewById(R.id.button_destroy_service);
        destroyButton.setOnClickListener(this::destroyService);



        Button bindButton = findViewById(R.id.button_bind_service);
        bindButton.setOnClickListener(this::bindService);

        Button unbindButton = findViewById(R.id.button_unbind_service);
        unbindButton.setOnClickListener(this::unbindService);


    }

    private void createService(View v){
        Intent intent = new Intent(this.getBaseContext(), TestService.class);
        startService(intent);
    }

    private void destroyService(View v){
        Intent intent = new Intent(this.getBaseContext(), TestService.class);
        stopService(intent);
    }

    private void bindService(View v){
        Intent intent = new Intent(this.getBaseContext(), TestService.class);
        bindService(intent, serviceConnection, BIND_AUTO_CREATE);
    }

    private void unbindService(View v){
        unbindService(serviceConnection);
    }


    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d("mDEBUG", "Connection: on service connected");

            MainActivity.this.service = ((TestService.LocalConnectionService) service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("mDEBUG", "Connection: on service disconnected");
        }
    };
}

This is my AndroidManifest.xml - file:

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

    <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>

        <service
            android:name=".TestService"
            android:enabled="true"
            android:exported="false"></service>
    </application>
</manifest>

This is my output after I ...

  1. Pressed Create Service - Button
  2. Pressed Bind Service - Button
  3. Pressed Unbind Service - Button
  4. Close App and Restart it
  5. Pressed Bind Service - Button

:

.../com.programm.testapp D/mDEBUG: Service: Start Command
.../com.programm.testapp D/mDEBUG: Test: 0
.../com.programm.testapp D/mDEBUG: Connection: on service connected
.../com.programm.testapp D/mDEBUG: Service: Start Command
.../com.programm.testapp D/mDEBUG: Test: 0
.../com.programm.testapp D/mDEBUG: Connection: on service connected

By the way the second "Service: Start Command" is called as I CLOSE the app ... after a few new Logs I noticed, that also the Constructer and the "onCreate" method of the Service - class will be called with it.

Is this normal?


Edit:

When I only minimize the App and not close it via Activity - Menu the behavior is exactly the one I want!!!


Edit 2:

A Foreground service does the job for now ... I couldn't find any other solution for this

If you actively close the app (by closing it from the Android activity list), Android will most likely kill your service. You can see that in your apps Logcat. The only real way around that is a foreground service.

Furthermore, onBind will not be called every time you bind to the service. From the Android documentation :

You can connect multiple clients to a service simultaneously. However, the system caches the IBinder service communication channel. In other words, the system calls the service's onBind() method to generate the IBinder only when the first client binds. The system then delivers that same IBinder to all additional clients that bind to that same service, without calling onBind() again.

Secondly, just that onStartCommand is called does not mean the service is recreated. It can be called multiple times during the service life cycle. For instance, each time startService is called, onStartCommand is executed, but the service is not necessarily recreated.

Also, it looks like you do not un-bind the service when closing the activity. That makes your activity leak the ServiceConnection and your app crash. It would explain why you see the service re-created every time you close and re-start the app.

Try adding an unbind in your activity's onPause method:

@Override
void onPause() {
    super.onPause()
    unbindService(this.serviceConnectino)
}

A working configuration could look like below. It implements incrementing the counter using a dedicated service function, rather than onBind:

MyBoundService.kt

package com.test

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log

class MyBoundService : Service() {

    abstract class MyBinder: Binder() {
        abstract fun getService(): MyBoundService
    }

    val iBinder: MyBinder = object: MyBinder() {
        override fun getService(): MyBoundService {
            return this@MyBoundService
        }
    }

    private var counter = 0

    fun increment() {
        counter ++
        Log.i("MyBoundService", "Counter: ${counter}")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.i("MyBoundService", "startCommand");
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onBind(p0: Intent?): IBinder? {
        counter++
        Log.i("MyBoundService", "Bound: ${counter}")
        return iBinder
    }

    override fun onUnbind(intent: Intent?): Boolean {
        Log.i("MyBoundService", "Unbound")
        return super.onUnbind(intent)
    }
}

MainActivity.kt

package com.test

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import android.content.ComponentName
import android.content.Context
import android.content.ServiceConnection
import android.os.IBinder
import android.util.Log
import com.test.MyBoundService

class MainActivity : AppCompatActivity() {


    private val serviceConnection: ServiceConnection = object: ServiceConnection {
        override fun onServiceDisconnected(p0: ComponentName?) {
            Log.i("MainActivity", "Service disconnected")
        }

        override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
            Log.i("MainActivity", "Service connected")
            p1?.let {
                (p1 as MyBoundService.MyBinder).getService().increment()
            }
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btn_create.setOnClickListener {
            val i = Intent(this@MainActivity, MyBoundService::class.java)
            startService(i)
        }

        btn_bind.setOnClickListener {
            val i = Intent(this@MainActivity, MyBoundService::class.java)
            bindService(i, serviceConnection, Context.BIND_AUTO_CREATE)
        }
    }

    override fun onPause() {
        super.onPause()
        unbindService(serviceConnection)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM