Android:访问传递给服务的变量
我创建了一个从主活动调用的服务,并向其传递一个简单的变量,以便从服务内部访问屏幕并祝酒。我似乎找不到正确的代码来从服务内部访问变量。任何帮助将不胜感激。谢谢。
从按钮单击侦听器内部调用服务的主活动:
@Override
public void onClick(View v) {
Intent eSendIntent = new Intent(getApplicationContext(), eSendService.class);
eSendIntent.putExtra("extraData", "somedata");
startService(eSendIntent);
}
eSendService 服务类代码:
public class eSendService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
// This is the code that I am struggling with. Not sure how to access the
// variable that was set in the intent. Please advise.
// The below code gives the following error in eclipse:
// The method getIntent() is undefined for the type eSendService
Bundle extras = getIntent().getExtras();
}
}
再次感谢您的所有帮助。我似乎找不到一个简单的例子来展示如何做到这一点。谢谢。
I have created a service that is called from the main activity and passing it a simple variable to access and toast to the screen from inside the service. I can't seem to find the right code to access the variable from inside the service. Any help would be greatly appreciated. Thanks.
Main Activity calling the service from inside a button click listener:
@Override
public void onClick(View v) {
Intent eSendIntent = new Intent(getApplicationContext(), eSendService.class);
eSendIntent.putExtra("extraData", "somedata");
startService(eSendIntent);
}
eSendService service class code:
public class eSendService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
// This is the code that I am struggling with. Not sure how to access the
// variable that was set in the intent. Please advise.
// The below code gives the following error in eclipse:
// The method getIntent() is undefined for the type eSendService
Bundle extras = getIntent().getExtras();
}
}
Again, thanks for any and all help. I just can't seem to find a simple example out there that shows me how to do this. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,终于找到了我自己的答案,并想分享它以帮助其他人。
答案:onStart() 或 onStartCommand()(哪一个取决于目标 api)是 Activity 调用 startService() 之后意图传递和调用的内容。我以为意图已传递给 onCreate() 方法,但实际上它传递给了服务的启动命令。
Ok, found my own answer finally and want to share it to help anyone else.
The answer: onStart() or onStartCommand() (which one depends on target api) are what the intent is passed to and called after startService() is called by the activity. I thought the intent was passed to the onCreate() method but it is actually passed to the start command for services.
您的原始代码给您带来了什么问题?您试图在调用 super.onCreate() 之前获取数据,这可能是问题所在。
我想你想要:
What problem was your original code giving you? You were trying to get the data before calling super.onCreate(), that might be the problem.
I think you want: