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

サービスをマニフェストに追加しましたか?

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

于 2013-08-19T23:01:09.767 に答える
0

エラーを注意深く読むと、次のように表示されますno empty constructor。したがって、次のような空のデフォルトの引数なしコンストラクターを用意してみてくださいIntentService

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

サービスを作成するときに空のコンストラクターがないことを参照してください

于 2013-08-19T22:57:34.140 に答える