Android: Access Variables passed to service

给你一囗甜甜゛ 提交于 2019-12-08 20:56:24

问题


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.


回答1:


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.

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



回答2:


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:

 @Override
public void onCreate() {
    super.onCreate();

    Bundle extras = getIntent().getExtras();
    string extraData = extras.getString("extraData");

}


来源:https://stackoverflow.com/questions/5252598/android-access-variables-passed-to-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!