android - 从 AsyncTask 更新通知栏导致通知栏崩溃

标签 android notifications android-asynctask android-notification-bar

我正在使用异步任务上传视频文件。为了跟踪进度,我在状态栏中运行了一个通知。通知正常工作和更新,但它会导致严重的性能问题,以至于状态栏崩溃并且需要重新启动手机。我的代码如下:

    private class UploadMedia extends AsyncTask<Void, Integer, String> {

    private int NOTIFICATION_ID = 1;
    private CharSequence _contentTitle;
    private final NotificationManager _notificationManager = (NotificationManager) getActivity()
            .getApplicationContext()
            .getSystemService(
                    getActivity().getApplicationContext().NOTIFICATION_SERVICE);
    Notification _notification;
    PendingIntent _pendingIntent;

    private long totalSize;
    private int _progress = 0;
    private InputStreamBody isb;
    private File uploadFile;

    protected void onPreExecute() {

        Intent intent = new Intent();
        _pendingIntent = PendingIntent.getActivity(getActivity(), 0,
                intent, 0);

        _contentTitle = "Uploader " + mediaTitle + " til Skoletube";
        CharSequence contentText = _progress + "% complete";

        _notification = new Notification(R.drawable.icon, _contentTitle,
                System.currentTimeMillis());
        _notification.flags = _notification.flags
                | Notification.FLAG_ONGOING_EVENT;
        _notification.contentIntent = _pendingIntent;
        _notification.setLatestEventInfo(getActivity(), _contentTitle,
                contentText, _pendingIntent);

        _notificationManager.notify(NOTIFICATION_ID, _notification);

        Toast.makeText(getActivity(), "Starter upload", Toast.LENGTH_SHORT)
                .show();

        try {
            uploadFile = new File(_mediaFile.getPath());

            // FileInputStream is = new FileInputStream(uploadFile);
            //
            // ByteArrayOutputStream bos = new ByteArrayOutputStream();
            // byte[] b = new byte[1024];
            // int bytesRead;
            // while ((bytesRead = is.read(b)) != -1) {
            // bos.write(b, 0, bytesRead);
            // }
            // byte[] data = bos.toByteArray();
            //
            // isb = new InputStreamBody(new ByteArrayInputStream(data),
            // uploadFile.getName());

        } catch (Exception ex) {
            Log.i(TAG,
                    "Pre execute - oh noes... D: "
                            + ex.getLocalizedMessage());
        }

    }

    @Override
    protected String doInBackground(Void... params) {
        String result = "";
        try {
            // Inititate connectionparts
            HttpClient client = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost(
                    "http://www.skoletube.dk/beta/api_userupload.php");

            CustomMultipartEntity multipartE = new CustomMultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE,
                    new ProgressListener() {

                        @Override
                        public void transferred(long num) {
                            publishProgress((int) ((num / (float) totalSize) * 100));

                        }
                    });

            // Add the post elements
            String timestamp = String
                    .valueOf(System.currentTimeMillis() / 1000);
            String mode = "xml";
            String hashSum = Utils.md5(ActiveUser.getPartner() + timestamp
                    + ActiveUser.getInstance().getToken()
                    + ActiveUser.getInstance().getSecret()
                    + ActiveUser.getInstance().getUserID()
                    + spnChannel.getSelectedItem().toString()
                    + mediaDescribtion + "KEYWORDLOL"
                    + spnPublic.getSelectedItem().toString() + mediaTitle
                    + ActiveUser.getSharedkey());

            multipartE.addPart("uid", new StringBody(ActiveUser
                    .getInstance().getUserID()));
            multipartE.addPart("token", new StringBody(ActiveUser
                    .getInstance().getToken()));
            multipartE.addPart("token_secret", new StringBody(ActiveUser
                    .getInstance().getSecret()));
            multipartE.addPart("partner",
                    new StringBody(ActiveUser.getPartner()));
            multipartE.addPart("timestamp",
                    new StringBody(timestamp.toString()));
            multipartE.addPart("key", new StringBody(hashSum));
            multipartE.addPart("video_title", new StringBody(mediaTitle));
            multipartE.addPart("video_desc", new StringBody(
                    mediaDescribtion));
            multipartE.addPart("video_keyword",
                    new StringBody("KEYWORDLOL"));
            multipartE.addPart("video_privacy", new StringBody(spnPublic
                    .getSelectedItem().toString()));
            multipartE.addPart("video_channel", new StringBody(spnChannel
                    .getSelectedItem().toString()));
            multipartE.addPart("videoupload", new FileBody(uploadFile));

            postRequest.setEntity(multipartE);

            totalSize = multipartE.getContentLength();


            HttpResponse loginResponse = client.execute(postRequest);
            HttpEntity theEnt = loginResponse.getEntity();
            result = EntityUtils.toString(theEnt);

            Log.i(TAG, "Result: " + result);

        } catch (Exception ex) {
            Log.i(TAG,
                    "Do in background - oh noes... D: "
                            + ex.getLocalizedMessage());

        }
        return result;
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        if (_notification == null)
            return;
        _progress = progress[0];
        _contentTitle = "Uploader " + mediaTitle + " til Skoletube";
        CharSequence contentText = _progress + "% complete";
        _notification.setLatestEventInfo(getActivity(), _contentTitle,
                contentText, _pendingIntent);
        _notificationManager.notify(NOTIFICATION_ID, _notification);
    }

    @Override
    protected void onPostExecute(String result) {
        _notificationManager.cancel(NOTIFICATION_ID);
    }

}

我正在 HTC Sensation 上对此进行测试。问题发生在我按下通知栏的那一刻,导致它展开。手机死机了,它一触即走,我是否真的会到达通知栏,或者通知栏会崩溃。如果我进入通知栏,性能问题仍然存在,再次关闭通知栏和打开它一样棘手。 我的想法是发送的通知更新数量可能是导致问题的原因,但我不确定。

感谢任何想法和建议。

最佳答案

你的怀疑是对的。 以下说明

publishProgress((int) ((num / (float) totalSize) * 100));

将以很短的间隔非常频繁地调用。

在这种情况下我会做的是存储我想要显示的 pourcent avancement 并仅在自最近一次通话后发生变化时才发送它。

doInBackground方法中,可以声明一个变量,例如:

int lastPourcent = 0;

然后,在transferred方法中:

int currentPoucent = (int) ((num / (float) totalSize) * 100);
if (currentPourcent > lastPourcent) {
    publishProgress(currentPourcent);
    lastPourcent = currentPourcent;
}

会显着减少Notification刷新方法的调用次数。

关于android - 从 AsyncTask 更新通知栏导致通知栏崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9399085/

相关文章:

android - 从 IntentService 调用 AsyncTask 的问题

android - 如何使用 FileInputStream 设置文件名?

android - 自定义 ImageView 适合其父宽度和高度

android - Android 3.0 是否支持 WebSockets?

html - 如何在 Firefox OS 中实现通知?

Android 状态栏通知加载 sd 图标

AndroidWear - 无法同时向智能 watch 发送多个通知

android - AsyncTask.execute() 安全

android - 获取 Android 中所有 Windows 的列表

android - 按后退按钮返回 Fragments