下载管理器下载失败

时间:2014-01-07 06:10:24

标签: android android-download-manager

我正在使用DownloadManager下载以下网址:

http://dj-videos.us/Music/XclusiveSinGleTrack/320%20Kbps/November%202013/Yo%20Yo%20Honey%20Singh%20-%20Blue%20Eyes- [DJKANG.Com] .MP3

但是下载失败了。我甚至在浏览器上点击了网址,它运行正常。这是url解析的问题吗?

代码:DDownloadService.java

public class DDownloadService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
Context conte;
// NotificationManager notificationManager;
// NotificationCompat.Builder mBuilder;
boolean playing = false;
Runnable runnable;
SharedPreferences pre;
static int countOfCurrent = 0;
String downloadName, downloadUrl;
NotificationManager notificationManager;
NotificationCompat.Builder mBuilder;

// ..
static int downloadNumber = 0;
DownloadManager mgr[] = new DownloadManager[100];
long downloadIds[] = new long[100];
BroadcastReceiver cancelDownload;

private final class ServiceHandler extends Handler {
    public ServiceHandler(Looper looper) {
        super(looper);
    }

    @Override
    public void handleMessage(Message msg) {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        downloadNumber++;
        downloadName = pre.getString("downloadname", "");
        downloadName = viewSD(downloadName);
        downloadUrl = pre.getString("downloadurl", "");
        downloadName = downloadName.toLowerCase();
        pre.edit()
                .putString(
                        "songsInDownload",
                        pre.getString("songsInDownload", "") + "|"
                                + downloadName).commit();
        pre.edit().putInt(downloadName + "no", +downloadNumber).commit();
        mgr[downloadNumber] = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        try {
            countOfCurrent++;
            downloadIds[downloadNumber] = mgr[downloadNumber]
                    .enqueue(new DownloadManager.Request(Uri
                            .parse(downloadUrl))
                            .setAllowedNetworkTypes(
                                    DownloadManager.Request.NETWORK_WIFI
                                            | DownloadManager.Request.NETWORK_MOBILE)
                            .setAllowedOverRoaming(false)
                            .setTitle("Downloading")
                            .setDescription(downloadName)
                            .setNotificationVisibility(
                                    DownloadManager.Request.VISIBILITY_HIDDEN)
                            .setDestinationInExternalPublicDir(
                                    Environment.DIRECTORY_MUSIC,
                                    downloadName)
                            .setVisibleInDownloadsUi(false));
            pre.edit()
                    .putLong(downloadName + "id",
                            downloadIds[downloadNumber]).commit();
            Timer myTimer = new Timer();
            myTimer.schedule(new RegrowCornAnimate(downloadNumber,
                    downloadName), 0, 10);
        } catch (IllegalStateException e) {
            Toast.makeText(getBaseContext(), "No storage found!",
                    Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), " Something wrong happened!",
                    Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
}

@Override
public void onCreate() {
    conte = this;
    pre = getSharedPreferences("download", 0);
    downloadName = pre.getString("downloadname", "");
    downloadUrl = pre.getString("downloadurl", "");
    cancelDownload = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            try {
                mgr[pre.getInt(arg1.getExtras().getString("name") + "no", 0)]
                        .remove(pre.getLong(
                                arg1.getExtras().getString("name") + "id",
                                0));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    registerReceiver(cancelDownload, new IntentFilter("cancelIt"));
    notificationManager = (NotificationManager) conte
            .getSystemService(Context.NOTIFICATION_SERVICE);
    mBuilder = new NotificationCompat.Builder(conte)
            .setSmallIcon(R.drawable.icon)
            .setContentTitle("Downloading in progress").setContentText("");
    startForeground(55, mBuilder.build());
    notificationManager.cancel(55);
    HandlerThread thread = new HandlerThread("ServiceStartArguments", 0);

    // //..................
    // notificationManager = (NotificationManager) conte
    // .getSystemService(Context.NOTIFICATION_SERVICE);
    // mBuilder = new NotificationCompat.Builder(conte);
    // RemoteViews remoteViews = new RemoteViews(getPackageName(),
    // R.layout.notification_layout);
    // try {
    // mBuilder.setSmallIcon(R.drawable.icon);
    // mBuilder.setAutoCancel(false).setOngoing(true)
    // .setContent(remoteViews);
    // Uri uri = RingtoneManager
    // .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    // mBuilder.setSound(uri);
    // notificationManager.notify(Mp3Constants.NOTIFICATION_NUMBER,
    // mBuilder.build());
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // //...................

    thread.start();
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // online = intent.getExtras().getString("online");
    // link = intent.getExtras().getString("link");
    // name = intent.getExtras().getString("name");
    Message msg = mServiceHandler.obtainMessage();
    msg.arg1 = startId;
    mServiceHandler.sendMessage(msg);
    return START_NOT_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onDestroy() {
    super.onDestroy();
    unregisterReceiver(cancelDownload);
}

class RegrowCornAnimate extends TimerTask {

    private final int serial;
    private final String name_of_da;
    boolean startFlag = true, errorFlag = true;

    RegrowCornAnimate(int serial, String name) {
        this.serial = serial;
        this.name_of_da = name;
    }

    public void run() {
        // Do stuff
        int dl_progress = 0;

        try {
            DownloadManager.Query q = new DownloadManager.Query();
            q.setFilterById(downloadIds[serial]);
            Cursor c = mgr[serial].query(q);
            c.moveToFirst();
            long bytes_downloaded = c
                    .getInt(c
                            .getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
            long bytes_total = c
                    .getInt(c
                            .getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
            dl_progress = (int) ((bytes_downloaded * 100) / bytes_total);
            pre.edit().putInt(name_of_da, dl_progress).commit();
            switch (c.getInt(c
                    .getColumnIndex(DownloadManager.COLUMN_STATUS))) {
            case DownloadManager.STATUS_FAILED:
                // msg = "Download failed!";
//                  Toast.makeText(getBaseContext(), "Url Broken!",
//                          Toast.LENGTH_SHORT).show();
                sendNotification(1, serial, name_of_da, dl_progress);
                this.cancel();
                countOfCurrent--;
                if (countOfCurrent == 0)
                    stopSelf();
                break;

            case DownloadManager.STATUS_PAUSED:
                // msg = "Download paused!";
                if (errorFlag) {
                    errorFlag = false;
                    sendNotification(7, serial, name_of_da, dl_progress);
                }
                break;

            case DownloadManager.STATUS_PENDING:
                // msg = "Download pending!";
                sendNotification(0, serial, name_of_da, dl_progress);
                break;

            case DownloadManager.STATUS_RUNNING:
                // msg = "Download in progress!";
                errorFlag = true;
                if (startFlag) {
                    if (verifyFromSD(name_of_da)) {
                        startFlag = false;
                        sendBroadcast(new Intent("start"));
                    }
                }
                sendNotification(0, serial, name_of_da, dl_progress);
                break;

            case DownloadManager.STATUS_SUCCESSFUL:
                // msg = "Download complete!";
                pre.edit()
                        .putString(
                                "songsInDownload",
                                pre.getString("songsInDownload", "")
                                        .replace("|" + name_of_da, ""))
                        .commit();
                pre.edit().putInt(name_of_da, 100);
                sendNotification(0, serial, name_of_da, dl_progress);
                this.cancel();
                countOfCurrent--;
                if (countOfCurrent == 0)
                    stopSelf();
                break;

            default:
                // msg = "Download is nowhere in sight";
                sendNotification(10, serial, name_of_da, dl_progress);
                this.cancel();
                countOfCurrent--;
                if (countOfCurrent == 0)
                    stopSelf();
                break;
            }
            c.close();
        } catch (Exception e) {
            e.printStackTrace();
            sendNotification(7, serial, name_of_da, dl_progress);
            cancel();
            countOfCurrent--;
            if (countOfCurrent == 0)
                stopSelf();
        }
    }
}

public void sendNotification(int tmout, int nin, String name, int progress) {
    if (tmout == 0) {

        // notificationManager.notify(nin, mBuilder.build());
        if (progress >= 100) {
            // notificationManager.cancel(nin);
            mBuilder.setSmallIcon(R.drawable.icon)
                    .setContentTitle("Completed").setContentText(name)
                    .setAutoCancel(true).setOngoing(false)
                    .setProgress(100, 100, false);
            Uri ttt = Uri.parse(Environment.getExternalStorageDirectory()
                    .toString() + "/Music/" + name);
            pre.edit().putInt("retry", 1).commit();
            Intent inten = new Intent(Intent.ACTION_VIEW, ttt);
            String arr[] = name.split("\\.");
            inten.setDataAndType(ttt, "audio/" + arr[arr.length - 1]);
            PendingIntent i = PendingIntent.getActivity(getBaseContext(),
                    0, inten, 0);
            mBuilder.setContentIntent(i);
            notificationManager.notify(nin, mBuilder.build());
        } else {
            mBuilder.setContentTitle("Downloading: " + name)
                    .setContentText(progress + " %")
                    .setSmallIcon(R.drawable.icon).setAutoCancel(false)
                    .setOngoing(true);
            mBuilder.setProgress(100, progress, false);
            notificationManager.notify(nin, mBuilder.build());
        }
    } else {
        if (tmout == 1) {
            mBuilder.setSmallIcon(R.drawable.icon)
                    .setContentTitle("Failed: " + name)
                    .setContentText(progress + " %").setAutoCancel(true)
                    .setProgress(100, progress, false).setOngoing(false);
            // Intent intnt = new Intent(Mp3Constants.NOTIFICATION);
            // intnt.putExtra("resume", "1");
            // intnt.putExtra("url", urlD);
            // intnt.putExtra("name", name);
            // intnt.putExtra("nin", nin);
            // PendingIntent i = PendingIntent
            // .getBroadcast(conte, 0, intnt, 0);
            // mBuilder.setContentIntent(i);
        } else if (tmout == 7) {
            mBuilder.setSmallIcon(R.drawable.icon)
                    .setContentTitle("Cancelled: " + name)
                    .setAutoCancel(true).setProgress(100, progress, false)
                    .setOngoing(false);
            // Intent intnt = new Intent(Mp3Constants.NOTIFICATION);
            // intnt.putExtra("resume", "1");
            // intnt.putExtra("url", urlD);
            // intnt.putExtra("name", name);
            // intnt.putExtra("nin", nin);
            // PendingIntent i = PendingIntent
            // .getBroadcast(conte, 0, intnt, 0);
            // mBuilder.setContentIntent(i);
        } else {
            mBuilder.setSmallIcon(R.drawable.icon)
                    .setContentTitle("Interrupted: " + name)
                    .setContentText("No storage found").setAutoCancel(true)
                    .setOngoing(false);
        }

        notificationManager.notify(nin, mBuilder.build());
    }
}

private String viewSD(String naame) {
    File f = new File(Environment.getExternalStorageDirectory().toString()
            + "/Music");
    File[] files = f.listFiles();
    if (files == null) {
        return naame;
    }

    while (true) {
        String newName = naame;
        naame = relooper(files, newName);
        if (newName.equals(naame))
            break;
    }

    return naame;
}

public String relooper(File[] files, String name) {
    int send = files.length;
    for (int i = 0; i < send; i++) {
        File file = files[i];
        String myfile = file
                .getPath()
                .substring(file.getPath().lastIndexOf("/") + 1,
                        file.getPath().length()).toLowerCase();
        if (name.equalsIgnoreCase(myfile))
            return "copy_of_" + name;
    }
    return name;
}

private boolean verifyFromSD(String naame) {
    File f = new File(Environment.getExternalStorageDirectory().toString()
            + "/Music");
    File[] files = f.listFiles();
    if (files == null) {
        return false;
    }
    int send = files.length;
    for (int i = 0; i < send; i++) {
        File file = files[i];
        String myfile = file
                .getPath()
                .substring(file.getPath().lastIndexOf("/") + 1,
                        file.getPath().length()).toLowerCase();
        if (naame.equalsIgnoreCase(myfile))
            return true;
    }
    return false;
}

}

编辑:我从logcat找到了问题:

01-07 11:47:37.313: W/DownloadManager(18893): Exception for id 285: Illegal character     in path at index 115: http://dj-videos.us/Music/XclusiveSinGleTrack/320%20Kbps/November%202013/Yo%20Yo%20Honey%20Singh%20-%20Blue%20Eyes-[DJKANG.Com].mp3
01-07 11:47:37.313: W/DownloadManager(18893): java.lang.IllegalArgumentException: Illegal character in path at index 115: http://dj-videos.us/Music/XclusiveSinGleTrack/320%20Kbps/November%202013/Yo%20Yo%20Honey%20Singh%20-%20Blue%20Eyes-[DJKANG.Com].mp3
01-07 11:47:37.313: W/DownloadManager(18893):   at java.net.URI.create(URI.java:727)
01-07 11:47:37.313: W/DownloadManager(18893):   at android.net.Proxy.getProxy(Proxy.java:113)
01-07 11:47:37.313: W/DownloadManager(18893):   at android.net.Proxy.getPreferredHttpHost(Proxy.java:218)
01-07 11:47:37.313: W/DownloadManager(18893):   at com.android.providers.downloads.DownloadThread.run(DownloadThread.java:174)

但我仍然需要知道使用哪种格式来解析DownloadManager的URL。

1 个答案:

答案 0 :(得分:0)

当网址包含 [ ] 等非法字符时,会发生IllegalArgumentException。如评论中所述,您需要使用URLEncoder对这些字符进行编码。

我在我的代码中以这种方式实现了它 -

private String checkUrl(String url) {
    if(url.contains("[")) {
            String[] a = url.split("\\["); 
            String b = "[" + a[1]; //contains text after [ e.g. [DJKANG.Com].mp3
            url = a[0] + URLEncoder.encode(b, "UTF-8"); // encodes illegal characters 
        }
    return url;
}