*11-06 11:08:16.390: E/AndroidRuntime(3482): java.lang.RuntimeException: Unable to instantiate service com.android.Description$MyService: java.lang.InstantiationException: com.android.Description$MyService
我的代码
Class Description extends Activity{
logic
startService(new Intent(getBaseContext(), MyService.class));
logic
public class MyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
public MyService(){
super();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
System.out.println("service started");
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
}
@Override
public void onDestroy() {
System.out.println("service stopped");
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
public class HelloService extends Service {
/** indicates how to behave if the service is killed */
int mStartMode;
/** interface for clients that bind */
IBinder mBinder;
/** indicates whether onRebind should be used */
boolean mAllowRebind;
/** Called when the service is being created. */
@Override
public void onCreate() {
}
/** The service is starting, due to a call to startService() */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return mStartMode;
}
/** A client is binding to the service with bindService() */
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/** Called when all clients have unbound with unbindService() */
@Override
public boolean onUnbind(Intent intent) {
return mAllowRebind;
}
/** Called when a client is binding to the service with bindService()*/
@Override
public void onRebind(Intent intent) {
}
/** Called when The service is no longer used and is being destroyed */
@Override
public void onDestroy() {
}
}
}
清单
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<service
android:name="com.android.Description$MyService"
android:enabled="true" />
答案 0 :(得分:3)
在Activity中将您的服务类声明为静态类。
答案 1 :(得分:1)
您需要将服务类设为static classes
,只需在服务类名称之前声明static
。
答案 2 :(得分:0)
首先,删除构造函数,因为从Service继承了一个公共零参数构造函数。
然后,要么使它成为静态内部类,要么使其成为独立的公共Java类。你不能在这里使用常规内部类,因为Android无法创建该内部类的实例。