How to send string data from Activity to started Service onclick method?

huangapple go评论116阅读模式
英文:

How to send string data from Activity to started Service onclick method?

问题

以下是您要翻译的内容:

我有一个活动和一个服务。应用程序上有三个按钮。其中一个是“开始”按钮,用于启动服务;另一个是“测试”按钮,用于发送“Test”字符串到服务;最后一个是“停止”按钮,用于停止服务。

我可以正常启动和停止服务,但是当我尝试发送字符串时,我尝试了Intent,但是找不到任何方法来实现这一点。我还尝试了onStartCommand(),但是这个方法也无法触发。

您有什么建议吗?

这是我的活动部分:

  1. override fun onCreate(savedInstanceState: Bundle?) {
  2. super.onCreate(savedInstanceState)
  3. setContentView(R.layout.activity_main)
  4. serviceIntent = Intent(applicationContext, MyService::class.java)
  5. }
  6. fun sendLogin(view: View){
  7. startService(serviceIntent)
  8. if (isMyServiceRunning(MyService::class.java)){
  9. Toast.makeText(applicationContext, "Service Started", Toast.LENGTH_SHORT).show()
  10. }
  11. }
  12. fun sendTest(view: View){ //尝试发送“TEST”
  13. val intent = Intent(this, MyService::class.java)
  14. val msj = "TEST"
  15. intent.putExtra("key", msj)
  16. applicationContext.startService(intent)
  17. }
  18. fun sendLogout(view: View){ //停止服务
  19. stopService(serviceIntent)
  20. if (!isMyServiceRunning(MyService::class.java)){
  21. Toast.makeText(applicationContext, "Service Stopped", Toast.LENGTH_SHORT).show()
  22. }
  23. }
  24. private fun isMyServiceRunning(serviceClass: Class<*>): Boolean { //检查应用程序是否已启动
  25. val manager = getSystemService(ACTIVITY_SERVICE) as ActivityManager
  26. for (service in manager.getRunningServices(Int.MAX_VALUE)) {
  27. if (serviceClass.name == service.service.className) {
  28. return true
  29. }
  30. }
  31. return false
  32. }

这是我的服务部分:

  1. private inner class MessageRequestHandler() : Handler() {
  2. override fun handleMessage(msg: Message) {
  3. when (msg.what) {
  4. SEND_MESSAGE_FLAG -> {
  5. val bundle = Bundle()
  6. bundle.putString("key", stringMessage)
  7. val mesg = Message.obtain(null, SEND_MESSAGE_FLAG)
  8. mesg.obj = bundle
  9. try {
  10. msg.replyTo.send(mesg)
  11. } catch (e: RemoteException) {
  12. Log.i(TAG, "Error: " + e.message)
  13. }
  14. }
  15. }
  16. super.handleMessage(msg)
  17. }
  18. }
  19. override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { //无法触发此方法...
  20. stringMessage = intent?.extras?.getString("key").toString()
  21. return super.onStartCommand(intent, flags, startId)
  22. }
  23. private val messageMessenger: Messenger = Messenger(MessageRequestHandler())
  24. override fun onBind(intent: Intent?): IBinder {
  25. return messageMessenger.binder
  26. }

谢谢。

英文:

I have one activity and service. I have three button on app. One of is Start to start Service the other is Test to send Service "Test" string the other is Stop to stop service.

I can start and stop service without any problem but when i try to send string i tried Intent but cannot find any way for this. I also tried onStartCommand() but cannot fire that method too..

What you can suggest?

Here my Activity

  1. override fun onCreate(savedInstanceState: Bundle?) {
  2. super.onCreate(savedInstanceState)
  3. setContentView(R.layout.activity_main)
  4. serviceIntent = Intent(applicationContext, MyService::class.java)
  5. }
  6. fun sendLogin(view: View){
  7. startService(serviceIntent)
  8. if (isMyServiceRunning(MyService::class.java)){
  9. Toast.makeText(applicationContext, &quot;Service Started&quot;, Toast.LENGTH_SHORT).show()
  10. }
  11. }
  12. fun sendTest(view: View){ //TRY TO SEND &quot;TEST&quot;
  13. val intent = Intent(this, MyService::class.java)
  14. val msj = &quot;TEST&quot;
  15. intent.putExtra(&quot;key&quot;, msj)
  16. applicationContext.startService(intent);
  17. }
  18. fun sendLogout(view: View){ //Stop service
  19. stopService(serviceIntent)
  20. if (!isMyServiceRunning(MyService::class.java)){
  21. Toast.makeText(applicationContext, &quot;Service Stopped&quot;, Toast.LENGTH_SHORT).show()
  22. }
  23. }
  24. private fun isMyServiceRunning(serviceClass: Class&lt;*&gt;): Boolean { //Checking app is started or not
  25. val manager = getSystemService(ACTIVITY_SERVICE) as ActivityManager
  26. for (service in manager.getRunningServices(Int.MAX_VALUE)) {
  27. if (serviceClass.name == service.service.className) {
  28. return true
  29. }
  30. }
  31. return false
  32. }

Here my service

  1. private inner class MessageRequestHandler() : Handler() {
  2. override fun handleMessage(msg: Message) {
  3. when (msg.what) {
  4. SEND_MESSAGE_FLAG -&gt; {
  5. val bundle = Bundle()
  6. bundle.putString(&quot;key&quot;, stringMessage)
  7. val mesg = Message.obtain(null, SEND_MESSAGE_FLAG)
  8. mesg.obj = bundle
  9. try {
  10. msg.replyTo.send(mesg)
  11. } catch (e: RemoteException) {
  12. Log.i(TAG, &quot;Error: &quot; + e.message)
  13. }
  14. }
  15. }
  16. super.handleMessage(msg)
  17. }
  18. }
  19. override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { //Cannot fire this...
  20. stringMessage = intent?.extras?.getString(&quot;key&quot;).toString()
  21. return super.onStartCommand(intent, flags, startId)
  22. }
  23. private val messageMessenger: Messenger = Messenger(MessageRequestHandler())
  24. override fun onBind(intent: Intent?): IBinder {
  25. return messageMessenger.binder
  26. }

Thanks

答案1

得分: 1

请检查,使用EventBus进行消息传递非常简单。以下是您的解决方案:

  1. //定义事件类
  2. class MessageEvent(val someString: String)
  3. //主活动
  4. class MainActivity : AppCompatActivity() {
  5. private lateinit var serviceIntent: Intent
  6. override fun onCreate(savedInstanceState: Bundle?) {
  7. super.onCreate(savedInstanceState)
  8. setContentView(R.layout.activity_main)
  9. serviceIntent = Intent(applicationContext, MessageService::class.java)
  10. }
  11. fun sendLogin(view: View) {
  12. startService(serviceIntent)
  13. if (isMyServiceRunning(MessageService::class.java)) {
  14. Toast.makeText(applicationContext, "Service Started", Toast.LENGTH_SHORT).show()
  15. }
  16. }
  17. fun sendTest(view: View) {
  18. //发布事件
  19. EventBus.getDefault().post(MessageEvent("TEST"))
  20. }
  21. fun sendLogout(view: View) {
  22. stopService(serviceIntent)
  23. if (!isMyServiceRunning(MessageService::class.java)) {
  24. Toast.makeText(applicationContext, "Service Stopped", Toast.LENGTH_SHORT).show()
  25. }
  26. }
  27. private fun isMyServiceRunning(serviceClass: Class<*>): Boolean {
  28. val manager = getSystemService(ACTIVITY_SERVICE) as ActivityManager
  29. for (service in manager.getRunningServices(Int.MAX_VALUE)) {
  30. if (serviceClass.name == service.service.className) {
  31. return true
  32. }
  33. }
  34. return false
  35. }
  36. }
  37. //服务类
  38. class MessageService : Service() {
  39. private val TAG: String? = "InService"
  40. private inner class MessageRequestHandler() : Handler() {
  41. override fun handleMessage(msg: Message) {
  42. super.handleMessage(msg)
  43. }
  44. }
  45. @Subscribe(threadMode = ThreadMode.MAIN)
  46. fun onMessageEvent(event: MessageEvent?) {
  47. Log.i(TAG, "onMessageEvent: " + event?.someString)
  48. }
  49. override fun onStart(intent: Intent?, startId: Int) {
  50. super.onStart(intent, startId)
  51. //订阅EventBus
  52. EventBus.getDefault().register(this);
  53. }
  54. override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
  55. return super.onStartCommand(intent, flags, startId)
  56. }
  57. private val messageMessenger: Messenger = Messenger(MessageRequestHandler())
  58. override fun onBind(intent: Intent?): IBinder {
  59. return messageMessenger.binder
  60. }
  61. override fun onDestroy() {
  62. super.onDestroy()
  63. //取消订阅EventBus
  64. EventBus.getDefault().unregister(this);
  65. }
  66. }
英文:

Please check, message passing is easy using EventBus. Here's your solution:

  1. //Define Event Class
  2. class MessageEvent(val someString: String)

Main Activity

  1. class MainActivity : AppCompatActivity() {
  2. private lateinit var serviceIntent: Intent
  3. override fun onCreate(savedInstanceState: Bundle?) {
  4. super.onCreate(savedInstanceState)
  5. setContentView(R.layout.activity_main)
  6. serviceIntent = Intent(applicationContext, MessageService::class.java)
  7. }
  8. fun sendLogin(view: View){
  9. startService(serviceIntent)
  10. if (isMyServiceRunning(MessageService::class.java)){
  11. Toast.makeText(applicationContext, &quot;Service Started&quot;, Toast.LENGTH_SHORT).show()
  12. }
  13. }
  14. fun sendTest(view: View){
  15. //Post Events
  16. EventBus.getDefault().post(MessageEvent(&quot;TEST&quot;))
  17. }
  18. fun sendLogout(view: View){
  19. stopService(serviceIntent)
  20. if (!isMyServiceRunning(MessageService::class.java)){
  21. Toast.makeText(applicationContext, &quot;Service Stopped&quot;, Toast.LENGTH_SHORT).show()
  22. }
  23. }
  24. private fun isMyServiceRunning(serviceClass: Class&lt;*&gt;): Boolean {
  25. val manager = getSystemService(ACTIVITY_SERVICE) as ActivityManager
  26. for (service in manager.getRunningServices(Int.MAX_VALUE)) {
  27. if (serviceClass.name == service.service.className) {
  28. return true
  29. }
  30. }
  31. return false
  32. }
  33. }

And Service class

  1. class MessageService : Service() {
  2. private val TAG: String? = &quot;InService&quot;
  3. private inner class MessageRequestHandler() : Handler() {
  4. override fun handleMessage(msg: Message) {
  5. super.handleMessage(msg)
  6. }
  7. }
  8. @Subscribe(threadMode = ThreadMode.MAIN)
  9. fun onMessageEvent(event: MessageEvent?) {
  10. Log.i(TAG, &quot;onMessageEvent: &quot; + event?.someString)
  11. }
  12. override fun onStart(intent: Intent?, startId: Int) {
  13. super.onStart(intent, startId)
  14. //subscribe to EventBus
  15. EventBus.getDefault().register(this);
  16. }
  17. override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
  18. return super.onStartCommand(intent, flags, startId)
  19. }
  20. private val messageMessenger: Messenger = Messenger(MessageRequestHandler())
  21. override fun onBind(intent: Intent?): IBinder {
  22. return messageMessenger.binder
  23. }
  24. override fun onDestroy() {
  25. super.onDestroy()
  26. //Unsubscribe to EventBus
  27. EventBus.getDefault().unregister(this);
  28. }
  29. }

huangapple
  • 本文由 发表于 2020年10月26日 03:59:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/64528168.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定