Use same service multiple times

2019-08-30 09:45发布

I'm about to be finished with my app, and noticed a "bug". Because if the user press the button that starts a service, and then press another button that also starts the service but with other information, the service will just be restarted and the first start is simply gone. They can't mean that I'm supposed to write like 1 million service classes with same code but other name? So each button start each service, I hope not at least.

So, is there someway to re-use the same service and have multiple services, in the service? I think it was a bad explanation but I hope at least somebody gets what I mean and want to help me :)

Thanks!

2条回答
女痞
2楼-- · 2019-08-30 10:23

Not sure what you mean by different services, but if you are just passing different information based on a button click you could pass information through extras. On the class you have buttons you would put something similar to this on each button click.

    Intent i = new Intent(FirstActivity.this, SecondActivity.class);   
    String values = "something";
    i.putExtra("EXTRASNAME", values);

Then to receive the values in the following class

    Bundle extras = getIntent().getExtras();
    String values = extras.getString("EXTRASNAME");

If the different buttons are values such as (YES OR NO) you put the value "YES" or the value "NO" in the same extras string and when receiving the value in the next activity you can do a simply if{} statement to have the activity do different things depending on extras value. With extras you can also do putBoolean/getBoolean and putInt/getInt. Hope this helps.

查看更多
虎瘦雄心在
3楼-- · 2019-08-30 10:26

The solution, as discussed in the chat:

http://chat.stackoverflow.com/rooms/23522/discussion-between-alex-oliveira-and-guiceu

The problem is that you are calling startService everytime. The solution is to change the call to bindService, so the Service is not restarted.

The Service will run until there are no more Context's bound to it. If you bind just an Activity, the Service can be stopped when the Activity is gone. If you need it to run continuously while your application is up, try calling from the application context.

查看更多
登录 后发表回答