安卓:访问变量传递到服务变量

2023-09-07 22:02:26 作者:归人

我创建了一个从主要活动名为并将其传递一个简单的变量访问和烤面包屏幕从服务中的服务。我似乎无法找到合适的code,从服务中访问变量。任何帮助将大大AP preciated。谢谢你。

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服务类code:

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.

推荐答案

好吧,我发现自己的答案终于,并希望分享它来帮助别人。

Ok, found my own answer finally and want to share it to help anyone else.

答案:在onStart()或onStartCommand()(其中一个取决于目标API)是什么的意图传递给并称为startService()后由活动调用。我以为的意图传递给onCreate()方法,但它实际上是传递给start命令的服务。

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.

@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();  
}