0

I have this issue: I have a main activity that is bound to a service, Also, that main activity can call a class (AsyncTask) that is a client that connects to a server and waits for data.

I tried to make the bind from class (AsyncTask) client to the service, but I don't know if that's possible or do I have to return data to the main activity so main activity can send it to the service?

I can do this in the main class

Intent intent = new Intent(getApplication(), ChatHeadService.class);
startService(intent);
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);

but how can I implement it in the class (AsyncTask) client?

tseres
  • 37
  • 7

2 Answers2

0

You can return the data from your async task to the main activity this way.

protected void onProgressUpdate(Integer... progress) {
    setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
    showDialog("Downloaded " + result + " bytes");
}

Then you can pass that data from activity to service by calling startService(...) and passing data in an intent.

Calling startService(...) multiple times is safe and will not start multiple instances.

P.S. Running a server in Android doesn't sound right to me. Android devices should only be used as clients.

priyank
  • 2,651
  • 4
  • 24
  • 36
  • maybe what im trying to do is not possible with asinc task, because only onpostexecute can return what is done in do in background. And i want to call a service in background and manipulate it without having to close the async task to get the the value passed from the server – tseres Jul 13 '17 at 19:15
  • What you're trying to do can be achieved with service – priyank Jul 13 '17 at 23:03
  • i added the service and it works but i got an error trying to move the image : Only the original thread that created a view hierarchy can touch its views. – tseres Jul 14 '17 at 14:38
  • @tseres You should not modify views in a service. Talk back to the activity from your service and let it manage the views. – priyank Jul 14 '17 at 19:16
  • ok got it main activity is the one that should handle it. thanks for the help :) – tseres Jul 14 '17 at 19:27
0

I think that you can just invoke the service from doInBackground() like you can in the activity. See this Stack Overflow post for a solution to a similar problem.

Cheticamp
  • 61,413
  • 10
  • 78
  • 131
  • im trying to follow that example Intent serviceIntent = new Intent(); serviceIntent.setAction("services.conServise"); Context context = getApplication(); context.startService(serviceIntent); but context is not recognized maybe think i need the main class so i can work – tseres Jul 13 '17 at 19:23
  • @tseres `MainActivity.class`? – Cheticamp Jul 13 '17 at 19:36
  • @tseres I believe what they are doing is passing the context in via the constructor for AsyncTask. As an aside, if you do this, you will need to be aware of [these issues](https://stackoverflow.com/a/3821998/6287910). – Cheticamp Jul 13 '17 at 21:29