I wrote some code to start a service from AsyncTask
, and I can see on debug mode that the service is started.
The code for starting the service on the background on AsyncTask
is as follows,
protected String doInBackground(String... params) {
//starts service number activite
MyResultReceiver resultReceiver = new MyResultReceiver(null);
Intent intent = new Intent(context, MyService.class);
intent.putExtra("receiver", resultReceiver);
context.startService(intent);
and the serivce is:
public class MyService extends Service{
ResultReceiver resultReceiver;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//resultReceiver = intent.getParcelableExtra("receiver");
resultReceiver = intent.getParcelableExtra("receiver");
Bundle data = new Bundle();
data.putString("key",getActivityUrl() );
resultReceiver.send(2, data);
resultReceiver.send(2,null);
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public String getActivityUrl() {
String str = null;
try{
URL url = null;
try {
url = new URL("http://www.google.com");
} catch (MalformedURLException ex) {
Logger.getLogger(MyService.class.getName()).log(Level.SEVERE, null, ex);
}
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
}
//all is ok
in.close();
} catch (IOException ex) {
Logger.getLogger(MyService.class.getName()).log(Level.SEVERE, null, ex);
}finally{ stopSelf();
}
//resultReceiver.send(100,null);
return str;
}
}
Another question: How can I send a String and not only an int with resultReceiver.send
?