2012-05-19 2 views
0

У меня есть поток, который открывает диалог прогресса и загружает файл. Пока поток загружает файл, он обновляет индикатор выполнения. Но если диалог прогресса был скрыт, поток создает уведомление и обновляет индикатор выполнения в уведомлении. Я хочу сделать это: когда пользователь нажимает на уведомление, Android открывает Activity и показывает диалог выполнения. Как я могу это сделать?Как запустить код при нажатии пользователем на уведомление?

Это мой метод, который загружает файл:

public void downloadAction(int id) { 
    if(id<0 || id>data.length) { IO.showNotify(MusicActivity.this, getResources().getStringArray(R.array.errors)[4]); return; } 
    final int itemId = id; 

    AsyncTask<Void, Integer, Boolean> downloadTask = new AsyncTask<Void, Integer, Boolean>() { 
     ProgressDialog progressDialog = new ProgressDialog(MusicActivity.this); 
     String error = null; 
     int nId = -1; 
     int progressPercent = 0; 
     boolean notificated = false; 
     int urlFileLength; 
     String FILE_NAME = fileName(data.getName(itemId)); 

     @Override 
     protected void onPreExecute() { 
      progressDialog.setTitle(data.getName(itemId)); 
      progressDialog.setIndeterminate(false); 
      progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
      progressDialog.setCancelable(true); 
      progressDialog.setOnCancelListener(new OnCancelListener() { 
       public void onCancel(DialogInterface dialog) { 
        cancel(true); 
       } 
      }); 

      progressDialog.setButton(Dialog.BUTTON_POSITIVE, getResources().getString(R.string.hide), new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 
        progressDialog.hide(); 
       } 
      }); 
      progressDialog.setButton(Dialog.BUTTON_NEGATIVE, getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 
        if(progressDialog.isShowing()) { cancel(true); progressDialog.dismiss();} 
       } 
      }); 

      progressDialog.show(); 
      progressDialog.setProgressNumberFormat("");        
     } 

     @Override 
     protected Boolean doInBackground(Void... params) { 
      int localFileLength, len; 
      int fullProgress = 0; 
      byte[] bytes = new byte[1024]; 
      File rootDir = new File(PATH); 

      if(!rootDir.isDirectory()) rootDir.mkdir(); 

      try { 
       URLConnection urlConnection = new URL(data.getUrl(itemId)).openConnection(); 
       urlConnection.setConnectTimeout(20000); 
       urlConnection.setReadTimeout(60000); 

       localFileLength = (int) new File(FILE_NAME).length(); 
       urlFileLength = urlConnection.getContentLength(); 

       if (urlFileLength == 169 || urlFileLength == 0 || urlFileLength == -1) { 
        error = getResources().getStringArray(R.array.errors)[5]; 
        return false; 
       } 
       if (urlFileLength == localFileLength) { 
        error = getResources().getString(R.string.file_exist); 
        return false; 
       } else { 
        publishProgress(0, urlFileLength); 
        InputStream in = urlConnection.getInputStream(); 
        OutputStream out = new FileOutputStream(FILE_NAME); 

        while((len=in.read(bytes))!=-1) { 
         if(!isCancelled()) { 
          out.write(bytes, 0, len); 
          fullProgress += len; 
          publishProgress(fullProgress); 
         } else { 
          new File(FILE_NAME).delete(); 
          error = getResources().getString(R.string.stopped); 
          return false;        
         } 
        } 

       } 

      } catch (MalformedURLException e) { 
       new File(FILE_NAME).delete(); 
       error = getResources().getStringArray(R.array.errors)[2]; 
      } catch (IOException e) { 
       new File(FILE_NAME).delete(); 
       error = getResources().getStringArray(R.array.errors)[3]; 
      } 



      return true; 
     } 

     @Override 
     protected void onProgressUpdate(Integer ... progress) { 
      int tmp; 

      if (progress.length==2) { 
       progressDialog.setProgress(progress[0]); 
       progressDialog.setMax(progress[1]); 
      } else if(progress.length==1) { 
       if(!progressDialog.isShowing()) { 
        if(!notificated) { 
         nId = NotificationUtils.getInstace(MusicActivity.this).createDownloadNotification(data.getName(itemId)); 
         notificated = true; 
        } else { 
         tmp = (int) (progress[0]/(urlFileLength*0.01)); 
         if(progressPercent!=tmp) { 
          progressPercent = tmp; 
          NotificationUtils.getInstace(MusicActivity.this).updateProgress(nId, progressPercent); 
         } 
        } 
       } else { 
        progressDialog.setProgress(progress[0]); 
       } 
      } 
     } 

     @Override 
     protected void onPostExecute(Boolean result) { 
      if(result==true && error == null) { 
       if(progressDialog.isShowing()) { 
        IO.showNotify(MusicActivity.this, getResources().getString(R.string.downloaded) + " " + PATH); 
        progressDialog.dismiss(); 
       } else if (nId!=-1) { 
        NotificationUtils.getInstace(MusicActivity.this).cancelNotification(nId); 
        NotificationUtils.getInstace(MusicActivity.this).createMessageNotification(data.getName(itemId) + " " + getResources().getString(R.string.finished)); 
       } 
      } else { 
       if(progressDialog.isShowing()) { 
        IO.showNotify(MusicActivity.this, error); 
        progressDialog.dismiss(); 
       } else if (nId!=-1){ 
        NotificationUtils.getInstace(MusicActivity.this).cancelNotification(nId); 
        NotificationUtils.getInstace(MusicActivity.this).createMessageNotification(getResources().getString(R.string.error) + "! " + error); 
       } 
      } 

     } 

     @Override 
     protected void onCancelled() { 
      IO.showNotify(MusicActivity.this, getResources().getString(R.string.stopped)); 
     } 

    }; 

    if(downloadTask.getStatus().equals(AsyncTask.Status.PENDING) || downloadTask.getStatus().equals(AsyncTask.Status.FINISHED)) 
     downloadTask.execute(); 
} 

И есть два метода Thats создающего уведомления:

public int createDownloadNotification(String fileName) { 
    String text = context.getString(R.string.notification_downloading).concat(" ").concat(fileName); 
    RemoteViews contentView = createProgressNotification(text, text); 
    contentView.setImageViewResource(R.id.notification_download_layout_image, android.R.drawable.stat_sys_download); 

    return lastId++; 
} 


private RemoteViews createProgressNotification(String text, String topMessage) { 
    Notification notification = new Notification(android.R.drawable.stat_sys_download, topMessage, System.currentTimeMillis()); 
    RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.notification_download_layout); 
    contentView.setProgressBar(R.id.notification_download_layout_progressbar, 100, 0, false); 
    contentView.setTextViewText(R.id.notification_download_layout_title, text); 

    notification.contentView = contentView; 
    notification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT | Notification.FLAG_ONLY_ALERT_ONCE; 

    Intent notificationIntent = new Intent(context, NotificationUtils.class); 
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); 

    notification.contentIntent = contentIntent; 

    manager.notify(lastId, notification); 
    notifications.put(lastId, notification); 

    return contentView; 
} 

Помогите мне пожалуйста ...

ответ

0

Я не уверен, , но в моем коде уведомления у меня нет notification.contentIntent = contentIntent;, и вам, кажется, не хватает этого до строки manager.notify(lastId, notification);:

notification.setLatestEventInfo(context, MyNotifyTitle, MyNotifiyText, contentIntent); 

MyNotifyTitle - это название уведомления, MyNotifyText - это текст. Добавьте их до contentIntent как

MyIntent.putExtra("extendedTitle", notificationIntent); 
MyIntent.putExtra("extendedText" , notificationIntent); 

Надеюсь, это поможет.

+0

способ комплектLatestEventInfo (...) лишен, поэтому я этого не сделал. И я думаю, что ты не поймал мою проблему. Я хочу сделать это: после создания уведомления, если пользователь нажмет на уведомление, затем вернитесь к потоку, который его создал, и запустите progressDialog.show(); КАК? :( – ruslanys

+0

О, да, я поймаю тебя. Я попробую, спасибо – ruslanys

+0

Да, извините, я неправильно понял вашу проблему, не могу помочь. – erdomester

Смежные вопросы