Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

android - Calling getIntent Method in service

I have to pass parameter from MyActivity.class to TestService.class. MyActivity is a Activity class and TestService is a Service that I have made for sending messages. I have to pass parameter from Activity to the Service, but when I call Intent i = getIntent(); in service class, I am getting an error getIntent() is undefined.

So, how can I send parameters from my Activity to Service?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Start your service like this;

 Intent ir=new Intent(this, Service.class); 
 ir.putExtra("data", data); 
 this.startService(ir); 

You attach your data as an intent extra.

Then to retrieve the data from the service;

data=(String) intent.getExtras().get("data"); 

So you can access your parameter from either the onHandleIntent or onStartCommand Intent parameter. (depending on which type of service you are running) For Example;

Service

protected void onStartCommand (Intent intent, int flags, int startId) {
    data=(String) intent.getExtras().get("data"); 
}

public int onStartCommand (Intent intent, int flags, int startId)

IntentService

protected void onHandleIntent(Intent intent) {
    data=(String) intent.getExtras().get("data"); 
}

protected abstract void onHandleIntent (Intent intent)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...