
从按钮单击侦听器内部调用服务的主Activity:
@OverrIDepublic 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(); }} 再次感谢任何和所有的帮助.我似乎无法找到一个简单的例子,告诉我如何做到这一点.谢谢.
解决方法 好的,最后找到了我自己的答案,并想分享它以帮助其他人.答案:onStart()或onStartCommand()(一个依赖于目标API)是在活动调用startService()之后传递和调用的意图.我认为意图传递给onCreate()方法,但它实际上传递给了服务的start命令.
@OverrIDe public voID onStart(Intent intent,int startID) { // Todo auto-generated method stub super.onStart(intent,startID); String extras; extras = intent.getExtras().getString("exTradata"); Toast.makeText(this,extras,Toast.LENGTH_LONG).show(); } 总结 以上是内存溢出为你收集整理的Android:访问变量传递给服务全部内容,希望文章能够帮你解决Android:访问变量传递给服务所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)