在后台服务上重复下载文件

时间:2017-04-23 06:47:52

标签: android android-service android-backup-service

这是我的代码。当我点击下载按钮时,它会下载两次。如何停止第二次下载?请帮我防止第二次下载。 这是我的按钮点击监听器:

 downloadPackage.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        downloadPackage.setEnabled(false);
                        SharedPreferences.Editor editor = getSharedPreferences("SETID", MODE_PRIVATE).edit();
                        editor.putInt("setId", setId);
                        editor.commit();
                        Intent intent = new Intent(ReadingListeningTestActivity.this, DownloadService.class);
                        startService(intent);
                    }
                });
这是我的 下载服务:

public class DownloadService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private NotificationManager notificationManager;
    private NotificationCompat.Builder notificationBuilder;
    private int totalFileSize;
    SharedPreferences prefs;
    private boolean isDownloading = false;

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        prefs = getSharedPreferences("SETID", MODE_PRIVATE);
        int setId = prefs.getInt("setId", 0);
        Log.d("SEtID", setId + "");
        if (isDownloading) {
            return;
        } else {
            Log.d("Download", "isDownloading: " + isDownloading);
            isDownloading = true;
            initDownload(setId);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    private void initDownload(int setId) {
                new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... voids) {
                        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                        notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
                                .setSmallIcon(R.mipmap.ic_launcher)
                                .setContentTitle(data.getTitle())
                                .setContentText("Downloading File")
                                .setAutoCancel(true);
                        notificationManager.notify(0, notificationBuilder.build());
                        downloadFileTest("test.zip");
                        return null;
                    }
                }.execute();

    }

    private void downloadFileTest(String uri) {
        int count;
        InputStream stream = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        String fileName = packageName(uri);

        try {
            URL url = new URL(Application.BASE_URL + uri);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return;
            }
            byte data[] = new byte[4096];
            long fileSize = connection.getContentLength();
            stream = new BufferedInputStream(connection.getInputStream());
            File outputFile = getCacheDir(fileName + ".part");
            output = new FileOutputStream(outputFile);
            try {
                long total = 0;
                long startTime = System.currentTimeMillis();
                int timeCount = 1;
                while ((count = stream.read(data)) != -1) {
                    total += count;
                    totalFileSize = (int) (fileSize / (Math.pow(1024, 2)));
                    double current = Math.round(total / (Math.pow(1021, 2)));
                    int progress = (int) ((total * 100) / fileSize);
                    long currentTime = System.currentTimeMillis() - startTime;
                    Download download = new Download();
                    download.setTotalFileSize(totalFileSize);
                    if (currentTime > 1000 * timeCount) {
                        download.setCurrentFileSize((int) current);
                        download.setProgress(progress);
                        sendNotification(download);
                        timeCount++;
                    }
                    output.write(data, 0, count);
                }
            } catch (IOException e) {
                isDownloading = false;
                prefs.edit().clear().commit();
                outputFile.delete();
                onErrorDownload("Internet Connection Problem Retry Download");
            } finally {
                isDownloading = false;
                prefs.edit().clear().commit();
                File originalName = getCacheDir(fileName);
                if (originalName.exists()) {
                    outputFile.delete();
                    throw new IOException("file exists");
                }
                boolean success = outputFile.renameTo(originalName);
                if (success) {
                    if (connection != null)
                        connection.disconnect();
                    onDownloadComplete();
                    output.flush();
                    output.close();
                    stream.close();
                }
            }
        } catch (IOException e) {
            isDownloading = false;
            prefs.edit().clear().commit();
            Log.d("Test", "Main");
            if (e.getMessage().equals("file exists"))
                onErrorDownload("Package Already Exists");
            else
                onErrorDownload("Internet Connection Problem Retry Download");
        }
    }

    private void onDownloadComplete() {
        Download download = new Download();
        download.setProgress(100);
        sendIntent(download);
        notificationManager.cancel(0);
        notificationBuilder.setOngoing(false);
        notificationBuilder.setProgress(0, 0, false);
        notificationBuilder.setContentText("File Downloaded");
        notificationManager.notify(0, notificationBuilder.build());
    }

    private void onErrorDownload(String message) {
        Download download = new Download();
        download.setProgress(download.getProgress());
        sendIntent(download);
        notificationManager.cancel(0);
        notificationBuilder.setOngoing(false);
        notificationBuilder.setProgress(0, 0, false);
        notificationBuilder.setContentText(message);
        notificationManager.notify(0, notificationBuilder.build());
    }

    private void sendNotification(Download download) {
        sendIntent(download);
        notificationBuilder.setProgress(100, download.getProgress(), false);
        notificationBuilder.setOngoing(true);
        notificationBuilder.setContentText("Downloading Progress " + download.getProgress() + "%" + " /100%");
        notificationManager.notify(0, notificationBuilder.build());

    }

    private void sendIntent(Download download) {
        Intent intent = new Intent(ReadingListeningTestActivity.MESSAGE_PROGRESS);
        intent.putExtra("download", download);
        LocalBroadcastManager.getInstance(DownloadService.this).sendBroadcast(intent);
    }

    private String packageName(String uri) {
        String[] parts = uri.split("/");
        return parts[parts.length - 1];
    }

    public File getCacheDir(String packageName) {
        File cache = null;
        File external = getApplication().getExternalCacheDir();
        if (external != null && external.exists()) {
            cache = external;
        } else {
            cache = getApplication().getCacheDir();
        }
        File file = new File(cache, packageName);
        return file;
    }
}

0 个答案:

没有答案