【发布时间】:2016-03-17 21:01:36
【问题描述】:
我的应用可以选择下载文件。它以这种方式工作: Activity -> IntentService -> AsyncTask(这里文件正在下载)。此外,我使用通知以百分比显示进度,这是我的问题:一切正常,例如在 Android 2.3 上,但在 Android 4.2 或 5.0 上,UI 被阻止。
之前我的代码中有一个错误(我每次都在循环中更新进度条),现在当我只在 oldProgress != actualProgress 时更新它时,它运行良好(100 次以上的操作而不是 2000 次以上)。但为什么它在 Android 2.3 上运行良好,即使有 2000+ 次操作?
这是我的通知类:
public class NotificationProgressHelper {
private static final int DOWNLOAD_PROGRESS_NOTIFICATION_ID = 1;
private Context mContext;
private Notification mNotification;
private NotificationManager mNotificationManager;
private PendingIntent mContentIntent;
private CharSequence mContentTitle;
public NotificationProgressHelper(Context context) {
mContext = context;
}
public void createNotification() {
mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.download_icon;
CharSequence contentName = mContext.getString(R.string.notification_content_name);
mNotification = new Notification(icon, contentName, System.currentTimeMillis());
mContentTitle = mContext.getString(R.string.notification_title);
CharSequence contentText = mContext.getString(R.string.notification_percent_completed, 0);
//pending intent left blank till the whole apk file will be downloaded
Intent notificationIntent = new Intent();
mContentIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0);
mNotification.setLatestEventInfo(mContext, mContentTitle, contentText, mContentIntent);
mNotification.flags = Notification.FLAG_ONGOING_EVENT;
mNotificationManager.notify(DOWNLOAD_PROGRESS_NOTIFICATION_ID, mNotification);
}
public void progressUpdate(int percentageComplete) {
CharSequence contentText = mContext.getString(R.string.notification_percent_completed, percentageComplete);
mNotification.setLatestEventInfo(mContext, mContentTitle, contentText, mContentIntent);
mNotificationManager.notify(DOWNLOAD_PROGRESS_NOTIFICATION_ID, mNotification);
}
public void completed() {
mNotificationManager.cancel(DOWNLOAD_PROGRESS_NOTIFICATION_ID);
}
public void removeDownloadSuccessNotification() {
mNotificationManager.cancel(ApplicationConstants.NotificationID.APP_UPDATE_NOTIFICATION_ID);
}
downloadFile 方法当然是在 doInBackground() 中调用的。
我知道这段代码很旧,现在我应该使用构建器,但我试过了,它与问题无关。
我做错了吗?为什么所有操作的版本在Android 2.3上运行良好?我认为它适用于主线程,但为什么呢?
【问题讨论】:
-
请粘贴您的 AsyncTask 代码。
标签: android android-asynctask android-notifications android-intentservice