Android 服务活动意图
我想将一个字符串从活动传递到服务。
Bundle mBundle = new Bundle();
mBundle.putString("MyString", string);
mIntent.putExtras(mBundle);
startService(mIntent);
这是在 Activity 类中
Intent myIntent = getIntent();
String value = myIntent.getExtras().getString(key);
,这是在 Service 类中 它不接受 getIntent() 方法:我不知道我会做什么
I want to pass a string from activiy to service.
Bundle mBundle = new Bundle();
mBundle.putString("MyString", string);
mIntent.putExtras(mBundle);
startService(mIntent);
this is in Activity class
Intent myIntent = getIntent();
String value = myIntent.getExtras().getString(key);
and this is in Service class
It doesn't accept getIntent() method :S I don't know what I'll do
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
服务中的代码必须放在
onStart(Intent Intent, int startid)
方法中,代码变为String value = intent.getExtras().getString(key);
The code in the service must be placed in
onStart(Intent intent, int startid)
method and the code becomesString value = intent.getExtras().getString(key);
当您使用
startService(mIntent)
启动服务时,服务的 onStartCommand 被调用,这是处理意图的好地方。When you start the service using
startService(mIntent)
the service's onStartCommand is called which is good place to handle the intent.将取决于意图的代码部分移至 onStartCommand: http://developer.android.com/reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)
OnStartCommand 在 api 版本 5 之前被称为 OnStart,请跟随链接到文档有关应用程序中向后兼容性的更多信息,
还请记住将繁重的代码移至您在 onStartCommand 中启动的后台线程中,否则您将遇到应用程序无响应错误。
Move the part of your code that depends on the intent to onStartCommand: http://developer.android.com/reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)
OnStartCommand was called OnStart before api version 5, follow link to documentation for further information about backwards compatibility in your app.
Also remember to move heavy code into a background thread that you start in onStartCommand, as otherwise you will run into an Application Not Responding error.