Android:使用Service for Background Task时出错?

时间:2016-08-30 06:48:24

标签: android service downloading

我正在开发一个用于从中下载文件的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();
        }
}

3 个答案:

答案 0 :(得分:4)

更改您的代码,

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

这个,

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

答案 1 :(得分:2)

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

答案 2 :(得分: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();
        }
    }
文件下载完成后停止服务后