Your service does need parameterless constructor, if you define:
public Controller(String name)
then java will not automatically add parameter less one, and android needs it to instantiate your Service using startService
سؤال
I'm trying to make a simple app to test out the Services class. I want to have a button that when pressed starts a service and shows a Toast that the service has started, however, whenever I press the button the app crashes and I do not know what the problem is. Testing Class:
public class ControllerTestingScreen extends Activity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_controller_test_screen);
//Set button colors to red, green, blue, and red, respectively
Button button = (Button) findViewById(R.id.testbutton);
button.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
OnClickListener buttonListener = new View.OnClickListener(){
public void onClick(View arg0) {
startService(new Intent(getBaseContext(),Controller.class));
//sendSMS("PutPhoneNumberHereForTesting","WhereYouApp Text Message Test");
}
};
button.setOnClickListener(buttonListener);
}
Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.whereyouapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<activity
android:name="com.example.whereyouapp.ControllerTestingScreen"
android:label="YOLO">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.example.whereyouapp.Controller"/>
</application>
</manifest>
Controller Class:
public class Controller extends Service{
private static final int POLL_INTERVAL = 1000 * 30;
public Controller(String name) {
super();
// TODO Auto-generated constructor stub
}
public int onStartCommand(Intent intent,int flags, int startId){
Toast.makeText(this, "yololo- the service class works", Toast.LENGTH_LONG).show();
return START_STICKY;
}
public void onDestroy(){
super.onDestroy();
Toast.makeText(this, "yolo- the service has stopped working", Toast.LENGTH_LONG).show();
}
}
Error that I'm getting:
logcat error: 02-23 14:10:40.187: E/AndroidRuntime(1173): java.lang.RuntimeException: Unable to instantiate service com.example.whereyouapp.Controller: java.lang.InstantiationException: can't instantiate class com.example.whereyouapp.Controller; no empty constructor
المحلول
Your service does need parameterless constructor, if you define:
public Controller(String name)
then java will not automatically add parameter less one, and android needs it to instantiate your Service using startService
نصائح أخرى
I can't see <application>
opening tag in your manifest O_o