0

我有一些线程可以打开进度对话框并下载文件。当线程下载文件时,它会更新进度条。但是如果进度对话框被隐藏,线程会创建一个通知并在通知中更新进度条。我想做这个:当用户点击通知时,Android 会打开 Activity 并显示进度对话框。我怎样才能做到这一点?

这是我下载文件的方法:

    public void downloadAction(int id) {
    if(id<0 || id>data.length) { IO.showNotify(MusicActivity.this, getResources().getStringArray(R.array.errors)[4]); return; }
    final int itemId = id;

    AsyncTask<Void, Integer, Boolean> downloadTask = new AsyncTask<Void, Integer, Boolean>() {
        ProgressDialog progressDialog = new ProgressDialog(MusicActivity.this);
        String error = null;
        int nId = -1;
        int progressPercent = 0;
        boolean notificated = false;
        int urlFileLength;
        String FILE_NAME = fileName(data.getName(itemId));

        @Override
        protected void onPreExecute() {
            progressDialog.setTitle(data.getName(itemId));
            progressDialog.setIndeterminate(false);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setCancelable(true);
            progressDialog.setOnCancelListener(new OnCancelListener() {
                public void onCancel(DialogInterface dialog) {
                    cancel(true);
                }
            });

            progressDialog.setButton(Dialog.BUTTON_POSITIVE, getResources().getString(R.string.hide), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    progressDialog.hide();
                }
            });
            progressDialog.setButton(Dialog.BUTTON_NEGATIVE, getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    if(progressDialog.isShowing()) { cancel(true); progressDialog.dismiss();}
                }
            });

            progressDialog.show();
            progressDialog.setProgressNumberFormat("");                             
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            int localFileLength, len;
            int fullProgress = 0;
            byte[] bytes = new byte[1024];
            File rootDir = new File(PATH);

            if(!rootDir.isDirectory()) rootDir.mkdir();

            try {
                URLConnection urlConnection = new URL(data.getUrl(itemId)).openConnection();
                urlConnection.setConnectTimeout(20000);
                urlConnection.setReadTimeout(60000);

                localFileLength = (int) new File(FILE_NAME).length();
                urlFileLength = urlConnection.getContentLength();

                if (urlFileLength == 169 || urlFileLength == 0 || urlFileLength == -1) {
                    error = getResources().getStringArray(R.array.errors)[5];
                    return false;
                }
                if (urlFileLength == localFileLength) {
                    error = getResources().getString(R.string.file_exist);
                    return false;
                } else {
                    publishProgress(0, urlFileLength);
                    InputStream in = urlConnection.getInputStream();
                    OutputStream out = new FileOutputStream(FILE_NAME);

                    while((len=in.read(bytes))!=-1) {
                        if(!isCancelled()) {
                            out.write(bytes, 0, len);
                            fullProgress += len;
                            publishProgress(fullProgress);
                        } else {
                            new File(FILE_NAME).delete();
                            error = getResources().getString(R.string.stopped);
                            return false;                               
                        }
                    }

                }

            } catch (MalformedURLException e) {
                new File(FILE_NAME).delete();
                error = getResources().getStringArray(R.array.errors)[2];
            } catch (IOException e) {
                new File(FILE_NAME).delete();
                error = getResources().getStringArray(R.array.errors)[3];
            }



            return true;
        }

        @Override
        protected void onProgressUpdate(Integer ... progress) {
            int tmp;

            if (progress.length==2) {
                progressDialog.setProgress(progress[0]);
                progressDialog.setMax(progress[1]);
            } else if(progress.length==1) {
                if(!progressDialog.isShowing()) {
                    if(!notificated) {
                        nId = NotificationUtils.getInstace(MusicActivity.this).createDownloadNotification(data.getName(itemId));
                        notificated = true;
                    } else {
                        tmp = (int) (progress[0]/(urlFileLength*0.01));
                        if(progressPercent!=tmp) {
                            progressPercent = tmp;
                            NotificationUtils.getInstace(MusicActivity.this).updateProgress(nId, progressPercent);
                        }
                    }
                } else {
                    progressDialog.setProgress(progress[0]);
                }
            }
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if(result==true && error == null) {
                if(progressDialog.isShowing()) {
                    IO.showNotify(MusicActivity.this, getResources().getString(R.string.downloaded) + " " + PATH);
                    progressDialog.dismiss();
                } else if (nId!=-1) {
                    NotificationUtils.getInstace(MusicActivity.this).cancelNotification(nId);
                    NotificationUtils.getInstace(MusicActivity.this).createMessageNotification(data.getName(itemId) + " " + getResources().getString(R.string.finished));
                }
            } else {
                if(progressDialog.isShowing()) {
                    IO.showNotify(MusicActivity.this, error);
                    progressDialog.dismiss();
                } else if (nId!=-1){
                    NotificationUtils.getInstace(MusicActivity.this).cancelNotification(nId);
                    NotificationUtils.getInstace(MusicActivity.this).createMessageNotification(getResources().getString(R.string.error) + "! " + error);
                }
            }

        }

        @Override
        protected void onCancelled() {
            IO.showNotify(MusicActivity.this, getResources().getString(R.string.stopped));
        }

    };

    if(downloadTask.getStatus().equals(AsyncTask.Status.PENDING) || downloadTask.getStatus().equals(AsyncTask.Status.FINISHED))
        downloadTask.execute();
}

这是创建通知的两种方法:

public int createDownloadNotification(String fileName) {
    String text = context.getString(R.string.notification_downloading).concat(" ").concat(fileName); 
    RemoteViews contentView = createProgressNotification(text, text);
    contentView.setImageViewResource(R.id.notification_download_layout_image, android.R.drawable.stat_sys_download);

    return lastId++;
}


private RemoteViews createProgressNotification(String text, String topMessage) {
    Notification notification = new Notification(android.R.drawable.stat_sys_download, topMessage, System.currentTimeMillis());
    RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.notification_download_layout);
    contentView.setProgressBar(R.id.notification_download_layout_progressbar, 100, 0, false);
    contentView.setTextViewText(R.id.notification_download_layout_title, text);

    notification.contentView = contentView;
    notification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT | Notification.FLAG_ONLY_ALERT_ONCE;

    Intent notificationIntent = new Intent(context, NotificationUtils.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

    notification.contentIntent = contentIntent;

    manager.notify(lastId, notification);
    notifications.put(lastId, notification);

    return contentView;
}

请帮帮我...

4

1 回答 1

0

我不确定,但在我的通知代码中我没有notification.contentIntent = contentIntent;,而且您似乎在该 manager.notify(lastId, notification);行之前错过了这个:

notification.setLatestEventInfo(context, MyNotifyTitle, MyNotifiyText, contentIntent );

MyNotifyTitle 是通知的标题,MyNotifyText 是文本。在 contentIntent 之前添加它们

MyIntent.putExtra("extendedTitle", notificationIntent );
MyIntent.putExtra("extendedText" , notificationIntent );

希望这可以帮助。

于 2012-05-19T06:58:30.693 回答