I have an application with many activities, and “behind” the application I want a server socket always running, listening and serving data on request.
So I’ve created a service, but maybe I’m not understanding how it works because I’m having some problems. Let’s see my service:
public class MyService extends Service {
private static final String TAG = "MyService";
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d("STATUS", "onCreate service");
try {
// create socket
ServerSocket servsock;
servsock = new ServerSocket(50000);
Log.v("STATUS","SERVER SOCKET CREATED at="+50000);
while (true) {
Log.v("status","Waiting...");
Socket sc = servsock.accept();
Log.v("status","Accepted connection : " + sc);
ObjectOutputStream os = new ObjectOutputStream(sc.getOutputStream());
ObjectInputStream is = new ObjectInputStream(sc.getInputStream());
.........
sc.close();
}
.............
In my app the first screen appearing it’s a login screen, and I want the service to start imediatelly after the login (on creation of the “logged in” activity)
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.mainActivity);
startService(new Intent(this, MyService.class));
........
Problem is, when the activity starts I get a Force Close above a black screen (interesting because the startService is after the setContentView) – although I can see through the Logcat that the service (and the server socket) was executed.
The activity manager gives me the following information:
01-10 17:55:43.706: E/ActivityManager(2490): ANR in
com.sapo.android.obesidade 01-10 17:55:43.706:
E/ActivityManager(2490): Reason: Executing service
com.sapo.android.obesidade/.MyService 01-10 17:55:43.706:
E/ActivityManager(2490): Load: 1.24 / 1.13 / 1.1 01-10 17:55:43.706:
E/ActivityManager(2490): CPU usage from 43658ms to 10ms ago: 01-10
17:55:43.706: E/ActivityManager(2490): system_server: 6% = 3% user +
3% kernel / faults: 7590 minor 01-10 17:55:43.706:
E/ActivityManager(2490): .app.twlauncher: 2% = 2% user + 0% kernel /
faults: 812 minor 01-10 17:55:43.706: E/ActivityManager(2490):
mmcqd: 0% = 0% user + 0% kernel
So the problem is undoubtedly (it works if removed) on the while(true) – something that was already working in an AsyncTask in an Activity (without using Services).
What can I do ?
Your problem (as with most ANRs) is that you’re hogging the main thread. A service by default runs on the main (UI) thread. Since you have a
while(true), it’s constantly blocking. You should launch a separate thread from your service.