2

I want to create a service that is running even when app is killed so I created a unbound service so that it is not bind to activity lifecycle. But everytime I kill the app by long press and swipe, the service also get killed. Can some please help me. Thanks

Service

public class MyService extends Service {

    public GCMNotificationIntentService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "Service binded");
        return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "Service unbound");
        return super.onUnbind(intent);
    }

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

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.d(TAG, "Service started");

        Thread readerThread = new Thread(new Runnable() {
            @Override
            public void run() {

                while(true) {
                    Log.d(TAG, "Thread present");
                    try {
                        // thread to sleep for 1000 milliseconds
                        Thread.sleep(3000);
                    } catch (Exception e) {
                        System.out.println(e);
                    }
                }
            }
        });
        readerThread.start();

        return super.onStartCommand(intent, flags, startId);
    }

} 

and I am calling it from activity like this

startService(new Intent(MyService.class.getName()));

The service runs fine until app is in background or foreground but when I long press and sweep the app, service also stops with crash message like this

Scheduling restart of crashed service com.net.gs.MyService in 1000ms

I/ActivityManager( 1160): Force stopping service ServiceRecord{44989bf0 u0 com.net.gs.MyService}

user3265443
  • 535
  • 1
  • 8
  • 25
  • Of course, when you kill a process, **everything** running in that process dies. Android may (or may not) then re-start some components in a new process. – Chris Stratton Mar 27 '15 at 05:11
  • I've solved the problem using: http://stackoverflow.com/questions/16651009/android-service-stops-when-app-is-closed/ – Elia12345 Feb 23 '17 at 13:05
  • Besides I added a function onDestroySubstitute() which I call from myActivity before unbinding service in the activity's onDestroy method. In onDestroySubstitute() I prepare service for following correct restart using e.g. SharedPreferences and saving there what I then need after restart. – Elia12345 Feb 23 '17 at 19:38

2 Answers2

2
// Display sticky notification using below function in notification-bar.   
private static final int NOTIFICATION_ID=1;

 private void displayNotification() {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                this).setSmallIcon(R.drawable.ic_launcher).setContentTitle(
                "Player");
        builder.setContentText("content text");

        if (getFileStructure() != null) {
            String title = Utils.filter(getFileStructure().getTitle());
            if (title.length() > 45)
                title = title.substring(0, 44);
            builder.setContentText(Utils.filter(title));
        }
        Intent resultIntent = new Intent(PlayerService.this, MainActivity.class);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(
                PlayerService.this, 0, resultIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(resultPendingIntent);
        builder.setAutoCancel(false);
        NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        nManager.notify(NOTIFICATION_ID, builder.build());
        startForeground(NOTIFICATION_ID, builder.build());
    }
  • Android kills any service if it needs memory for another task. So if you display notification in notification-bar then system assumes it as a foreground and destroy other processes. But android is not guaranteed that your service may run forever. –  Mar 27 '15 at 04:44
  • I call displayNotification() method in onStartCommand() method but again same result – user3265443 Mar 27 '15 at 04:49
  • Please add it in OnCreate of your service class. Make sure that notification is displayed in notification-bar after calling above function. –  Mar 27 '15 at 04:51
  • Sorry but same result....yes notification is getting displayed but when I kill app notification also gets hide. and service is killed and giving the same output on logcat as before – user3265443 Mar 27 '15 at 04:56
  • What is the android version and phone model are you using for testing your application. –  Mar 27 '15 at 04:57
  • I am testing it on xiomi mi3 and using kitkat version – user3265443 Mar 27 '15 at 04:58
  • Is this can be phone issue as well? Can you give me a sample app that runs on your phone – user3265443 Mar 27 '15 at 05:01
  • 1
    Can you please test it on android emulator or another device. So we can identify problem, xiomi customizes the os a lot. –  Mar 27 '15 at 05:05
0

You have done all things right except one change :

You should remove the Binding overridden methods from your code :

Remove this :

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "Service binded");
        return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "Service unbound");
        return super.onUnbind(intent);
    }

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

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

After this, your issue should solve.

When you start service call :

startService(/* intent to service*/);
Kushal
  • 8,100
  • 9
  • 63
  • 82