1. 程式人生 > >開發問題及解決 E/AndroidRuntime(15377): Caused by: java.lang.InstantiationException: can't instantiate clas

開發問題及解決 E/AndroidRuntime(15377): Caused by: java.lang.InstantiationException: can't instantiate clas

在使用IntentService時,沒有定義無參的建構函式。

如下所示。

程式碼段1:

public class CustomIntentService extends IntentService {
	
	private static final String TAG = CustomIntentService.class.getSimpleName();
	static String s = "test";
	
//	public CustomIntentService() {
//		super("CustomIntentService");
//	}

	public CustomIntentService(String name) {
		super(name);
		Log.i(TAG, "CustomIntentService");
	}

	@Override
	public void setIntentRedelivery(boolean enabled) {
		super.setIntentRedelivery(enabled);
		Log.i(TAG, "setIntentRedelivery");
	}

	@Override
	public void onCreate() {
		super.onCreate();
		Log.i(TAG, "onCreate");
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		Log.i(TAG, "onStart");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return super.onStartCommand(intent, flags, startId);
	}
}

這樣我們用以下方式使用IntentService的時,就會報如標題所示的錯誤。

程式碼段2:

		Intent startServiceIntent1 = new Intent();
		startServiceIntent1.setClass(this, CustomIntentService.class);
		Bundle bundle = new Bundle();
		bundle.putString("param", "oper1");
		startServiceIntent1.putExtras(bundle);  
		startService(startServiceIntent1);

解決方法就是將程式碼段1中被註釋掉的部分放開。