Progress bar in notification not updates in Androi

2019-08-17 11:12发布

问题:

In my android app, using a progress notification, its working in all android versions except android O. In android O, file is getting downloaded but progress bar is not updating neither it shows "Download Complete". Below is my code which is under AsyncTask --

private class BackTask extends AsyncTask<String,Integer,Void> {
        NotificationManager mNotifyManager;
        NotificationCompat.Builder mBuilder;
        NotificationChannel notificationChannel;

        protected void onPreExecute() {
            super.onPreExecute();
            mNotifyManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);

            Uri selectedUri = Uri.parse(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(selectedUri, "resource/folder");
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

            mBuilder = new NotificationCompat.Builder(context, null);
            mBuilder.setContentTitle("Downloading - "+lblTitle.getText())
                    .setContentText("Download in progress")
                    .setSmallIcon(R.drawable.doupnowlogo)
                    .setOnlyAlertOnce(true)
                    .setContentIntent(pendingIntent);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH);

                // Configure the notification channel.
                notificationChannel.setDescription("Channel description");
                notificationChannel.enableLights(true);
                notificationChannel.setLightColor(Color.RED);
                notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
                notificationChannel.enableVibration(true);
                notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
                mNotifyManager.createNotificationChannel(notificationChannel);
            }
            else {
                mBuilder.setContentTitle("Downloading - "+lblTitle.getText())
                        .setPriority(NotificationCompat.PRIORITY_HIGH)
                        .setColor(ContextCompat.getColor(context, R.color.red))
                        .setVibrate(new long[]{100, 250})
                        .setLights(Color.YELLOW, 500, 5000)
                        .setAutoCancel(true);
            }

            mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            mNotifyManager.notify(1, mBuilder.build());

            Toast.makeText(getActivity().getApplicationContext(), "Downloading the file...", Toast.LENGTH_SHORT).show();
        }

        protected Void doInBackground(String...params){
            URL url;
            int count;
            try {
                url = new URL(params[0].replaceAll(" ", "%20"));
                String pathl="";
                try {
                    File f=new File(storeDir);
                    if(f.exists()){
                        HttpURLConnection con=(HttpURLConnection)url.openConnection();
                        InputStream is=con.getInputStream();
                        String pathr=url.getPath();
                        String filename=pathr.substring(pathr.lastIndexOf('/')+1);
                        pathl=storeDir+"/"+filename;
                        FileOutputStream fos=new FileOutputStream(pathl);
                        int lenghtOfFile = con.getContentLength();
                        byte data[] = new byte[1024];
                        long total = 0;
                        while ((count = is.read(data)) != -1) {
                            total += count;
                            // publishing the progress
                            publishProgress((int)((total*100)/lenghtOfFile));
                            // writing data to output file
                            fos.write(data, 0, count);
                        }

                        is.close();
                        fos.flush();
                        fos.close();
                    }
                    else{
                        Log.e("Error","Not found: "+storeDir);
                    }

                } catch (Exception e) {
                    e.printStackTrace();

                }

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;

        }

        protected void onProgressUpdate(Integer... progress) {

            mBuilder.setProgress(100, progress[0], false);
            // Displays the progress bar on notification
            mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
        }

        protected void onPostExecute(Void result){
            mBuilder.setContentText("Download complete");
            // Removes the progress bar
            mBuilder.setProgress(0,0,false);
            mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
        }
    }

The full program is working great in other versions, but getting the problem only in android o.

回答1:

It may help you, I am showing notifications in my current ongoing project. It shows notifications from 4.1 to latest 8.0 Oreo. Tested on each platform.


Here are my class private members :

private static final int NOTIFICATION_ID = 1;
private static final String NOTIFICATION_CHANNEL_ID = "1";

In the same class i am creating and showing notifications with following code

try
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            startForeground(1,new Notification());

            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);

            // Configure the notification channel.
            notificationChannel.setDescription("Channel description");
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationManager.createNotificationChannel(notificationChannel);

            // notification.defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE;

            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                    .setSmallIcon(R.drawable.ic_service_success)
                    .setContentTitle("Insta Promo")
                    .setContentText("We are ready to help you.");

            notificationManager.notify(NOTIFICATION_ID, builder.build());
        }
        else
        {
            final Intent intent = new Intent(this, WatchMan.class);
            PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationCompat.Builder b = new NotificationCompat.Builder(this,"mychannel");

            b.setAutoCancel(true)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.drawable.ic_service_success)
                    .setTicker("Success")
                    .setContentTitle("Insta Promo")
                    .setContentText("We are ready to help you.")
                    .setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND).setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND)
                    .setContentIntent(contentIntent)
                    .setContentInfo("Info");

            NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(1, b.build());

        }

    }
    catch(Exception e)
    {
        Log.d(TAG, "Null pointer exception xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...\n");
        System.out.println("Null Pointer ");
    }

JUST DO NOT USE startForeground(1,new Notification()); , As i am in service and want to continue onstartcommand to get started.


You may see the developer warning TOAST message on android 8.0 oreo and if you or any other member can resolve this issue too then it would be great for both of us.



回答2:

The problem in line:

mBuilder = new NotificationCompat.Builder(context, null);

You should use channel_id in builder constructor (you have added it below like notificationChannel) Also I see you created channel bellow like:

notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_HIGH);

I think it's better to use NotificationManager.IMPORTANCE_LOW for progress notifications because NotificationManager.IMPORTANCE_HIGH will displays with pops up effect.

So I think the best way to use two channels here. First one for starting/completed/error notifications and second one only for progress. And the first channel will use NotificationManager.IMPORTANCE_DEFAULT or NotificationManager.IMPORTANCE_HIGH priority but progress channel -NotificationManager.IMPORTANCE_LOW. In this implementation we could see start notification with sound vibration etc. and progress notifications without sound in system tray.