0

I pass value to the service like this

MyService.user = new ChatUser(task.getResult().getUser().getUid(),task.getResult().getUser().getDisplayName(), task.getResult().getUser().getEmail(), password, true, "");
                        Intent intent = new Intent(Login.this, MyService.class);
                        startService(intent);

When destroying the application the service keeps running with flag START_REDELIVER_INTENT but the user that I passed it becomes null

How to keeps the value from returning to null

Mehdi Glida
  • 547
  • 2
  • 5
  • 11
  • don't store it in a static field – Tim Jan 17 '17 at 19:10
  • `I pass value to the service like this` - you don't pass anything to your service. – Mark Jan 17 '17 at 19:42
  • @TimCastelijns if i dont store in static i cant pass it – Mehdi Glida Jan 17 '17 at 19:56
  • @MarkKeen i do like this `MyService.user = new ChatUser(task.getResult().getUser().getUid(),task.getResult().getUser().getDisplayName(), task.getResult().getUser().getEmail(), password, true, "");` before I call startservice() – Mehdi Glida Jan 17 '17 at 19:57
  • You're creating a `static class variable` and as such belongs to the class, not the instance of the `service`. you need to 1) make sure your `ChatUser` class implements `Parcelable` interface 2) create a local `ChatUser` object in your `Activity` 3) create a `Bundle` add your `ChatUser` object as a `parcelable` object (including a key) 4) add the bundle to the intent then start your service - You can then retrieve the bundle in the service. http://stackoverflow.com/a/27309167/4252352 – Mark Jan 17 '17 at 20:15
  • Possible duplicate of [How to send an object from one Android Activity to another using Intents?](http://stackoverflow.com/questions/2139134/how-to-send-an-object-from-one-android-activity-to-another-using-intents) – Mark Jan 17 '17 at 20:16

1 Answers1

1

You instantiating wrong the service. The right steps are:

  1. Create an intent and add the required values to it, like this:

    Intent intent = new Intent(this, Service.class);
        intent.putExtra("uid_key", task
                .getResult()
                .getUser()
                .getUid());
        intent.putExtra("display_name_key", task
                .getResult()
                .getUser()
                .getDisplayName()));
        startService(intent);
    
  2. In the your service:

    .
    .
    .
    
    ChatUser myChatUser;
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent.getExtras() != null){
            String uid = intent.getStringExtra("uid_key");
            String displayName = intent.getStringExtra("display_name_key");
    
            if (uid !=null && displayName != null){
                myChatUser = new ChatUser(uid, displayName);
            }
        }
    
    
        return START_REDELIVER_INTENT;
    }
    }
    
Artyom Okun
  • 939
  • 1
  • 8
  • 14