Обновление progressbar из IntentService?

#android

#Android

Вопрос:

Я пытаюсь обновить progressbar, который встроен в мою панель уведомлений, но, похоже, он не работает. У меня вроде есть идея, почему это не работает, но я понятия не имею, как это решить. это код:

 public class DownloadService extends IntentService{

     public DownloadService() {
        super("DownloadService");


    }

       @Override
       public void onCreate() {
           super.onCreate();
           ctx = getApplicationContext();
           root = new File(Environment.getExternalStorageDirectory() "/folder-videos/");
           if(root.exists() amp;amp; root.isDirectory()) {

           }else{
               root.mkdir();
           }          
           notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
           PendingIntent contentIntent = PendingIntent.getActivity(this, 0, null, 0);

           notification = new Notification(R.drawable.icon, "App", System.currentTimeMillis());
           contentView = new RemoteViews(getPackageName(), R.layout.progress_layout);
           notification.flags = Notification.FLAG_AUTO_CANCEL;
           notification.contentView = contentView;
           notification.contentIntent = contentIntent;
           contentView.setProgressBar(R.id.status_progress, 100, 0, false);        
           contentView.setTextViewText(R.id.status_text,"Downloading...");  

       }

        @Override
    protected void onHandleIntent(Intent intent) {
        Intent broadcastIntent = new Intent();

        int count;
        String full_url = URL   intent.getStringExtra(VIDEOS);

        try {
            URL url = new URL(full_url);
            URLConnection conexion = url.openConnection();
            conexion.connect();
            File file = new File(root.getPath(), intent.getStringExtra(VIDEOS));

            int lenghtOfFile = conexion.getContentLength();
            Log.d("ANDRO_ASYNC", "Lenght of file: "   lenghtOfFile);

            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(file);

            byte data[] = new byte[1024];

            long total = 0;
            contentView.setTextViewText(R.id.status_text,"Downloading "   intent.getStringExtra(VIDEOS));  
            while ((count = input.read(data)) > 0) {
               total  = count;      
               notification.contentView.setProgressBar(R.id.status_progress, 100,(int)((total*100)/lenghtOfFile), false);       
               Log.e("totaltotal",""   (int)((total*100)/lenghtOfFile));
               output.write(data, 0, count);


            } 
            notificationManager.notify(1,notification);
            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
            Log.e("PRINTSTACK","STACK:"   e.getMessage());
            e.printStackTrace();
        }

    }
}
  

Я знаю, что мне нужно вызвать: NotificationManager.notify(1, уведомление); в цикле while, и я пробовал, но это замораживает приложение и приводит к его сбою. Есть ли какой-либо другой способ уведомить диспетчер уведомлений об обновлениях progressbar.

Спасибо!!

Ответ №1:

попробуйте использовать notificationManager.notify(1,notification); только несколько раз

как в :

 int lastProgressUpdate=0;
while(...)
{
    if(progress%5==0 amp;amp; progress!=lastProgressUpdate)
    {

         notificationManager.notify(1,notification);
         lastProgressUpdate=progress;
    }
}
  

Комментарии:

1. Попробовал с 5, он все еще продолжал замораживать пользовательский интерфейс. Попробовал с 10 тем же, хотя и в меньшей степени, я все равно мог опустить панель уведомлений, но она шла медленно и зависала.

2. есть ли какой-то NotificationListener, который прослушивает обновления и уведомляет NotificationManager.

3. он обновляет его, как и раньше, но когда я опускаю панель уведомлений, она продолжает зависать…

4. есть ли какой-либо другой способ, кроме использования цикла while для обновления progressbar во время загрузки файла!!

5. этот код (цикл while) находится внутри IntentService и внутри onHandleIntent, который выполняется как отдельный поток от основного, который должен быть в порядке.