微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Android:访问变量传递给服务

我已经创建了一个从主活动调用的服务,并传递一个简单的变量来访问服务内部并向屏幕干杯.我似乎无法找到从服务内部访问变量的正确代码.任何帮助将不胜感激.谢谢.

从按钮单击侦听器内部调用服务的主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();  
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐