I’m reading “Pro Android 2” which contains an excellent Service example as follows:
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class TestService1 extends Service {
private static final String TAG = "TestService1";
@Override
public void onCreate() {
Log.d(TAG, "onCreate");
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind");
return null;
}
}
I also added the service definition entry as a child of:
<application> in my AndroidManifest.xml as follows:
<service android:name="TestService1"></service>
The book then says:”The next obvious question is how to do you call the service?”
And that’s precisely what I want to know!!! I’ve scoured the book and I don’t see how to start up the service. The book actually seems to indicate that the service is called on start up. Maybe I’ve just misunderstood this part.
This is just experimental and I just want to see the service run and see the Log messages in logcat. The book says:”The system calls onCreate() when the service is first created, but before calling onStart(). This process, which resembles the process for creating an activity, provides a way for the service to perform one-time initialization at startup.”
Well ok, but I’m not sure what to do to start the service except perhaps in my primary activity’s onCreate() do something like:
Intent TestService1 = new Intent(this,com.mydomain.myproject.TestService1.class);
startActivity(TestService1);
But when I do this I get THE error: “The application … has stopped unexpectedly.”
I think this problem has a simple solution, but I’m just too simple to see it:)
You’re very close. A service is not an activity, so you can’t use
startActivityto start it. Instead, use the similarly namedstartServicemethod.