【问题标题】:Notification blocks UI通知块 UI
【发布时间】: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


【解决方案1】:

在 Donut 之后直到 Honeycomb (1.6 – 3.0) 到版本 3.0 默认情况下它并行使用多个 AsyncTask,所以这可能就是它工作正常的原因。 详细解释可以参考https://stackoverflow.com/a/36078608/2249287

【讨论】:

  • 那么在我的情况下是否可以在单独的线程中运行通知?
猜你喜欢
  • 2019-06-28
  • 2012-04-11
  • 1970-01-01
  • 1970-01-01
  • 2015-05-26
  • 1970-01-01
  • 1970-01-01
  • 2020-01-17
  • 2018-06-06
相关资源
最近更新 更多