0

这是我第一次尝试使用服务。我的服务旨在根据动态获取的文件名字符串从服务器下载图像文件。

我收到以下错误。有谁看到我做错了什么?谢谢!

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

这是我启动服务的方式:

Intent intent = new Intent(context, DownloadPicture.class);
intent.putExtra(DownloadPicture.FILENAME, filename);
startService(intent);
System.err.println("service started");

这是我的服务:

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);
      }
}
4

2 回答 2

0

If you carefully read the error it says : no empty constructor . So try to have an empty default no-argument constructor for IntentService like:

public DownloadPicture() {
    super("DownloadPicture");
}

See No empty constructor when create a service Hope it helps.

于 2013-08-19T22:57:34.140 回答
0

Have you added the service to your manifest?

<service android:name=".DownloadPicture" />

于 2013-08-19T23:01:09.767 回答