【问题标题】:Android: Error when using Service for Background Task?Android:使用后台任务服务时出错?
【发布时间】:2025-11-26 20:40:01
【问题描述】:

我正在开发一个用于从以下位置下载文件的 Android 应用程序 服务器并将该文件保存到指定的路径..

我想让这在后台发生,所以我在服务中编写了下载功能。现在,当我在服务中使用代码时出现错误..

谁能帮我找出错误...谢谢..

我的服务代码是...

public class MyService extends Service {

  Contacts c = new Contacts();
  // File url to download
    private static String file_url = "http://f23.wapka-files.com/download/6/9/4/1408248_69459e029be95f96ff9f98ff.mp3/a0f9f2173d3d81a49c28/01-Podimeesha-Anand.Madhusoodhanan.mp3y";

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

            File folder = new File(Environment.getExternalStorageDirectory().getPath() + "/Jithin's/");
            if (!folder.exists()) {
                try {
                    folder.mkdirs();
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("Default Save Path Creation Error:" + folder);
                }
            }
            c.setA(Environment.getExternalStorageDirectory().toString() + "/Jithin's/downloadedfile.srt");
            // starting new Async Task
            new DownloadFileFromURL().execute(file_url);

        MyService.this.stopService(intent);

        return super.onStartCommand(intent, flags, startId);
    }


    /**
     * Background Async Task to download file
     * */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread
         * Show Progress Bar Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

         * Downloading file in background thread
         */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                // 6yi7 conection.connect();
                conection.setRequestProperty("Accept-Encoding", "identity");

                // getting file length
                int lenghtOfFile = conection.getContentLength();

                // input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(), 8192);

                // Output stream to write file
                OutputStream output = new FileOutputStream(c.getA());

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }


        @Override
        protected void onPostExecute(String file_url) {

            Toast.makeText(MyService.this, "Downloaded Succesfully.. check Jithin's folder 2 see file...", Toast.LENGTH_LONG).show();

            //my_image.setImageDrawable(Drawable.createFromPath(imagePath));
        }
    }
}

我的主要活动代码是..

 public void download(View view) {
        String value = getIntent().getExtras().getString("id");
        if (value.equals("Song0")) {
            Intent i=new Intent(Song_List.this, MyService.class);
            startActivity(i);
            Toast.makeText(Song_List.this, "Downloading..........", Toast.LENGTH_SHORT).show();
        }
}

【问题讨论】:

  • 错误是什么?
  • Onclick 方法无法执行..,我的主要活动中的代码]

标签: android service download


【解决方案1】:

更改您的代码,

Intent i=new Intent(Song_List.this, MyService.class);
startActivity(i); 

这个到,

Intent i=new Intent(Song_List.this, MyService.class);
startService(i);

【讨论】:

  • 谢谢它的工作.. 我还有一个疑问.. 那是下载无法在后台工作。该文件夹没有像我在代码中给出的那样创建。你能建议修改一下吗..
  • 使用字符串创建文件夹 folder_main = "NewFolder";文件 f = new File(Environment.getExternalStorageDirectory(), folder_main); if (!f.exists()) { f.mkdirs();并请检查您是否在 Manifest 中提到了写入外部存储权限
【解决方案2】:

首先,您应该像这样启动您的服务,而不是使用 startActivity

public void download(View view) {
        String value = getIntent().getExtras().getString("id");
        if (value.equals("Song0")) {
            Intent i=new Intent(Song_List.this, MyService.class);
            startService(i);
            Toast.makeText(Song_List.this, "Downloading..........", Toast.LENGTH_SHORT).show();
        }
    }

文件下载完成后停止服务

【讨论】:

    【解决方案3】:

    MyService 是服务的扩展。所以你必须使用 startService(Intent)。

    所以你的代码可能看起来像这样:

    public void download(View view) {
            String value = getIntent().getExtras().getString("id");
            if (value.equals("Song0")) {
                Intent i=new Intent(Song_List.this, MyService.class);
                startService(i);
                Toast.makeText(Song_List.this, "Downloading..........", Toast.LENGTH_SHORT).show();
            }
    }
    

    【讨论】: