我已经创建了一个从主活动调用的服务,并传递一个简单的变量来访问服务内部并向屏幕干杯.我似乎无法找到从服务内部访问变量的正确代码.任何帮助将不胜感激.谢谢.
从按钮单击侦听器内部调用服务的主Activity:
@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(); } }
再次感谢任何和所有的帮助.我似乎无法找到一个简单的例子,告诉我如何做到这一点.谢谢.
解决方法
好的,最后找到了我自己的答案,并想分享它以帮助其他人.
答案: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(); }