17

I am having issues passing a value from an Activity to an already running service. I was wondering what the best approach to take would be? Adding extras wont work as I believe this has to be done before the intent is started? (correct me if i'm wrong).

Any help would be great! I can elaborate if needed.

Dan.

Daniel Flannery
  • 1,166
  • 8
  • 23
  • 51

2 Answers2

39

If your service is not an IntentService, you can call startService(...) as many times you want. The service will run the first time but next calls will result in new onStartCommand() calls with the new extras you need.

Check this answer and the doc.

Community
  • 1
  • 1
fedepaol
  • 6,834
  • 3
  • 27
  • 34
  • 1
    Agreed, here's more proof from [`Activity#startService()`](https://developer.android.com/reference/android/content/Context.html#startService%28android.content.Intent%29)'s documentation. – Sam Mar 11 '13 at 19:19
  • Ah I see. Dont know how I missed this reading the documentation. Thanks for your swift answer! – Daniel Flannery Mar 11 '13 at 19:34
  • 1
    Also see [this answer](http://stackoverflow.com/a/15899750/1340631) which explains how to to call `startService()` to pass new Intents and read them inside your service during `onStartCommand()`. Essentially the same answer as here but a little more verbose. – scai Aug 06 '16 at 08:19
0

pass intent extra to service from activity start this intent if service is running try this from activity and pass param with putExtra.

Intent rc = new Intent(getApplicationContext(), myService.class);
rc.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //important for Android 10
rc.putExtra("parama","ciao");
rc.putExtra("paramb","hello");
startService(rc);

Remember, new thread, exit to main Thread.

new Thread(){
    @Override
        public void run() {
            super.run();
            //start service..
        }    
}

your service

 public class myService extends Service {
               @Override
                public int onStartCommand(Intent intent, int flags, int startId) {
                if (intent.hasExtra("parama")){            
                Bundle b=new Bundle();
                b=intent.getExtras();
                String par_a=b.getString("parama");
                }
                if (intent.hasExtra("paramb")){            
                Bundle b=new Bundle();
                b=intent.getExtras();
                String par_b =b.getString("paramb");
                }
        }
    }
Daniela
  • 1
  • 1