2013-08-19 83 views
0

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

我收到以下错误消息。有没有人看到我在做什么错了?谢谢!

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

回答

0

如果你仔细阅读它说的错误:no empty constructor。所以要尽量有一个空的默认的无参数的构造函数为IntentService,如:

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

No empty constructor when create a service希望它能帮助。

+0

看起来像解决了眼前的问题。现在我只需要处理所有新问题......谢谢! – Alex

+0

顺便说一句,我曾尝试创建一个空的构造函数,然后发布它。我的错误是我用'super();'而不是'super(“DownloadPicture”)''' – Alex

+0

ohh好的行。它有时会发生。现在好好工作。 –

0

您是否已将该服务添加到清单中?

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

+0

是的,它已经在清单中。谢谢! – Alex