我正在尝试制作一个简单的应用来测试Services类。我想要一个按钮,按下按钮启动服务并显示服务已启动的Toast,但是,每当我按下按钮时,应用程序崩溃,我不知道问题是什么。 测试类:
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);
}
清单文件
<?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>
控制器类:
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();
}
}
我收到的错误:
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
答案 0 :(得分:1)
如果您定义:
,您的服务确实需要无参数构造函数public Controller(String name)
然后java不会自动添加参数少一个,并且android需要它使用startService
来实例化你的服务
答案 1 :(得分:0)
我无法在您的清单O_o
中看到<application>
张开标记