This my first attempt at working with a service. My service is intended to download an image file from a server based on a filename string that it gets dynamically.
I'm getting the following error. Does anyone see what I am doing wrong? Thank you!
08-19 16:40:18.102: E/AndroidRuntime(27702): java.lang.RuntimeException: Unable to instantiate service database.DownloadPicture: java.lang.InstantiationException: can't instantiate class database.DownloadPicture; no empty constructor
Here is how I am starting the service:
Intent intent = new Intent(context, DownloadPicture.class);
intent.putExtra(DownloadPicture.FILENAME, filename);
startService(intent);
System.err.println("service started");
This is my service:
public class DownloadPicture extends IntentService {
private int result = Activity.RESULT_CANCELED;
public static final String FILENAME = "filename";
public static final String FILEPATH = "filepath";
public static final String RESULT = "result";
public static final String NOTIFICATION = "com.mysite.myapp";
public DownloadPicture(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent intent) {
String urlPath = this.getResources().getString(R.string.imagesURL);
String fileName = intent.getStringExtra(FILENAME);
File output = new File(Environment.getExternalStorageDirectory(), fileName);
if (output.exists()) {output.delete();}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
stream = url.openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
fos = new FileOutputStream(output.getPath());
int next = -1;
while ((next = reader.read()) != -1) {
fos.write(next);
}
// Successful finished
result = Activity.RESULT_OK;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
publishResults(output.getAbsolutePath(), result);
}
private void publishResults(String outputPath, int result) {
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(FILEPATH, outputPath);
intent.putExtra(RESULT, result);
sendBroadcast(intent);
}
}